Ejemplo n.º 1
0
        public void ComplexPatching()
        {
            using (var documentStore = this.NewDocumentStore()) {
                #region scriptedpatching1
                var blogComment = new BlogComment() {
                    Title = "Awesome Feature",
                    Content = @"ScriptedPatchRequest is the greatest thing since sliced bread."
                };

                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest() {
                        Script = @"this.Comments.push(newComment)",
                        Values = { { "newComment", blogComment } }
                });
                #endregion

                #region scriptedpatching2
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest() {
                        Script = "this.Tags.Remove(tagToRemove)",
                        Values = { { "tagToRemove", "Interesting" } }
                    });
                #endregion

                #region scriptedpatching3
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest() {
                        Script = @"
                            this.Comments.RemoveWhere(function(comment) {
                                return comment.Content === 'Spam'
                            });
                        "
                    });
                #endregion
            }
        }
Ejemplo n.º 2
0
 public ActionResult Comment([Bind(Include = "ArticleId, Message")] string Slug, BlogComment blogComment)
 {
     if (ModelState.IsValid)
     {
         if (blogComment.Message != null)
         {
             blogComment.AuthorId   = User.Identity.GetUserId();
             blogComment.CreateDate = DateTimeOffset.Now;
             blogComment.UpdateDate = DateTimeOffset.Now;
             db.Comment.Add(blogComment);
             db.SaveChanges();
         }
     }
     return(RedirectToAction("Details", new { Slug = Slug }));
 }
Ejemplo n.º 3
0
        public void SimplePatching()
        {
            using (var documentStore = this.NewDocumentStore())
            {
                #region patching1
                var comment = new BlogComment
                {
                    Title   = "Foo",
                    Content = "Bar"
                };

                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new[]
                {
                    new PatchRequest
                    {
                        Type  = PatchCommandType.Add,
                        Name  = "Comments",
                        Value = RavenJObject.FromObject(comment)
                    }
                });

                #endregion

                #region patching2
                // Setting a native type value
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new[]
                {
                    new PatchRequest
                    {
                        Type  = PatchCommandType.Set,
                        Name  = "Title",
                        Value = RavenJObject.FromObject("New title")
                    }
                });

                // Setting an object as a property value
                documentStore.DatabaseCommands.Patch(
                    "blogposts/4321",
                    new[]
                {
                    new PatchRequest
                    {
                        Type  = PatchCommandType.Set,
                        Name  = "Author",
                        Value = RavenJObject.FromObject(
                            new BlogAuthor
                        {
                            Name     = "Itamar",
                            ImageUrl = "/author_images/itamar.jpg"
                        })
                    }
                });

                #endregion

                #region patching3
                // This is how you rename a property; copying works
                // exactly the same, but with Type = PatchCommandType.Copy
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new[]
                {
                    new PatchRequest
                    {
                        Type  = PatchCommandType.Rename,
                        Name  = "Comments",
                        Value = new RavenJValue("cmts")
                    }
                });

                #endregion

                #region patching4
                // Assuming we have a Views counter in our entity
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new[]
                {
                    new PatchRequest
                    {
                        Type  = PatchCommandType.Inc,
                        Name  = "Views",
                        Value = new RavenJValue(1)
                    }
                });

                #endregion

                #region patching_arrays1
                // Append a new comment; Insert operation is supported
                // as well, by using PatchCommandType.Add and
                // specifying a Position to insert at
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new[]
                {
                    new PatchRequest
                    {
                        Type  = PatchCommandType.Add,
                        Name  = "Comments",
                        Value =
                            RavenJObject.FromObject(new BlogComment
                        {
                            Content = "FooBar"
                        })
                    }
                });

                // Remove the first comment
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new[]
                {
                    new PatchRequest
                    {
                        Type     = PatchCommandType.Remove,
                        Name     = "Comments",
                        Position = 0
                    }
                });

                #endregion

                var doc = new RavenJObject();

                #region nested1
                var addToPatchedDoc = new JsonPatcher(doc).Apply(
                    new[]
                {
                    new PatchRequest
                    {
                        Type   = PatchCommandType.Modify,
                        Name   = "user",
                        Nested = new[]
                        {
                            new PatchRequest {
                                Type = PatchCommandType.Set, Name = "name", Value = new RavenJValue("rahien")
                            },
                        }
                    },
                });

                #endregion

                #region nested2
                var removeFromPatchedDoc = new JsonPatcher(doc).Apply(
                    new[]
                {
                    new PatchRequest
                    {
                        Type    = PatchCommandType.Modify,
                        Name    = "user",
                        PrevVal = RavenJObject.Parse(@"{ ""name"": ""ayende"", ""id"": 13}"),
                        Nested  = new[]
                        {
                            new PatchRequest {
                                Type = PatchCommandType.Unset, Name = "name"
                            },
                        }
                    },
                });

                #endregion
            }
        }
Ejemplo n.º 4
0
        public ActionResult BlogCommentAdd(int blogPostId, BlogPostModel model, bool captchaValid)
        {
            if (!_blogSettings.Enabled)
            {
                return(HttpNotFound());
            }

            var blogPost = _blogService.GetBlogPostById(blogPostId);

            if (blogPost == null || !blogPost.AllowComments)
            {
                return(HttpNotFound());
            }

            if (_workContext.CurrentCustomer.IsGuest() && !_blogSettings.AllowNotRegisteredUsersToLeaveComments)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Blog.Comments.OnlyRegisteredUsersLeaveComments"));
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage && !captchaValid)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptcha"));
            }

            if (ModelState.IsValid)
            {
                var comment = new BlogComment
                {
                    BlogPostId  = blogPost.Id,
                    CustomerId  = _workContext.CurrentCustomer.Id,
                    IpAddress   = _webHelper.GetCurrentIpAddress(),
                    CommentText = model.AddNewComment.CommentText,
                    IsApproved  = true
                };
                _customerContentService.InsertCustomerContent(comment);

                //update totals
                _blogService.UpdateCommentTotals(blogPost);

                //notify a store owner
                if (_blogSettings.NotifyAboutNewBlogComments)
                {
                    _workflowMessageService.SendBlogCommentNotificationMessage(comment, _localizationSettings.DefaultAdminLanguageId);
                }

                //activity log
                _customerActivityService.InsertActivity("PublicStore.AddBlogComment", _localizationService.GetResource("ActivityLog.PublicStore.AddBlogComment"));

                NotifySuccess(T("Blog.Comments.SuccessfullyAdded"));

                var url = UrlHelper.GenerateUrl(
                    routeName: "BlogPost",
                    actionName: null,
                    controllerName: null,
                    protocol: null,
                    hostName: null,
                    fragment: "new-comment",
                    routeValues: new RouteValueDictionary(new { blogPostId = blogPost.Id, SeName = blogPost.GetSeName(blogPost.LanguageId, ensureTwoPublishedLanguages: false) }),
                    routeCollection: System.Web.Routing.RouteTable.Routes,
                    requestContext: this.ControllerContext.RequestContext,
                    includeImplicitMvcValues: true /*helps fill in the nulls above*/
                    );

                return(Redirect(url));
            }

            //If we got this far, something failed, redisplay form
            PrepareBlogPostModel(model, blogPost, true);
            return(View(model));
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Inserts a blog comment
 /// </summary>
 /// <param name="blogComment">Blog comment</param>
 public virtual void InsertBlogComment(BlogComment blogComment)
 {
     _blogCommentRepository.Insert(blogComment);
 }
Ejemplo n.º 6
0
 public void DeleteComment(BlogComment img)
 {
     _context.BlogComments.Remove(img);
     _context.SaveChanges();
 }
Ejemplo n.º 7
0
		public void ComplexPatching()
		{
			using (var documentStore = this.NewDocumentStore())
			{
				#region scriptedpatching1
				var blogComment = new BlogComment()
				{
					Title = "Awesome Feature",
					Content = @"ScriptedPatchRequest is the greatest thing since sliced bread."
				};

				documentStore.DatabaseCommands.Patch(
					"blogposts/1234",
					new ScriptedPatchRequest()
					{
						Script = @"this.Comments.push(newComment)",
						Values = { { "newComment", blogComment } }
					});
				#endregion

				#region scriptedpatching_get_id
				documentStore.DatabaseCommands.Patch(
					"blogposts/1234",
					new ScriptedPatchRequest()
					{
						Script = "var currentDocId = this.__document_id;"
					});
				#endregion

				#region scriptedpatching_remove
				documentStore.DatabaseCommands.Patch(
					"blogposts/1234",
					new ScriptedPatchRequest()
					{
						Script = "this.Tags.Remove(tagToRemove)",
						Values = { { "tagToRemove", "Interesting" } }
					});
				#endregion

				#region scriptedpatching_remove_where
				documentStore.DatabaseCommands.Patch(
					"blogposts/1234",
					new ScriptedPatchRequest()
					{
						Script = @"
							this.Comments.RemoveWhere(function(comment) { 
								return comment.Content === 'Spam' 
							});
						"
					});
				#endregion

				#region scriptedpatching_map
				documentStore.DatabaseCommands.Patch(
					"blogposts/1234",
					new ScriptedPatchRequest()
					{
						Script = @"
							this.Comments.Map(function(comment) {   
								if(comment.Content.indexOf(""Raven"") != -1)
								{
									comment.Title = ""[Raven] "" + comment.Title;
								}
								return comment;
							});
						"
					});
				#endregion

				#region scriptedpatching_load
				documentStore.DatabaseCommands.Patch(
					"blogposts/1234",
					new ScriptedPatchRequest()
					{
						Script = @"
							var author = LoadDocument(this.Author.Id);
							this.AuthorName = author.FirstName + ' ' + author.LastName;
						"
					});
				#endregion

				#region scriptedpatching_put
				documentStore.DatabaseCommands.Patch(
					"blogposts/1234",
					new ScriptedPatchRequest()
					{
						Script = @"
							PutDocument('titles/' + this.Title,
										{ 'PostId' : this.Id }, 
										{ 'MetadataAuthorValue' : this.Author }
							);
						"
					});
				#endregion

				#region scriptedpatching_trim
				documentStore.DatabaseCommands.Patch(
					"blogposts/1234",
					new ScriptedPatchRequest()
					{
						Script = @"
							this.Title = this.Title.trim();
						"
					});
				#endregion

				#region scriptedpatching_lodash
				documentStore.DatabaseCommands.Patch(
					"blogposts/1234",
					new ScriptedPatchRequest()
					{
						Script = @"_(this.Comments).forEach(function(comment){
							PutDocument('CommentAuthors/', { 'Author' : comment.Author }
							);
						});"
					});
				#endregion
				

				#region scriptedpatching_debug

				var patchOutput = documentStore.DatabaseCommands.Patch(
					"blogposts/1234",
					new ScriptedPatchRequest
					{
						Script = @"
							output(this.AuthorName);

							this.NumberOfViews += 1;
							output(this.NumberOfViews);
						"
					});

				var debugInfo = patchOutput.Value<RavenJArray>("Debug");

				foreach (var debug in debugInfo)
				{
					Console.WriteLine("Patch debug: " + debug);
				}
				#endregion


			}
		}
Ejemplo n.º 8
0
 public Task <BlogRevision> GetLastRevisionAsync(BlogComment comment)
 {
     return(Context.Set <BlogRevision>()
            .Where(r => r.CommentId == comment.Id && r.Version == comment.Revision)
            .SingleOrDefaultAsync());
 }
Ejemplo n.º 9
0
 public void PostBlogComment(BlogComment comment)
 {
     _context.BlogComments.Add(comment);
     _context.SaveChanges();
 }
 public PreSubmissionCommentEventArgs(BlogComment blogComment)
 {
     BlogComment        = blogComment;
     CommentReplacement = String.Empty;
 }
Ejemplo n.º 11
0
 public virtual void AddBlogCommentTokens(IList <Token> tokens, BlogComment blogComment)
 {
     tokens.Add(new Token("BlogComment.BlogPostTitle", blogComment.BlogPost.Title));
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Deletes a blog comment
 /// </summary>
 /// <param name="blogComment">Blog comment</param>
 public void DeleteBlogComment([FromBody] BlogComment blogComment)
 {
     _blogService.DeleteBlogComment(blogComment);
 }
Ejemplo n.º 13
0
 public bool SendCommentEmail(Note note, BlogComment comment, long userId, string content)
 {
     throw new Exception();
 }
Ejemplo n.º 14
0
        public ActionResult BlogCommentAdd(string blogPostId, BlogPostModel model, bool captchaValid)
        {
            if (!_blogSettings.Enabled)
            {
                return(RedirectToRoute("HomePage"));
            }

            var blogPost = _blogService.GetBlogPostById(blogPostId);

            if (blogPost == null || !blogPost.AllowComments)
            {
                return(RedirectToRoute("HomePage"));
            }

            if (_workContext.CurrentCustomer.IsGuest() && !_blogSettings.AllowNotRegisteredUsersToLeaveComments)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Blog.Comments.OnlyRegisteredUsersLeaveComments"));
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

            if (ModelState.IsValid)
            {
                var comment = new BlogComment
                {
                    BlogPostId    = blogPost.Id,
                    CustomerId    = _workContext.CurrentCustomer.Id,
                    CommentText   = model.AddNewComment.CommentText,
                    CreatedOnUtc  = DateTime.UtcNow,
                    BlogPostTitle = blogPost.Title,
                };
                _blogService.InsertBlogComment(comment);
                //update totals
                blogPost.CommentCount = _blogService.GetBlogCommentsByBlogPostId(blogPost.Id).Count;
                _blogService.UpdateBlogPost(blogPost);
                if (!_workContext.CurrentCustomer.IsHasBlogComments)
                {
                    _workContext.CurrentCustomer.IsHasBlogComments = true;
                    EngineContext.Current.Resolve <ICustomerService>().UpdateHasBlogComments(_workContext.CurrentCustomer.Id);
                }
                //notify a store owner
                if (_blogSettings.NotifyAboutNewBlogComments)
                {
                    _workflowMessageService.SendBlogCommentNotificationMessage(comment, _localizationSettings.DefaultAdminLanguageId);
                }

                //activity log
                _customerActivityService.InsertActivity("PublicStore.AddBlogComment", comment.Id, _localizationService.GetResource("ActivityLog.PublicStore.AddBlogComment"));

                //The text boxes should be cleared after a comment has been posted
                //That' why we reload the page
                TempData["nop.blog.addcomment.result"] = _localizationService.GetResource("Blog.Comments.SuccessfullyAdded");
                return(RedirectToRoute("BlogPost", new { SeName = blogPost.GetSeName(blogPost.LanguageId, ensureTwoPublishedLanguages: false) }));
            }

            //If we got this far, something failed, redisplay form
            PrepareBlogPostModel(model, blogPost, true);
            return(View(model));
        }
Ejemplo n.º 15
0
 public BlogCommentApprovedEvent(BlogComment blogComment)
 {
     this.BlogComment = blogComment;
 }
        public async Task AddBlogCommentTokens(LiquidObject liquidObject, BlogPost blogPost, BlogComment blogComment, Store store, Language language)
        {
            var liquidBlogComment = new LiquidBlogComment(blogComment, blogPost, store, language);

            liquidObject.BlogComment = liquidBlogComment;
            await _mediator.EntityTokensAdded(blogComment, liquidBlogComment, liquidObject);
        }
Ejemplo n.º 17
0
        public ActionResult BlogCommentAdd(int blogPostId, BlogPostModel model, bool captchaValid)
        {
            if (!_blogSettings.Enabled)
            {
                return(RedirectToRoute("HomePage"));
            }

            var blogPost = _blogService.GetBlogPostById(blogPostId);

            if (blogPost == null || !blogPost.AllowComments)
            {
                return(RedirectToRoute("HomePage"));
            }

            if (_workContext.CurrentCustomer.IsGuest() && !_blogSettings.AllowNotRegisteredUsersToLeaveComments)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Blog.Comments.OnlyRegisteredUsersLeaveComments"));
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage && !captchaValid)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptcha"));
            }

            if (ModelState.IsValid)
            {
                var comment = new BlogComment()
                {
                    BlogPostId   = blogPost.Id,
                    CustomerId   = _workContext.CurrentCustomer.Id,
                    IpAddress    = _webHelper.GetCurrentIpAddress(),
                    CommentText  = model.AddNewComment.CommentText,
                    IsApproved   = true,
                    CreatedOnUtc = DateTime.UtcNow,
                    UpdatedOnUtc = DateTime.UtcNow,
                };
                _customerContentService.InsertCustomerContent(comment);

                //update totals
                _blogService.UpdateCommentTotals(blogPost);

                //notify a store owner
                if (_blogSettings.NotifyAboutNewBlogComments)
                {
                    _workflowMessageService.SendBlogCommentNotificationMessage(comment, _localizationSettings.DefaultAdminLanguageId);
                }

                //activity log
                _customerActivityService.InsertActivity("PublicStore.AddBlogComment", _localizationService.GetResource("ActivityLog.PublicStore.AddBlogComment"));

                //The text boxes should be cleared after a comment has been posted
                //That' why we reload the page
                TempData["nop.blog.addcomment.result"] = _localizationService.GetResource("Blog.Comments.SuccessfullyAdded");
                return(RedirectToRoute("BlogPost", new { blogPostId = blogPost.Id, SeName = blogPost.GetSeName() }));
            }

            //If we got this far, something failed, redisplay form
            PrepareBlogPostModel(model, blogPost, true);
            return(View(model));
        }
Ejemplo n.º 18
0
            public static List<BlogComment> getComment(Account account, string blog_id, string log_no)
            //public static string getComment(Account account, string blog_id, string log_no)
            {
                List<BlogComment> rtn = new List<BlogComment>();
                BlogComment cmt;
                string data;
                HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
                int page_max;

                data = Tool.webGet($"http://blog.naver.com/CommentList.nhn?blogId={blog_id}&logNo={log_no}");
                html.LoadHtml(data);

                //댓글 페이지 수 체크
                if (html.DocumentNode.SelectSingleNode("//div[@class='cc_paginate cmt']") == null)
                {
                    page_max = 1;
                }
                else
                {
                    page_max = 1;
                    //페이지 두개 이상 개발 보류
                }

                foreach (HtmlNode node in html.DocumentNode.SelectNodes("//li[@id]"))
                {
                    if (!node.GetAttributeValue("id", "").Contains("postComment"))
                        continue;

                    cmt = new BlogComment();
                    cmt.blog_id = blog_id;
                    cmt.log_no = log_no;

                    if (node.GetAttributeValue("issecret", "").Contains("true"))
                    {
                        //비밀댓글
                        cmt.secret = true;
                        rtn.Add(cmt);
                        continue;
                    }

                    HtmlNode dt = node.SelectSingleNode("dl/dt[@class='h']");
                    HtmlNode a = dt.SelectSingleNode("a");
                    string href = a.GetAttributeValue("href", "");
                    string nick = a.InnerText.Trim();

                    if (href.Contains("/DomainDispatcher"))
                        cmt.writer_blog_id = Tool.splitEx(href, "&id=", "&");
                    else if (href.Contains("blog.naver.com/"))
                        cmt.writer_blog_id = Tool.splitEx(href, "naver.com/", "");
                    if (nick.Length > 0)
                        cmt.nick = nick;

                    HtmlNode span = dt.SelectSingleNode("span");
                    if (dt.GetAttributeValue("class", "").Contains("date"))
                        cmt.date = DateTime.Parse(span.InnerText.Trim());

                    HtmlNode dd = node.SelectSingleNode("dl/dd[@class]");
                    if (dd.GetAttributeValue("id", "").Contains("comment"))
                        cmt.content = dd.InnerText.Trim();

                    rtn.Add(cmt);
                }

                if (rtn.Count > 0)
                    return rtn;
                else
                    return null;
            }
Ejemplo n.º 19
0
 /// <summary>
 /// Sends a blog comment notification message to a store owner
 /// </summary>
 /// <param name="blogComment">Blog comment</param>
 /// <param name="languageId">Message language identifier</param>
 /// <returns>Queued email identifier</returns>
 public int SendBlogCommentNotificationMessage(BlogComment blogComment, int languageId)
 {
     return(_workflowMessageService.SendBlogCommentNotificationMessage(blogComment, languageId));
 }
Ejemplo n.º 20
0
 public void CreateComment(BlogComment model)
 {
     model.CreatedAt = DateTime.Now;
     _context.BlogComments.Add(model);
     _context.SaveChanges();
 }
Ejemplo n.º 21
0
 public BlogCommentedDomainEvent(BlogComment blogComment)
 {
     BlogComment = blogComment;
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Deletes a blog comment
 /// </summary>
 /// <param name="blogComment">Blog comment</param>
 public virtual void DeleteBlogComment(BlogComment blogComment)
 {
     _blogCommentRepository.Delete(blogComment);
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Inserts a blog comment
 /// </summary>
 /// <param name="blogComment">Blog comment</param>
 /// <returns>A task that represents the asynchronous operation</returns>
 public virtual async Task InsertBlogCommentAsync(BlogComment blogComment)
 {
     await _blogCommentRepository.InsertAsync(blogComment);
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Update a blog comment
 /// </summary>
 /// <param name="blogComment">Blog comment</param>
 public virtual void UpdateBlogComment(BlogComment blogComment)
 {
     _blogCommentRepository.Update(blogComment);
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Update a blog comment
 /// </summary>
 /// <param name="blogComment">Blog comment</param>
 /// <returns>A task that represents the asynchronous operation</returns>
 public virtual async Task UpdateBlogCommentAsync(BlogComment blogComment)
 {
     await _blogCommentRepository.UpdateAsync(blogComment);
 }
Ejemplo n.º 26
0
        public void SimplePatching()
        {
            using (var documentStore = this.NewDocumentStore())
            {
                #region patching1
                var comment = new BlogComment
                                {
                                    Title = "Foo",
                                    Content = "Bar"
                                };

                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new[]
                        {
                            new PatchRequest
                                {
                                    Type = PatchCommandType.Add,
                                    Name = "Comments",
                                    Value = RavenJObject.FromObject(comment)
                                }
                        });

                #endregion

                #region patching2
                // Setting a native type value
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new[]
                        {
                            new PatchRequest
                                {
                                    Type = PatchCommandType.Set,
                                    Name = "Title",
                                    Value = RavenJObject.FromObject("New title")
                                }
                        });

                // Setting an object as a property value
                documentStore.DatabaseCommands.Patch(
                    "blogposts/4321",
                    new[]
                        {
                            new PatchRequest
                                {
                                    Type = PatchCommandType.Set,
                                    Name = "Author",
                                    Value = RavenJObject.FromObject(
                                        new BlogAuthor
                                            {
                                                Name = "Itamar",
                                                ImageUrl = "/author_images/itamar.jpg"
                                            })
                                }
                        });

                #endregion

                #region patching3
                // This is how you rename a property; copying works
                // exactly the same, but with Type = PatchCommandType.Copy
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new[]
                        {
                            new PatchRequest
                                {
                                    Type = PatchCommandType.Rename,
                                    Name = "Comments",
                                    Value = new RavenJValue("cmts")
                                }
                        });

                #endregion

                #region patching4
                // Assuming we have a Views counter in our entity
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new[]
                        {
                            new PatchRequest
                                {
                                    Type = PatchCommandType.Inc,
                                    Name = "Views",
                                    Value = new RavenJValue(1)
                                }
                        });

                #endregion

                #region patching_arrays1
                // Append a new comment; Insert operation is supported
                // as well, by using PatchCommandType.Add and
                // specifying a Position to insert at
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new[]
                        {
                            new PatchRequest
                                {
                                    Type = PatchCommandType.Add,
                                    Name = "Comments",
                                    Value =
                                        RavenJObject.FromObject(new BlogComment
                                                                    {Content = "FooBar"})
                                }
                        });

                // Remove the first comment
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new[]
                        {
                            new PatchRequest
                                {
                                    Type = PatchCommandType.Remove,
                                    Name = "Comments",
                                    Position = 0
                                }
                        });

                #endregion

                var doc = new RavenJObject();

                #region nested1
                var addToPatchedDoc = new JsonPatcher(doc).Apply(
                    new[]
                {
                    new PatchRequest
                    {
                        Type = PatchCommandType.Modify,
                        Name = "user",
                        Nested = new[]
                        {
                            new PatchRequest {Type = PatchCommandType.Set, Name = "name", Value = new RavenJValue("rahien")},
                        }
                    },
                });

                #endregion

                #region nested2
                var removeFromPatchedDoc = new JsonPatcher(doc).Apply(
                new[]
                {
                    new PatchRequest
                    {
                        Type = PatchCommandType.Modify,
                        Name = "user",
                        PrevVal = RavenJObject.Parse(@"{ ""name"": ""ayende"", ""id"": 13}"),
                        Nested = new[]
                        {
                            new PatchRequest {Type = PatchCommandType.Unset, Name = "name" },
                        }
                    },
                });

                #endregion
            }
        }
 /// <summary>
 /// Sends a blog comment notification message to a store owner
 /// </summary>
 public static CreateMessageResult SendBlogCommentNotificationMessage(this IMessageFactory factory, BlogComment blogComment, int languageId = 0)
 {
     Guard.NotNull(blogComment, nameof(blogComment));
     return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.BlogCommentStoreOwner, languageId, customer: blogComment.Customer), true, blogComment));
 }
Ejemplo n.º 28
0
        public void ComplexPatching()
        {
            using (var documentStore = this.NewDocumentStore())
            {
                #region scriptedpatching1
                var blogComment = new BlogComment()
                {
                    Title   = "Awesome Feature",
                    Content = @"ScriptedPatchRequest is the greatest thing since sliced bread."
                };

                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest()
                {
                    Script = @"this.Comments.push(newComment)",
                    Values = { { "newComment", blogComment } }
                });
                #endregion

                #region scriptedpatching_get_id
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest()
                {
                    Script = "var currentDocId = this.__document_id;"
                });
                #endregion

                #region scriptedpatching_remove
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest()
                {
                    Script = "this.Tags.Remove(tagToRemove)",
                    Values = { { "tagToRemove", "Interesting" } }
                });
                #endregion

                #region scriptedpatching_remove_where
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest()
                {
                    Script = @"
							this.Comments.RemoveWhere(function(comment) { 
								return comment.Content === 'Spam' 
							});
						"
                });
                #endregion

                #region scriptedpatching_map
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest()
                {
                    Script = @"
							this.Comments.Map(function(comment) {   
								if(comment.Content.indexOf(""Raven"") != -1)
								{
									comment.Title = ""[Raven] "" + comment.Title;
								}
								return comment;
							});
						"
                });
                #endregion

                #region scriptedpatching_load
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest()
                {
                    Script = @"
							var author = LoadDocument(this.Author.Id);
							this.AuthorName = author.FirstName + ' ' + author.LastName;
						"
                });
                #endregion

                #region scriptedpatching_put
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest()
                {
                    Script = @"
							PutDocument('titles/' + this.Title,
										{ 'PostId' : this.Id }, 
										{ 'MetadataAuthorValue' : this.Author }
							);
						"
                });
                #endregion

                #region scriptedpatching_trim
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest()
                {
                    Script = @"
							this.Title = this.Title.trim();
						"
                });
                #endregion

                #region scriptedpatching_lodash
                documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest()
                {
                    Script = @"_(this.Comments).forEach(function(comment){
							PutDocument('CommentAuthors/', { 'Author' : comment.Author }
							);
						});"
                });
                #endregion


                #region scriptedpatching_debug

                var patchOutput = documentStore.DatabaseCommands.Patch(
                    "blogposts/1234",
                    new ScriptedPatchRequest
                {
                    Script = @"
							output(this.AuthorName);

							this.NumberOfViews += 1;
							output(this.NumberOfViews);
						"
                });

                var debugInfo = patchOutput.Value <RavenJArray>("Debug");

                foreach (var debug in debugInfo)
                {
                    Console.WriteLine("Patch debug: " + debug);
                }
                #endregion
            }
        }
Ejemplo n.º 29
0
        public static async Task AddSeedBlogs(IServiceProvider services)
        {
            var context = services.GetRequiredService <AppDbContext>();

            Random random = new Random();

            int[] blogCat = { 1, 1, 1, 2, 2, 3, 3, 3, 6, 6, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4 };

            string[] bodyAr =
            {
                "طبق شهي و لذيذ شكله جميل يمكن تحضيره من الخضار المتواجدة دائما في المطبخ العربي",
                " المقبلات أو المشهيات أو المزة (في الشام) أو المفتحات (في تونس) هي مادة غذائية من الخضار أو الفاكهة تكون مطبوخا أو مخللا أو مفرومًا وعادة ما يُستخدم كـتوابل خصوصًا لتجميل الطبق الرئيسي. ",
                "المخلل من التخليل (خلّله) أي وضعه في مادة تخلّله فالخيار مثلاً ينقع في الماء والملح في إناء مضغوط ومسحوب منه الهواء لفترة أسبوع",

                "ختبر الإنسانُ السَّفر منذ بداية وجوده على المعمورة، حيث كان مضطرًّا للتنقُّل بحثًا عن الماء والطَّعام، ثمَّ استمرَّ في ذلك بعد أنْ أصبح في غنيةٍ عن مشقَّة الطَّريق، فقد فطرتِ النَّفس البشريَّة",
                "إيجابيات السَّفر وسلبياته والمشاعر يحكمها طبع الإنسان من جهةٍ وطبيعة سفره وحاله من جهةٍ أخرى؛ فمن خبر محاسن الغربة ووجد فيها ملاذًا مطمئنًا له",

                "فيروز مغنية لبنانية. اسمها الحقيقي «نهاد رزق وديع حداد»، ولدت في نوفمبر من سنة 1935 في حي يسمى 《زقاق البلاط》 في بيروت، قدمت العديد من الأغاني والأوبريهات",
                "ليلى مراد مغنية وممثلة مصرية، تعتبر من أبرز المغنيات والممثلات في الوطن العربي في القرن العشرين. بدأت مشوارها مع الغناء في سن أربعة عشر عامًا",
                "سيد درويش مغني وملحن مصري اسمه الحقيقي السيد درويش البحر هو مجدد الموسيقى وباعث النهضة[؟] الموسيقية في مصر والوطن العربي. بدأ ينشد مع أصدقائه ألحان الشيخ",

                "لألعاب الأولمبية الصيفية ، أو ألعاب الأولمبياد الصيفية ، هي حدث رياضي يقام كل أربع سنوات لممارسة الألعاب الأولمبية",
                " ليبرون جيمس حل أولاً بين لاعبي NBA وفي المركز الثاني عامة بعد كريستيانو رونالدو نجم الريال الذي تصدّر القائمة. في حين حلّ كيفن دورانت في المركز الثامن.",

                "وعرف اللياقة البدنية Clarke، 1976 على أنها القدرة على القيام بالأعباء اليومية بقوة ووعي وبدون تعب لا مبرر له من توافر قدر كاف ممن الطاقة",
                "هي السمات البدنية التي على الفرد تحقيقها للقيام بالأعمال اليومية الاعتيادية بأفضل كفاءة دون الشعور بالتعب والإرهاق الشديد. هي الأعمال اليومية على بساطتها، لكنها قد تزداد تعقيدا لتشمل الرياضات التنافسية والنشاطات الأكثر صعوبة.",
                "المرونة هي قدرة المفصل على الحركة لأبعد مدى ضمن نطاق حركته! ومن الأمثلة على التمارين التي تحسن المرونة تمارين اليوغا وشد الجسم. مثلاً، قم بوضع قدميك على الأرض مع جعل مسافة بينهما",

                "المِرِّيخ أو الكوكب الأحمر هو الكوكب الرابع من حيث البعد عن الشمس في النظام الشمسي وهو الجار الخارجي للأرض ويصنف كوكبا صخريا",
                "مذبحة القلعة، أو مذبحة المماليك هي حادثة تاريخيَّة وقعت في ولاية مصر العثمانية دبرها محمد علي باشا للتخلص من أعدائه المماليك يوم الجمعة 5 صفر سنة 1226 هـ الموافق 1 مارس",
                "اعتقلت الولايات المتحدة الأمريكية أكثر من 779 معتقلاً إدارياً خارج نطاق القضاء في معتقل غوانتانامو الأمريكي في كوبا منذ فتح معسكرات الاعتقال في 11 يناير 2002",
                "الحركة الثقافية هي كل تغيير في طريقة التفكير والاعتقادات السائدة بخصوص مجموعة من القضايا الثقافية ذات العلاقة بنواحٍ وفروع معينة، مما يترتب عليه تغيير في طريقة مقاربة ومعالجة العمل",
                "الهندسة التطبيقية تعني تطبيق العلم لتوفير الحاجات الإنسانية. وذلك من خلال تطبيق العلوم النظرية والتطبيقية: الفيزياء، الكيمياء، الرياضيات، والأحياء.",
                "الإنسان الآلي أوالروبوت (بالإنجليزية: Robot)‏ عبارة عن أداة ميكانيكية قادرة على القيام بفعاليات مبرمجة سلفا ويقوم الإنسان الآلي بإنجاز تلك الفعاليات",
                "إمحوتب هو بانى هرم زوسر المدرج وهو أول مهندس معمارى ، وأحد أشهر المهندسين في مصر القديمة ، رفع إلى درجة معبود بعد وفاتة وأصبح إله الطب ."
            };

            string[] bodyDe =
            {
                "Ein köstliches und köstliches Gericht mit einer schönen Form, das aus dem Gemüse zubereitet werden kann, das in der arabischen Küche immer vorhanden ist",
                "Vorspeisen, Vorspeisen, Mezze (in der Levante) oder Moftahat (in Tunesien) ist ein Lebensmittel aus Gemüse oder Obst, das gekocht, eingelegt oder gehackt wird. Es wird normalerweise als Gewürz verwendet, insbesondere um das Hauptgericht zu verschönern.",
                "Die Gurke wird aus Beizen (Beizen) hergestellt, dh in eine Substanz gegeben, die damit gemischt ist. Die Gurke wird beispielsweise in einem Druckbehälter, der eine Woche lang Luft daraus zieht, in Wasser und Salz eingeweicht.",

                "Der Mensch erlebte Reisen von Beginn seiner Existenz auf dem Planeten an, als er gezwungen war, sich auf der Suche nach Wasser und Nahrung zu bewegen, und fuhr dann damit fort, nachdem er von den Strapazen der Straße reich geworden war, als die menschliche Seele unerträglich wurde.",
                "Die positiven und negativen Aspekte des Reisens und der Gefühle werden einerseits von der Natur eines Menschen und andererseits von der Art seiner Reise und seinem Zustand bestimmt. Aus den Nachrichten über die Vorteile der Entfremdung fand er darin einen beruhigenden Zufluchtsort für ihn.",

                "Fairouz ist eine libanesische Sängerin. Ihr richtiger Name ist  Nihad Rizk Wadih Haddad  . Sie wurde im November 1935 in einem Viertel namens Zuqaq El Blat in Beirut geboren. Sie spielte viele Lieder und Opern.",
                "Laila Murad ist eine ägyptische Sängerin und Schauspielerin. Sie gilt im 20. Jahrhundert als eine der bekanntesten Sängerinnen und Schauspielerinnen der arabischen Welt. Sie begann ihre Gesangskarriere im Alter von vierzehn Jahren.",
                "Sayed Darwish ist ein ägyptischer Sänger und Komponist, dessen richtiger Name Herr Darwish Al-Bahr ist. Er ist der Erneuerer der Musik und der Katalysator für die musikalische Renaissance [?] In Ägypten und der arabischen Welt.",

                "Die Olympischen Sommerspiele oder die Olympischen Sommerspiele sind ein Sportereignis, das alle vier Jahre für die Olympischen Spiele stattfindet.",
                "LeBron James wurde Erster unter den NBA-Spielern und im Allgemeinen Zweiter nach Cristiano Ronaldo, dem Star von Real Madrid, der die Liste anführte, während Kevin Durant Achter wurde.",

                "Er definierte Fitness von Clarke, 1976, als die Fähigkeit, tägliche Aufgaben mit Kraft, Bewusstsein und ohne übermäßige Müdigkeit aufgrund der Verfügbarkeit ausreichender Energie auszuführen.",
                "Sie sind die physischen Merkmale, die ein Individuum erreichen muss, um normale tägliche Aufgaben mit der besten Effizienz zu erledigen, ohne sich müde und erschöpft zu fühlen. Die täglichen Aufgaben sind einfach, aber sie können komplexer werden, um Leistungssport und schwierigere Aktivitäten einzuschließen.",
                "Flexibilität ist die Fähigkeit des Gelenks, sich innerhalb seines Bewegungsbereichs am weitesten zu bewegen! Beispiele für Übungen, die die Flexibilität verbessern, sind Yoga-Übungen, die den Körper dehnen. Stellen Sie beispielsweise Ihre Füße mit einem Abstand zwischen ihnen auf den Boden.",

                "Der Mars oder der rote Planet ist der vierte Planet in Bezug auf die Entfernung von der Sonne im Sonnensystem und der äußerste Nachbar der Erde. Er wird als felsiger Planet klassifiziert.",
                "Das Massaker an der Burg oder das Massaker an den Mamluken ist ein historischer Vorfall in der osmanischen Provinz Ägypten, der von Muhammad Ali Pascha geplant wurde, um seine Mamluk-Feinde am Freitag, dem 5. Safar 1226 AH, entsprechend dem 1. März, loszuwerden.",
                "Die Vereinigten Staaten von Amerika haben seit der Eröffnung der Haftlager am 11. Januar 2002 mehr als 779 außergerichtliche Verwaltungshäftlinge im Haftzentrum von Guantanamo Bay in Kuba festgenommen.",
                "Die kulturelle Bewegung ist jede Änderung der Denkweise und der vorherrschenden Überzeugungen in Bezug auf eine Gruppe kultureller Probleme, die sich auf bestimmte Aspekte und Zweige beziehen, was zu einer Änderung der Art und Weise führt, wie wir mit Arbeit umgehen und sie behandeln.",
                "Angewandte Technik bedeutet, Wissenschaft anzuwenden, um die Bedürfnisse des Menschen durch Anwendung theoretischer und angewandter Wissenschaften zu erfüllen: Physik, Chemie, Mathematik und Biologie.",
                "Ein Roboter oder ein Roboter (auf Englisch: Roboter) ist ein mechanisches Werkzeug, das vorprogrammierte Aktivitäten ausführen kann, und der Roboter führt diese Aktivitäten aus.",
                "Imhotep war der Erbauer der Stufenpyramide von Djoser, dem ersten Architekten und einer der berühmtesten Ingenieure im alten Ägypten. Nach seinem Tod wurde er zum Idol erhoben und zum Gott der Medizin."
            };

            var categiryList = new List <int>();

            // 1000*20=20000 Blogs
            for (int r = 0; r < 1000; r++)
            {
                for (var i = 0; i < bodyAr.Length; i++)
                {
                    var title     = bodyDe[i].Substring(0, 15);
                    var sTitle    = bodyDe[i].Substring(0, 30);
                    var body      = bodyDe[i];
                    var lngId     = LanguageCodeId[2];
                    var publiched = true;
                    var top       = false;

                    if (i % 2 == 0)
                    {
                        title  = bodyAr[i].Substring(0, 15);
                        sTitle = bodyAr[i].Substring(0, 30);
                        body   = bodyAr[i];
                        lngId  = LanguageCodeId[1];
                    }

                    if (i % 3 == 1)
                    {
                        publiched = false;
                    }
                    // to add some of blogs  of Top of the list
                    if ((r == 10 && i == 15) || (r == 15 && i == 6) || (r == 30 && i == 18))
                    {
                        top = true;
                    }


                    var daterelase = DateTime.Now;
                    var randNum    = random.Next(1, 100);
                    if (randNum == 1)
                    {
                        daterelase = DateTime.Now;
                    }
                    else if (randNum > 1 && randNum < 10)
                    {
                        daterelase = DateTime.Now.AddDays(-5);
                    }
                    else if (randNum > 10 && randNum < 20)
                    {
                        daterelase = DateTime.Now.AddDays(-10);
                    }
                    else if (randNum > 20 && randNum < 30)
                    {
                        daterelase = DateTime.Now.AddDays(-15);
                    }
                    else if (randNum > 30 && randNum < 40)
                    {
                        daterelase = DateTime.Now.AddDays(-20);
                    }
                    else if (randNum > 40 && randNum < 50)
                    {
                        daterelase = DateTime.Now.AddDays(-25);
                    }
                    else if (randNum > 50 && randNum < 60)
                    {
                        daterelase = DateTime.Now.AddDays(-30);
                    }
                    else if (randNum > 60 && randNum < 70)
                    {
                        daterelase = DateTime.Now.AddDays(-35);
                    }
                    else if (randNum > 70 && randNum < 80)
                    {
                        daterelase = DateTime.Now.AddDays(-40);
                    }
                    else if (randNum > 80 && randNum < 90)
                    {
                        daterelase = DateTime.Now.AddDays(-45);
                    }


                    // add new Blog
                    var newBlog = new Blog
                    {
                        Title         = title,
                        ShortTitle    = sTitle,
                        Body          = body,
                        Publish       = publiched,
                        Commentable   = true,
                        AtTop         = top,
                        ReleaseDate   = daterelase,
                        LanguageId    = lngId,
                        UserId        = superAdmin_id,
                        AddedDateTime = DateTime.Now
                    };
                    categiryList.Add(blogCat[i]);

                    context.Blog.Add(newBlog);
                }
            }
            await context.SaveChangesAsync();

            // get just the last 10000 blog to add categoryies and images to save time
            var blogs = context.Blog.Where(b => b.Publish == true).OrderByDescending(b => b.ReleaseDate).Take(10000).ToList();

            // Add Blogs categories
            foreach (var blog in blogs)
            {
                var catId = random.Next(0, 7);
                var cat   = new BlogCategoryList
                {
                    BlogId         = blog.Id,
                    BlogCategoryId = categiryList[catId]
                };
                context.BlogCategoryList.Add(cat);
            }
            //await context.SaveChangesAsync();

            // Add Blogs Images, every blog has from 1 to 3 images
            var blogUpload = new List <BlogUploads>();

            foreach (var blog in blogs)
            {
                var indexImage = random.Next(1, 52);
                var repNumber  = random.Next(1, 4);
                for (int rep = 1; rep <= repNumber; rep++)
                {
                    var upload = new Upload
                    {
                        Name          = "img (" + indexImage + "_" + rep + ")",
                        Path          = "/Uploads/Images/img (" + indexImage + ").jfif",
                        AddedDateTime = DateTime.Now,
                        UserId        = superAdmin_id
                    };
                    await context.Upload.AddAsync(upload);

                    var saveBlogUplad = new BlogUploads
                    {
                        BlogId   = blog.Id,
                        UploadId = upload.Id
                    };
                    blogUpload.Add(saveBlogUplad);
                }
            }
            await context.SaveChangesAsync();

            // add images data in UploadBlogImagesList table
            var defaultImage = true;
            int blogId       = 0;

            foreach (var item in blogUpload)
            {
                if (item.BlogId != blogId)
                {
                    defaultImage = true;
                }

                var blogImage = new UploadBlogImagesList
                {
                    UploadId     = item.UploadId,
                    BlogId       = item.BlogId,
                    Default      = defaultImage,
                    UploadTypeId = 3
                };
                blogId       = item.BlogId;
                defaultImage = false;

                await context.UploadBlogImagesList.AddAsync(blogImage);
            }
            await context.SaveChangesAsync();


            // add some Like and dislike for Blogs
            var users = context.Users.ToList();

            blogs = blogs.ToList();
            foreach (var user in users)
            {
                // like/dislike number for this user
                var repeatedNum = random.Next(1, blogs.Count());
                // to be sure the blog id is not repeated for every user
                var blogIdsList = new List <int>();
                for (int i = 0; i < repeatedNum; i++)
                {
                    var like    = true;
                    var dislike = false;
                    // select random Blog
                    var randomBlog = blogs[random.Next(1, blogs.Count())];
                    // if this blog not selected before
                    if (!blogIdsList.Contains(randomBlog.Id))
                    {
                        if (random.Next(1, 5) < 2)
                        {
                            like    = false;
                            dislike = true;
                        }
                        var likeDislike = new BlogLike
                        {
                            Like          = like,
                            Dislike       = dislike,
                            AddedDateTime = DateTime.Now,
                            BlogId        = randomBlog.Id,
                            UserId        = user.Id
                        };
                        blogIdsList.Add(randomBlog.Id);
                        await context.BlogLike.AddAsync(likeDislike);

                        var comment = new BlogComment
                        {
                            AddedDateTime = DateTime.Now,
                            BlogId        = randomBlog.Id,
                            UserId        = user.Id,
                            Comment       = "Hi I'm " + user.UserName + ", random number : " + i
                        };
                        await context.BlogComment.AddAsync(comment);
                    }
                }
            }
            await context.SaveChangesAsync();
        }
Ejemplo n.º 30
0
        public virtual IActionResult BlogCommentAdd(int blogPostId, BlogPostModel model, bool captchaValid)
        {
            if (!_blogSettings.Enabled)
            {
                return(RedirectToRoute("Homepage"));
            }

            var blogPost = _blogService.GetBlogPostById(blogPostId);

            if (blogPost == null || !blogPost.AllowComments)
            {
                return(RedirectToRoute("Homepage"));
            }

            if (_customerService.IsGuest(_workContext.CurrentCustomer) && !_blogSettings.AllowNotRegisteredUsersToLeaveComments)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Blog.Comments.OnlyRegisteredUsersLeaveComments"));
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage && !captchaValid)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptchaMessage"));
            }

            if (ModelState.IsValid)
            {
                var comment = new BlogComment
                {
                    BlogPostId   = blogPost.Id,
                    CustomerId   = _workContext.CurrentCustomer.Id,
                    CommentText  = model.AddNewComment.CommentText,
                    IsApproved   = !_blogSettings.BlogCommentsMustBeApproved,
                    StoreId      = _storeContext.CurrentStore.Id,
                    CreatedOnUtc = DateTime.UtcNow,
                };

                _blogService.InsertBlogComment(comment);

                //notify a store owner
                if (_blogSettings.NotifyAboutNewBlogComments)
                {
                    _workflowMessageService.SendBlogCommentNotificationMessage(comment, _localizationSettings.DefaultAdminLanguageId);
                }

                //activity log
                _customerActivityService.InsertActivity("PublicStore.AddBlogComment",
                                                        _localizationService.GetResource("ActivityLog.PublicStore.AddBlogComment"), comment);

                //raise event
                if (comment.IsApproved)
                {
                    _eventPublisher.Publish(new BlogCommentApprovedEvent(comment));
                }

                //The text boxes should be cleared after a comment has been posted
                //That' why we reload the page
                TempData["nop.blog.addcomment.result"] = comment.IsApproved
                    ? _localizationService.GetResource("Blog.Comments.SuccessfullyAdded")
                    : _localizationService.GetResource("Blog.Comments.SeeAfterApproving");
                return(RedirectToRoute("BlogPost", new { SeName = _urlRecordService.GetSeName(blogPost, blogPost.LanguageId, ensureTwoPublishedLanguages: false) }));
            }

            //If we got this far, something failed, redisplay form
            _blogModelFactory.PrepareBlogPostModel(model, blogPost, true);
            return(View(model));
        }
Ejemplo n.º 31
0
 public void sendEmail(Note note, BlogComment comment, long?userId, string Content)
 {
     throw new Exception();
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Prepare blog comment model
        /// </summary>
        /// <param name="blogComment">Blog comment entity</param>
        /// <returns>Blog comment model</returns>
        protected virtual async Task <BlogCommentModel> PrepareBlogPostCommentModelAsync(BlogComment blogComment)
        {
            if (blogComment == null)
            {
                throw new ArgumentNullException(nameof(blogComment));
            }

            var customer = await _customerService.GetCustomerByIdAsync(blogComment.CustomerId);

            var model = new BlogCommentModel
            {
                Id                   = blogComment.Id,
                CustomerId           = blogComment.CustomerId,
                CustomerName         = await _customerService.FormatUsernameAsync(customer),
                CommentText          = blogComment.CommentText,
                CreatedOn            = await _dateTimeHelper.ConvertToUserTimeAsync(blogComment.CreatedOnUtc, DateTimeKind.Utc),
                AllowViewingProfiles = _customerSettings.AllowViewingProfiles && customer != null && !await _customerService.IsGuestAsync(customer)
            };

            if (_customerSettings.AllowCustomersToUploadAvatars)
            {
                model.CustomerAvatarUrl = await _pictureService.GetPictureUrlAsync(
                    await _genericAttributeService.GetAttributeAsync <int>(customer, NopCustomerDefaults.AvatarPictureIdAttribute),
                    _mediaSettings.AvatarPictureSize, _customerSettings.DefaultAvatarEnabled, defaultPictureType : PictureType.Avatar);
            }

            return(model);
        }
Ejemplo n.º 33
0
            public bool doComment(BlogComment comment) 
            {
                if (comment == null)
                    return false;

                if (this.personacon_id == null)
                    this.personacon_id = getPersonaconId();

                string data;
                string referer;
                  data = $"blogId={comment.blog_id}&logNo={comment.log_no}&comment.emoticon={personacon_id}&isMemolog=false&currentPage=&commentProfileImageType=0&comment.imageType=0&shortestContentAreaWidth=true&captchaKey=&captchaValue=&comment.stickerCode=&comment.contents={Tool.encodeURI(Encoding.Default, comment.content)}&comment.secretYn={comment.secret.ToString().ToLower()}";
                //data = "blogId=dhsb7&logNo=10100261946&comment.emoticon=8070&isMemolog=false&currentPage=1&commentProfileImageType=0&comment.imageType=0&shortestContentAreaWidth=true&captchaKey=&captchaValue=&comment.stickerCode=&comment.contents=%B0%A1%A4%BF%B8%B8%B4%D9&comment.secretYn=false";
                referer = $"http://blog.naver.com/CommentList.nhn?blogId={comment.blog_id}&logNo={comment.log_no}&currentPage=&isMemolog=false&shortestContentAreaWidth=true";
                data = webPost("http://blog.naver.com/CommentWrite.nhn", referer, false, data);
                if (data == null)
                    return false;
                else
                    return data.Contains("포스트 Comment 리스트");
            }
Ejemplo n.º 34
0
        public void Can_get_customer_content_by_type()
        {
            var customer = SaveAndLoadEntity <Customer>(GetTestCustomer(), false);
            var product  = SaveAndLoadEntity <Product>(GetTestProduct(), false);

            var productReview = new ProductReview
            {
                Customer     = customer,
                Product      = product,
                Title        = "Test",
                ReviewText   = "A review",
                IpAddress    = "192.168.1.1",
                IsApproved   = true,
                CreatedOnUtc = new DateTime(2010, 01, 01),
                UpdatedOnUtc = new DateTime(2010, 01, 02),
            };

            var productReviewHelpfulness = new ProductReviewHelpfulness
            {
                Customer      = customer,
                ProductReview = productReview,
                WasHelpful    = true,
                IpAddress     = "192.168.1.1",
                IsApproved    = true,
                CreatedOnUtc  = new DateTime(2010, 01, 03),
                UpdatedOnUtc  = new DateTime(2010, 01, 04)
            };

            var blogComment = new BlogComment
            {
                Customer     = customer,
                IpAddress    = "192.168.1.1",
                IsApproved   = true,
                CreatedOnUtc = new DateTime(2010, 01, 03),
                UpdatedOnUtc = new DateTime(2010, 01, 04),
                BlogPost     = new BlogPost()
                {
                    Title         = "Title 1",
                    Body          = "Body 1",
                    AllowComments = true,
                    CreatedOnUtc  = new DateTime(2010, 01, 01),
                    Language      = new Language()
                    {
                        Name            = "English",
                        LanguageCulture = "en-Us",
                    }
                }
            };

            context.Set <CustomerContent>().Add(productReview);
            context.Set <CustomerContent>().Add(productReviewHelpfulness);
            context.Set <CustomerContent>().Add(blogComment);

            context.SaveChanges();

            context.Dispose();
            context = new SmartObjectContext(GetTestDbName());

            var query = context.Set <CustomerContent>();

            query.ToList().Count.ShouldEqual(3);

            var dbReviews = query.OfType <ProductReview>().ToList();

            dbReviews.Count().ShouldEqual(1);
            dbReviews.First().ReviewText.ShouldEqual("A review");

            var dbHelpfulnessRecords = query.OfType <ProductReviewHelpfulness>().ToList();

            dbHelpfulnessRecords.Count().ShouldEqual(1);
            dbHelpfulnessRecords.First().WasHelpful.ShouldEqual(true);

            var dbBlogCommentRecords = query.OfType <BlogComment>().ToList();

            dbBlogCommentRecords.Count().ShouldEqual(1);
        }
Ejemplo n.º 35
0
        public async Task <BlogComment> CreateAsync(BlogPost post, int uid, string contentMd, BlogComment replyTo)
        {
            var e = Context.Set <BlogComment>().Add(new BlogComment
            {
                PublishTime = DateTimeOffset.Now,
                PostId      = post.Id,
                UserId      = uid,
                ReplyToId   = replyTo?.Id,
                ContentHtml = PreparingInternally,
            });

            await Context.SaveChangesAsync();

            await ReviseAsync(e.Entity, contentMd);

            return(e.Entity);
        }