public void Index_GIVEN_BlogPostRepository_Has_1_BlogSummary_THEN_Sets_BlogSummaryViewModel_To_Have_Same_Values() { const string title = "Title"; const string description = "Description"; var url = new Uri("http://www.jumbleblocks.co.uk/noimage.jpg"); var publishedDate = DateTime.Now; var author = new BlogUser { Forenames = "Authors", Surname = "Name" }; var blogPosts = new BlogPost[] { new BlogPost(title, description, "full article", new ImageReference(1, url:url.AbsoluteUri), publishedDate, author) }; var mockedBlogPostRepository = new Mock<IBlogPostRepository>(); mockedBlogPostRepository.Setup(r => r.GetPosts(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<IEnumerable<string>>())).Returns(blogPosts); mockedBlogPostRepository.Setup(r => r.Count).Returns(blogPosts.Length); var controller = MockCreators.CreateBlogPostController(blogPostRepository: mockedBlogPostRepository.Object); var result = controller.Index() as ViewResult; var model = (FrontPageModel)result.Model; model.Summaries.First().Title.ShouldEqual(title); model.Summaries.First().Description.ShouldEqual(description); model.Summaries.First().ImageUrl.ShouldEqual(url); model.Summaries.First().PublishedDate.ShouldEqual(publishedDate); model.Summaries.First().AuthorsName.ShouldEqual(author.FullName); }
public void CanAddAndGetBlogPost() { BlogPost b1 = null; try { // Arrange b1 = new BlogPost(BlogId1, "rest-assured", "REST assured", "Blah"); // Act BlogPostRepository.Add(b1); BlogPost b2 = BlogPostRepository.Get(b1.Id); // Assert Assert.IsNotNull(b2); Assert.AreEqual(b1.Id, b2.Id); Assert.AreNotEqual(b1.Id, Guid.Empty, "Persistence layer must assign IDs"); Assert.AreEqual(b1.BlogId, b2.BlogId); Assert.AreEqual(b1.Slug, b2.Slug); Assert.AreEqual(b1.Title, b2.Title); Assert.AreEqual(b1.Body, b2.Body); Assert.AreEqual(b1.PublishDate.ToLongDateString(), b2.PublishDate.ToLongDateString()); } finally { BlogPostRepository.Remove(b1.Id); } }
public ActionResult Create(BlogPost blogPost) { RavenSession.Store(blogPost); RavenSession.SaveChanges(); return RedirectToAction("Index"); }
public static BlogPost ConvertPost(BloggerPostData post) { if (post == null) { throw new ArgumentNullException(nameof(post)); } var author = new BlogAuthor { ImageUrl = post.Author?.Image?.Url, Name = post.Author?.DisplayName, SourceId = post.Author?.Id, Url = post.Author?.Url }; // Properties set by BlogSyncServiceUpdatePostsHelper: BlavenId, UrlSlug var blogPost = new BlogPost { BlogAuthor = author, Content = post.Content, Hash = GetBlogPostHash(post), PublishedAt = post.Published, SourceId = post.Id, SourceUrl = post.Url, BlogPostTags = post.Labels?.Select(x => new BlogPostTag(x)).ToList() ?? new List<BlogPostTag>(), Title = post.Title, UpdatedAt = post.Updated }; return blogPost; }
private String getStatus( BlogPost post ) { //if (pickedService.IsPicked( post )) return "<span class='red'>[" + lang( "recommend" ) + "]</span> "; //return ""; if (post.IsPick > 0) return "<span class='red'>[" + lang("recommend") + "]</span> "; return ""; }
private void bindPostOne( IBlock listBlock, BlogPost post, BlogSetting s ) { String status = string.Empty; if (post.IsTop == 1) status = "<span class=\"lblTop\">[" + lang( "sticky" ) + "]</span>"; if (post.IsPick == 1) status = status + "<span class=\"lblTop\">[" + lang( "picked" ) + "]</span>"; if (post.AttachmentCount > 0) { status = status + string.Format( "<span><img src=\"{0}\"/></span>", strUtil.Join( sys.Path.Img, "attachment.gif" ) ); } String postLink = alink.ToAppData( post ); listBlock.Set( "blogpost.Status", status ); listBlock.Set( "blogpost.Title", post.Title ); listBlock.Set( "blogpost.Url", postLink ); String body = s.ListMode == BlogListMode.Full ? post.Content : strUtil.ParseHtml( post.Content, s.ListAbstractLength ); listBlock.Set( "blogpost.Body", body ); listBlock.Set( "author", ctx.owner.obj.Name ); listBlock.Set( "authroUrl", Link.ToMember( ctx.owner.obj ) ); listBlock.Set( "blogpost.CreateTime", post.Created.ToShortTimeString() ); listBlock.Set( "blogpost.CreateDate", post.Created.ToShortDateString() ); listBlock.Set( "blogpost.Hits", post.Hits ); String replies = post.Replies > 0 ? string.Format( "<a href=\"{0}\">{1}(<span class=\"blogItemReviews\">{2}</span>)</a>", postLink + "#comments", lang( "comment" ), post.Replies ) : string.Format( "<a href=\"{0}\">发表评论</a>", postLink + "#comments" ); listBlock.Set( "blogpost.ReplyCount", replies ); listBlock.Set( "blogpost.CategoryName", post.Category.Name ); listBlock.Set( "blogpost.CategoryLink", to( new CategoryController().Show, post.Category.Id ) ); String tags = post.Tag.List.Count > 0 ? "tag:" + post.Tag.HtmlString : ""; listBlock.Set( "blogpost.TagList", tags ); }
public async Task<IHttpActionResult> Post(BlogPost m) { if (!ModelState.IsValid) return BadRequest(ModelState); m.CreateTime = System.DateTimeOffset.Now; //TODO:获取当前用户 m.UserId = "{B0FBB2AC-3174-4E5A-B772-98CF776BD4B9}"; //添加博客 m = db.BlogPost.Add(m); try { db.SaveChanges(); } catch (Exception ex) { throw new Exception("发布博客失败:" + ex.Message); } int postId =m.Id; //添加多个标签 foreach (int tagId in m.BlogTagIds) { db.BlogPostTag.Add( new BlogPostTag { PostId = postId, BlogTagId = tagId, CreateTime = DateTime.Now, Deleted = false }); } await db.SaveChangesAsync(); return Created<BlogPost>(m); }
private void bindPostOne( IBlock listBlock, BlogPost post ) { String status = string.Empty; // if (post.IsTop == 1) status = "<span class=\"lblTop\">[" + lang( "sticky" ) + "]</span>"; // if (post.IsPick == 1) status = status + "<span class=\"lblTop\">[" + lang( "picked" ) + "]</span>"; // listBlock.Set( "blogpost.Status", status ); listBlock.Set( "blogpost.Title", post.Title ); listBlock.Set( "blogpost.Url", alink.ToAppData( post ) ); listBlock.Set( "blogpost.Body", strUtil.ParseHtml( post.Content, 300 ) ); listBlock.Set( "author", ctx.owner.obj.Name ); listBlock.Set( "authroUrl", Link.ToMember( ctx.owner.obj ) ); listBlock.Set( "blogpost.CreateTime", post.Created.ToShortTimeString() ); listBlock.Set( "blogpost.CreateDate", post.Created.ToShortDateString() ); listBlock.Set( "blogpost.Hits", post.Hits ); listBlock.Set( "blogpost.ReplyCount", post.Replies ); if (ctx.viewer.IsLogin && (ctx.viewer.Id == ctx.owner.Id)) { listBlock.Set("EditUrlStyle", ""); } else { listBlock.Set("EditUrlStyle", "display:none"); } listBlock.Set("blogpost.EditUrl", to(new Admin.PostController().Edit, post.Id)); }
/// <summary> /// Retrieving all blog posts here, so this only has to be called once. /// </summary> internal ICollection<BlogPost> Initialize(bool redirect) { var blog = Retriever.GetBlog(_blogService); var blogPosts = _blogPostService.Get(blog, VersionOptions.Published); _allBlogPosts = new List<BlogPost>(); string redirects = string.Empty; foreach (var blogPostPart in blogPosts) { if (redirect) { string currentSlug = GetUrl(blogPostPart); string redirectRule = "<location path=\"{0}\"><system.webServer><httpRedirect enabled=\"true\" destination=\"http://jan-v.nl/post/{0}\" httpResponseStatus=\"Permanent\" /></system.webServer></location>"; redirects = redirects + string.Format(redirectRule, currentSlug); } else { var blogPost = new BlogPost(); blogPost.Title = blogPostPart.Title; blogPost.Content = blogPostPart.Text; blogPost.PubDate = blogPostPart.PublishedUtc.Value; blogPost.LastModified = blogPostPart.PublishedUtc.Value; //blogPost.Categories = blogPostPart.; blogPost.Slug = GetUrl(blogPostPart); blogPost.Author = blogPostPart.Creator.UserName; blogPost.IsPublished = true; _allBlogPosts.Add(blogPost); Storage.Save(blogPost, string.Format("C:\\BlogPosts\\{0}.xml", blogPost.Slug)); } } return _allBlogPosts; }
public static Mock<IBlogPostRepository> CreateMockedBlogPostRepository(bool shouldBlogPostRepositoryAlwayReturnPost = true, int blogPostCount = 20) { //TODO: may need to allow return of specific blog post if no match var blogPostList = new List<BlogPost>(); for (int i = 0; i < blogPostCount; i++) { var blogPost = new BlogPost(i.ToString(), i.ToString(), i.ToString(), new ImageReference(1, "/noimage.jpg"), DateTime.Now, new BlogUser()); blogPost.SetProperty(p => p.Id, i); blogPostList.Add(blogPost); } var mockedBlogPostRepository = new Mock<IBlogPostRepository>(); mockedBlogPostRepository.Setup(r => r.Count).Returns(blogPostCount); mockedBlogPostRepository.Setup(r => r.LoadAll()).Returns(blogPostList); mockedBlogPostRepository.Setup(r => r.LoadFrom(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<string>())) .Returns<int, int, int, string>((year, month, day, title) => ReturnBlogPost(year, month, day, title, blogPostList, shouldBlogPostRepositoryAlwayReturnPost)); mockedBlogPostRepository.Setup(r => r.GetPosts(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<IEnumerable<string>>())) .Returns<int, int, IEnumerable<string>>((skip, take, tags) => blogPostList.Skip(skip).Take(take)); return mockedBlogPostRepository; }
public void Delete_GIVEN_BlogPostRepository_Has_BlogPost_With_Id_1_WHEN_blogPostId_Parameter_Is_1_And_User_Is_Logged_In_THEN_Saves_BlogPost_With_DeletedByUser_Set_To_Logged_In_User() { const int UserId = 1; const int BlogPostId = 1; BlogPost savedBlogPost = null; var blogPost = new BlogPost("test", "test", "test", new ImageReference(1, "/noimage.jpg"), DateTime.Now, new BlogUser()); blogPost.SetProperty(bp => bp.Id, BlogPostId); var mockedBlogPostRepository = new Mock<IBlogPostRepository>(); mockedBlogPostRepository.Setup(r => r.LoadFullArticle(BlogPostId)).Returns(blogPost); mockedBlogPostRepository.Setup(r => r.SaveOrUpdate(It.IsAny<BlogPost>())).Callback<BlogPost>(bp => savedBlogPost = bp); var mockedLookupRepository = MockCreators.CreateMockedLookupRepository(); Mock<IJumbleblocksPrincipal> mockedPrincipal = MockCreators.CreateMockedPrincipalAndAddBlogUserToLookUp(mockedLookupRepository, UserId); var controller = MockCreators.CreateBlogPostController(blogPostRepository: mockedBlogPostRepository.Object, lookupRepository: mockedLookupRepository.Object); controller.SetPrincipal(mockedPrincipal.Object); controller.Delete(BlogPostId); savedBlogPost.ShouldNotBeNull(); savedBlogPost.DeletedByUser.Id.ShouldEqual(UserId); }
public void Ctor_WHEN_fullArticle_Is_Abc_THEN_Sets_FullArticle_Property_To_Abc() { const string fullArticle = "ABC"; var post = new BlogPost("a", "description", fullArticle, GetImageReference(), DateTime.Now, new BlogUser()); post.FullArticle.ShouldEqual(fullArticle); }
public void BlogPostController_Edit_GIVEN_BlogPostRepository_Contains_BlogPost_With_ID_1_WHEN_blogPostId_Is_1_THEN_Returns_ViewModel_For_BlogPost() { const int BlogPostId = 1; var imageReference = new ImageReference(1, "/noimage.jpg"); var author = new BlogUser { Id = 1, Forenames = "Joe", Surname = "Blogs" }; var blogPost = new BlogPost("Test", "This is the description", "Not much in this article", imageReference, DateTime.Now, author); blogPost.SetProperty("Id", BlogPostId); blogPost.UpdateSeries(new Series { Name = "Series A" }); blogPost.UpdateTags(new Tag[] { new Tag { Text = "Tag 1" } }); var mockedBlogPostRepository = new Mock<IBlogPostRepository>(); mockedBlogPostRepository.Setup(r => r.Load(BlogPostId)).Returns(blogPost); var controller = MockCreators.CreateBlogPostController(blogPostRepository: mockedBlogPostRepository.Object); var result = controller.Edit(blogPost.Id.Value) as ViewResult; result.ShouldNotBeNull(); result.Model.ShouldBeInstanceOfType(typeof(CreateEditModel)); var model = (CreateEditModel)result.Model; model.BlogPostId.ShouldEqual(blogPost.Id); model.PublishedDate.ShouldEqual(blogPost.PublishedDate); model.Title.ShouldEqual(blogPost.Title); model.Description.ShouldEqual(blogPost.Description); model.FullArticle.ShouldEqual(blogPost.FullArticle); model.ImageId.ShouldEqual(blogPost.ImageReference.Id.Value); model.SeriesName.ShouldEqual(blogPost.Series.Name); }
public void Ctor_WHEN_description_Is_Abc_THEN_Sets_Description_Property_To_Abc() { const string description = "ABC"; var post = new BlogPost("a", description, "fullArticle", GetImageReference(), DateTime.Now, new BlogUser()); post.Description.ShouldEqual(description); }
public void Ctor_WHEN_author_has_value_THEN_Sets_Author_Property_To_That_Value() { var author = new BlogUser(); var post = new BlogPost("a", "b", "c", GetImageReference(), DateTime.Now, author); post.Author.ShouldEqual(author); }
public void BlogPostController_List_GIVEN_BlogPost_Has_1_Item_THEN_Returns_1_ArticleListingViewModel_With_Data_From_Post() { const int BlogPostId = 1; var imageReference = new ImageReference(1, "/noimage.jpg"); var author = new BlogUser { Id = 1, Forenames = "Joe", Surname = "Blogs" }; var blogPost = new BlogPost("Test", "This is the description", "Not much in this article", imageReference, DateTime.Now, author); blogPost.SetProperty("Id", BlogPostId); blogPost.UpdateSeries(new Series { Name = "Series A" }); blogPost.UpdateTags(new Tag[] { new Tag { Text = "Tag 1" } }); var mockedBlogPostRepository = new Mock<IBlogPostRepository>(); mockedBlogPostRepository.Setup(r => r.LoadAll()).Returns(new BlogPost[] { blogPost }); var controller = MockCreators.CreateBlogPostController(blogPostRepository: mockedBlogPostRepository.Object); var result = controller.List() as ViewResult; result.ShouldNotBeNull(); result.Model.ShouldBeInstanceOfType(typeof(IEnumerable<BlogPostListingItemModel>)); var viewModelForPost = ((IEnumerable<BlogPostListingItemModel>)result.Model).First(); viewModelForPost.BlogPostId.ShouldEqual(blogPost.Id.Value); viewModelForPost.Title.ShouldEqual(blogPost.Title); viewModelForPost.PublishedDate.ShouldEqual(blogPost.PublishedDate); viewModelForPost.AuthorsName.ShouldEqual(blogPost.Author.FullName); }
public string RenderFlatTaxaAsLink(BlogPost post, string taxonomyFieldName) { var baseUrl = string.Empty; var currentProvider = SiteMapBase.GetCurrentProvider(); if (currentProvider == null || currentProvider != null && currentProvider.CurrentNode == null) { return string.Empty; } else { var currentNode = currentProvider.CurrentNode as PageSiteNode; if (currentNode == null) { baseUrl = currentProvider.CurrentNode.Url; } else { var firstPageDataNode = RouteHelper.GetFirstPageDataNode(currentNode, true); if (!currentNode.IsGroupPage || !(firstPageDataNode.Url != currentProvider.CurrentNode.Url)) { baseUrl = currentProvider.CurrentNode.Url; } else { baseUrl = firstPageDataNode.Url; } } } var tagList = ""; var tags = post.GetValue<TrackedList<Guid>>(taxonomyFieldName); if (tags != null && tags.Count() > 0) { tagList = " | "; var taxManager = TaxonomyManager.GetManager(); foreach (var tag in tags) { var t = taxManager.GetTaxon<FlatTaxon>(tag); var url = string.Format("{0}/-in-{1}/{2}/{3}", VirtualPathUtility.ToAbsolute(baseUrl), t.Taxonomy.Name, t.Taxonomy.Name, t.UrlName); var link = string.Format("<a class='tag' href='{0}'><span>{1}</span></a>", url, t.Title).ToString(); tagList += link; } } return tagList; }
public static void Create(BlogPost m_BlogPost) { SqlConnection conn = DB.DbConnect(); conn.Open(); string queryString = "SELECT IDENT_CURRENT('CMS_BlogPosts')"; SqlCommand getBlogId = new SqlCommand(queryString, conn); int m_BlogId = (int)(decimal)getBlogId.ExecuteScalar(); conn.Close(); if (m_BlogId == 1) { conn.Open(); queryString = "SELECT COUNT(*) FROM CMS_BlogPosts"; SqlCommand getPageCount = new SqlCommand(queryString, conn); int pageCount = (int)getPageCount.ExecuteScalar(); if (m_BlogId == pageCount) { m_BlogId = pageCount + 1; } conn.Close(); } else { m_BlogId++; } conn.Open(); queryString = "INSERT INTO CMS_BlogPosts(blogId, title, publishDate, expirationDate, contentGroup, [content], comments, pageWorkFlowState, lockedBy, lastModifiedBy, lastModifiedDate, newsImageId, newsImageName, author, introText) VALUES(@blogId, @title, @publishDate, @expirationDate, @contentGroup, @content, @comments, 1, @lockedBy, @lastModifiedBy, @lastModifiedDate, @newsImageId, @newsImageName, @author, @introText)"; SqlCommand insertBlogPost = new SqlCommand(queryString, conn); insertBlogPost.Parameters.AddWithValue("blogId", m_BlogId); insertBlogPost.Parameters.AddWithValue("title", m_BlogPost.Title); insertBlogPost.Parameters.AddWithValue("publishDate", m_BlogPost.PublishDate.ToString()); insertBlogPost.Parameters.AddWithValue("expirationDate", m_BlogPost.PublishDate.ToString()); insertBlogPost.Parameters.AddWithValue("contentGroup", m_BlogPost.ContentGroup); insertBlogPost.Parameters.AddWithValue("content", m_BlogPost.Content); insertBlogPost.Parameters.AddWithValue("comments", m_BlogPost.Comments); insertBlogPost.Parameters.AddWithValue("lockedBy", HttpContext.Current.Session["uid"]); insertBlogPost.Parameters.AddWithValue("lastModifiedBy", HttpContext.Current.Session["uid"]); insertBlogPost.Parameters.AddWithValue("lastModifiedDate", DateTime.Now); insertBlogPost.Parameters.AddWithValue("newsImageId", m_BlogPost.NewsImageId); insertBlogPost.Parameters.AddWithValue("newsImageName", m_BlogPost.NewsImageName ?? ""); insertBlogPost.Parameters.AddWithValue("author", m_BlogPost.Author ?? ""); insertBlogPost.Parameters.AddWithValue("introText", m_BlogPost.IntroText); insertBlogPost.ExecuteNonQuery(); foreach (int catId in m_BlogPost.Categories) { queryString = "INSERT INTO CMS_BlogPostsToCategories(blogPostId, categoryId) VALUES(@blogId, @catId)"; SqlCommand insertCat = new SqlCommand(queryString, conn); insertCat.Parameters.AddWithValue("blogId", m_BlogId); insertCat.Parameters.AddWithValue("catId", catId); insertCat.ExecuteNonQuery(); } conn.Close(); }
public void DeletePost( BlogPost post ) { // 全站首页缓存移除(如果在首页) // 全站首页列表页标记过期 // 用户博客列表页标记过期 // 分类列表页标记过期 // 详细页缓存移除 }
public ActionResult Edit(string id, BlogPost blogPost) { blogPost.LastModified = DateTime.Now; RavenSession.Store(blogPost); RavenSession.SaveChanges(); return RedirectToAction("Index"); }
private static void updatePost( BlogPost post ) { User owner = User.findById( post.OwnerId ); int appId = post.AppId; BlogLayoutViewCacher.Update( owner, appId ); BlogHomeViewCacher.Update( owner, appId ); BlogMainViewCacher.Update( appId ); }
private static void updatePost( BlogPost post ) { User owner = User.findById( post.OwnerId ); int appId = post.AppId; LayoutCacher.Update( owner, appId ); HomeCacher.Update( owner, appId ); MainCacher.Update( appId ); }
public async Task<IActionResult> EditPost(int id = 0) { var post = await db.BlogPosts.FirstOrDefaultAsync(a => a.id == id); if(post == null) { post = new BlogPost { Author = db.Users.First(a => a.Id == HttpContext.User.GetUserId()) }; } return View(post); }
public ActionResult AddBlogPost() { ViewBag.Categories = BlogPostRepository.getCategories(); ViewBag.myContentGroups = Utility.ContentGroups(); BlogPost m_BlogPost = new BlogPost(); ViewBag.NewsImages = ImageRepository.RetrieveAll(23); return View("AddBlogPost", m_BlogPost); }
public Task<BlogPost> Transform(BlogPost blogPost) { if (blogPost.Content != null) { blogPost.Content = EncodePreTags(blogPost.Content); } return Task.FromResult(blogPost); }
public object BindToModel(BlogPost blogPost) { return new Result() { HeaderValue = blogPost.Title, HeaderValues = blogPost.Tags, ModelStateErrors = ModelState.Where(kvp => kvp.Value.Errors.Count > 0).Select(kvp => kvp.Key).ToArray(), }; }
public void MarkAsDeleted(BlogPost blogPost, int userId) { var deletionUser = LookupRepository.LoadForId<BlogUser>(userId); if (deletionUser == null) throw new UnknownUserException(userId); blogPost.MarkAsDeleted(deletionUser); BlogPostRepository.SaveOrUpdate(blogPost); }
public void ValidateBlogPost_WhenCalledWithInvalidBlogPost_ErrorsShouldNotBeEmpty() { //Arrange var invalidBlogPost = new BlogPost(); //Act var result = invalidBlogPost.Validate(); //Assert Assert.IsNotEmpty(invalidBlogPost.Errors); }
public void CanAddBlogPostWithSameSlugForDifferentBlogs() { // Arrange BlogPost p1 = BlogPostBuilder.BuildPost(BlogId1, "MYslug", "My title", "Blah blah ..."); BlogPost p2 = new BlogPost(BlogId2, "myslug", "My title", "My body"); BlogPostBuilder.RegisterInstance(p2); // Act + Assert BlogPostRepository.Add(p2); }
// TODO 不同的数据类型,有不同的列表项 public void UpdatePost( BlogPost post ) { // 全站首页缓存移除 // 全站首页列表所在页面移除 // 博客列表页缓存移除 // 移除所在列表页 removeListPage( post ); // 详细页缓存移除 }
public async Task SendNotification(BlogPost post) { await hubConnection.SendAsync("SendNotification", post); }
static async Task MainAsync(string[] args) { var store = await StoreFactory.CreateAndInitializeAsync( new Configuration() .UseSqlServer(@"Data Source =.; Initial Catalog = yessql; Integrated Security = True") .SetTablePrefix("Hi") ); using (var connection = store.Configuration.ConnectionFactory.CreateConnection()) { connection.Open(); using (var transaction = connection.BeginTransaction(store.Configuration.IsolationLevel)) { new SchemaBuilder(store.Configuration, transaction) .CreateMapIndexTable <BlogPostByAuthor>(table => table .Column <string>("Author") ) .CreateReduceIndexTable <BlogPostByDay>(table => table .Column <int>("Count") .Column <int>("Day") ); transaction.Commit(); } }; // register available indexes store.RegisterIndexes <BlogPostIndexProvider>(); // creating a blog post var post = new BlogPost { Title = "Hello YesSql", Author = "Bill", Content = "Hello", PublishedUtc = DateTime.UtcNow, Tags = new[] { "Hello", "YesSql" } }; // saving the post to the database using (var session = store.CreateSession()) { session.Save(post); } // loading a single blog post using (var session = store.CreateSession()) { var p = await session.Query().For <BlogPost>().FirstOrDefaultAsync(); Console.WriteLine(p.Title); // > Hello YesSql } // loading blog posts by author using (var session = store.CreateSession()) { var ps = await session.Query <BlogPost, BlogPostByAuthor>().Where(x => x.Author.StartsWith("B")).ListAsync(); foreach (var p in ps) { Console.WriteLine(p.Author); // > Bill } } // loading blog posts by day of publication using (var session = store.CreateSession()) { var ps = await session.Query <BlogPost, BlogPostByDay>(x => x.Day == DateTime.UtcNow.ToString("yyyyMMdd")).ListAsync(); foreach (var p in ps) { Console.WriteLine(p.PublishedUtc); // > [Now] } } // counting blog posts by day using (var session = store.CreateSession()) { var days = await session.QueryIndex <BlogPostByDay>().ListAsync(); foreach (var day in days) { Console.WriteLine(day.Day + ": " + day.Count); // > [Today]: 1 } } }
public async Task AddAsync(BlogPost post) { await this._context.BlogPosts.AddAsync(post); await this._context.SaveChangesAsync(); }
public virtual BlogPostPicked GetByPost(BlogPost post) { return(db.find <BlogPostPicked>("Post.Id=" + post.Id).first()); }
public ActionResult Edit(string inputTitle, string tags, string text, string rowkey, string articledescription, HttpPostedFileBase headerImage, IEnumerable <HttpPostedFileBase> inputFile, IEnumerable <string> inputCode) { if (AuthTokens == null || AuthTokens[3] != "su") { return(RedirectToAction("Index", "Home")); } BlogPostClient bpc = new BlogPostClient(); BlogTagClient btc = new BlogTagClient(); BlogPost blogPost = bpc.GetByPartitionAndRowKey("blogPost", rowkey); if (blogPost != null) { string article1 = ""; string article2 = ""; string article3 = ""; string article4 = ""; if (text.Length <= 32500) { article1 = text; } else if (text.Length > 32500 && text.Length <= 65000) { article1 = text.Substring(0, 32500); article2 = text.Substring(32500); } else if (text.Length > 65000 && text.Length <= 97500) { article1 = text.Substring(0, 32500); article2 = text.Substring(32500, 32500); article3 = text.Substring(65000); } else if (text.Length > 97500 && text.Length <= 130000) { article1 = text.Substring(0, 32500); article2 = text.Substring(32500, 32500); article3 = text.Substring(65000, 32500); article4 = text.Substring(97500); } else { ViewBag.Error = "Article too long"; return(View()); } blogPost.Article1 = article1; blogPost.Article2 = article2; blogPost.Article3 = article3; blogPost.Article4 = article4; blogPost.Title = inputTitle; blogPost.ArticleDescription = articledescription; List <string> currentTagList = blogPost.Tags.Split(',').ToList(); List <string> newTagList = tags.Split(',').ToList(); foreach (string tag in currentTagList) { if (!newTagList.Contains(tag)) { BlogTag blogTag = btc.GetByPartitionAndRowKey("blogTag", tag); if (blogTag != null) { blogTag.PublicPosts--; btc.Update(blogTag); } } } foreach (string tag in newTagList) { if (!currentTagList.Contains(tag)) { BlogTag blogTag = btc.GetByPartitionAndRowKey("blogTag", tag); if (blogTag != null) { blogTag.PublicPosts++; btc.Update(blogTag); } } } blogPost.Tags = tags.ToLower(); bpc.Update(blogPost); PictureManager pm = new PictureManager(); if (headerImage != null) { WebImage image = new WebImage(headerImage.InputStream); var b = pm.UploadPictureToBlobStorage(image, blogPost.HeaderImageCode.Substring(2, 4), "blog", rowkey, 960, 960, 50, 50, false, false); } if (inputFile != null) { List <HttpPostedFileBase> files = inputFile.ToList(); List <string> codes = inputCode.ToList(); for (var i = 0; i < files.Count; i++) { if (files[i] != null) { WebImage image = new WebImage(files[i].InputStream); pm.UploadPictureToBlobStorage(image, codes[i].Substring(2, 4), "blog", rowkey, 960, 960, 50, 50, false, false); } } } } return(RedirectToAction("Admin")); }
public static BlogPost ToEntity(this BlogPostModel model, BlogPost destination) { return(Mapper.Map(model, destination)); }
private void LoadBlogPost() { //Context item - gets Blog Post infomration BlogPost blogPost = Sitecore.Context.Item.CreateAs <BlogPost>(); scTitle.Item = Sitecore.Context.Item; scBody.Item = Sitecore.Context.Item; dateBlogPostPublishDate.Item = Sitecore.Context.Item; UrlOptions option = new UrlOptions(); option.AlwaysIncludeServerUrl = true; //currentUrl = HttpUtility.UrlEncode(LinkManager.GetItemUrl(blogPost.InnerItem, option)); currentUrl = LinkManager.GetItemUrl(blogPost.InnerItem, option); title = HttpUtility.UrlEncode(blogPost.Title); if (settingsItem.IncludeEmailOnBlogPost) { pnlEmail.Visible = true; } if (settingsItem.IncludeFacebookOnBlogPost) { pnlFacebook.Visible = true; } if (settingsItem.IncludeGooglePlusOnBlogPost) { pnlGooglePlus.Visible = true; } if (settingsItem.IncludeLinkedinOnBlogPost) { pnlLinkedin.Visible = true; } if (settingsItem.IncludeTwitterOnBlogPost) { pnlTwitter.Visible = true; } if (dateBlogPostPublishDate != null) { dateBlogPostPublishDate.Field = BlogPost.BlogPostPublishDateFieldId; dateBlogPostPublishDate.Format = settingsItem.BlogPostDateFormat; } if (blogPost.Authors.Any()) { List <Sitecore.Data.ID> authorIds = new List <Sitecore.Data.ID>(); foreach (Author a in blogPost.Authors) { authorIds.Add(a.ItemId); } List <Author> authors = AuthorManager.GetAuthorsForBlogPost(authorIds); litAuthor.Text = authors[0].FullName; } litCategories.Text = CategoryManager.GetCommaSeperatedCategoryList(blogPost); litTags.Text = TagManager.GetCommaSeperatedTagList(blogPost); }
public void AddBlog(BlogPost postToAdd) { _repo.AddBlog(postToAdd); }
public void UpdateBlog(BlogPost postToUpdate) { _repo.UpdateBlog(postToUpdate); }
public void RemoveBlogPost(BlogPost postToRemove) { var result = _posts.FirstOrDefault(p => p.Id == postToRemove.Id); _posts.Remove(result); }
public void DeleteTagBlogBridgeTable(BlogPost id) { throw new NotImplementedException(); }
public static BlogPost ToEntity(this BlogPostModel model, BlogPost destination) { return(model.MapTo(destination)); }
//blog posts public static BlogPostModel ToModel(this BlogPost entity) { return(entity.MapTo <BlogPost, BlogPostModel>()); }
public ActionResult Create(BlogPost post) { db.BlogPost.Add(post); db.SaveChanges(); return(RedirectToAction("Index")); }
public void AddBlogPost(BlogPost blogPost) { blogPost.Date = DateTime.Now; _blogPostRepository.AddPost(blogPost); _blogContext.SaveChanges(); }
public async Task <BlogPost> SaveBlogPostAsync([FromBody] BlogPost item) { return(await api.SaveBlogPostAsync(item)); }
//blog posts public static BlogPostModel ToModel(this BlogPost entity) { return(Mapper.Map <BlogPost, BlogPostModel>(entity)); }
public async Task DeleteBlogPostAsync([FromBody] BlogPost item) { await api.DeleteBlogPostAsync(item); }
public bool DeleteBlogPost(BlogPost blogPost) { throw new NotImplementedException(); }
public async Task <IActionResult> AddEditBlog([FromBody] BlogPost blog) { try { if (blog == null) { throw new Exception("No blog posted!"); } BlogPost editing = _context.Blogs.FirstOrDefault(b => b.Id == blog.Id); if (editing != null) { editing.Active = blog.Active; editing.Author = blog.Author; editing.Content = blog.Content; editing.PostDate = blog.PostDate; editing.Tags = blog.Tags; editing.Title = blog.Title; editing.Views = blog.Views; _context.Entry(editing).State = Microsoft.EntityFrameworkCore.EntityState.Modified; } else { editing = new BlogPost { Active = blog.Active, Author = blog.Author, Content = blog.Content, PostDate = blog.PostDate, Tags = blog.Tags, Title = blog.Title, Views = blog.Views }; await _context.Blogs.AddAsync(editing); } //Header image added/replaced. if (blog.HeaderImageBase64.Length > 0) { Image img = Image.Load(Convert.FromBase64String(blog.HeaderImageBase64)); JpegEncoder encoder = new JpegEncoder(); await using MemoryStream mem = new MemoryStream(); encoder.Quality = 100; await img.SaveAsJpegAsync(mem, encoder); int q = 100; while (mem.Length >= 400000 && q > 1) { q -= 10; encoder.Quality = q; mem.Position = 0; img = await Image.LoadAsync(mem); //start again mem.SetLength(0); await img.SaveAsJpegAsync(mem, encoder); } editing.HeaderImageBase64 = Convert.ToBase64String(mem.ToArray()); if (mem.Length > 500000) { throw new Exception($"Could not compress image enough! Try uploading a smaller image"); } } await _context.SaveChangesAsync(); return(Ok(new BasicHttpResponse <object> { Ok = true })); } catch (Exception e) { return(Ok(new BasicHttpResponse <object> { Ok = false, Message = e.Message })); } }
/// <summary> /// Prepare blog comment search model /// </summary> /// <param name="searchModel">Blog comment search model</param> /// <param name="blogPost">Blog post</param> /// <returns>Blog comment search model</returns> public virtual BlogCommentSearchModel PrepareBlogCommentSearchModel(BlogCommentSearchModel searchModel, BlogPost blogPost) { if (searchModel == null) { throw new ArgumentNullException(nameof(searchModel)); } //prepare "approved" property (0 - all; 1 - approved only; 2 - disapproved only) searchModel.AvailableApprovedOptions.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.ContentManagement.Blog.Comments.List.SearchApproved.All"), Value = "0" }); searchModel.AvailableApprovedOptions.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.ContentManagement.Blog.Comments.List.SearchApproved.ApprovedOnly"), Value = "1" }); searchModel.AvailableApprovedOptions.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.ContentManagement.Blog.Comments.List.SearchApproved.DisapprovedOnly"), Value = "2" }); searchModel.BlogPostId = blogPost?.Id; //prepare page parameters searchModel.SetGridPageSize(); return(searchModel); }
public async Task <IActionResult> PostBlogPost([FromBody] BlogPost blogPost) { //Do code here return(Ok()); }
public virtual Boolean IsPicked(BlogPost post) { BlogPostPicked pickedPost = GetByPost(post); return(pickedPost != null); }
protected void lvBlogPosts_ItemDataBound(object sender, ListViewItemEventArgs e) { if (e.Item.ItemType != ListViewItemType.DataItem) { return; } BlogPost blogPost = e.Item.DataItem as BlogPost; if (blogPost == null) { return; } Text scBlogPostTitle = e.Item.FindControl("scBlogPostTitle") as Text; if (scBlogPostTitle != null) { scBlogPostTitle.Item = blogPost.InnerItem; } HyperLink hlTitle = e.Item.FindControl("hlTitle") as HyperLink; if (hlTitle != null) { hlTitle.Text = blogPost.Title; hlTitle.ToolTip = blogPost.Title; hlTitle.NavigateUrl = Sitecore.Links.LinkManager.GetItemUrl(blogPost.InnerItem); } Date dateBlogPostPublishDate = e.Item.FindControl("dateBlogPostPublishDate") as Date; if (dateBlogPostPublishDate != null) { dateBlogPostPublishDate.Item = blogPost.InnerItem; dateBlogPostPublishDate.Field = BlogPost.BlogPostPublishDateFieldId; dateBlogPostPublishDate.Format = settingsItem.BlogListingDateFormat; } Literal litAuthor = e.Item.FindControl("litAuthor") as Literal; if (litAuthor != null && blogPost.Authors.Any()) { List <ID> authorIds = new List <Sitecore.Data.ID>(); foreach (Author a in blogPost.Authors) { authorIds.Add(a.ItemId); } List <Author> authors = AuthorManager.GetAuthorsForBlogPost(authorIds); string authorNames = string.Empty; foreach (Author a in authors) { authorNames += a.FullName; } litAuthor.Text = authors[0].FullName; } }
public IActionResult AddBlogPost([FromBody] BlogPost newBlogPost) { var savedBlogPost = _blogPostService.AddBlogPost(newBlogPost); return(Created(new Uri(Urls.BlogPost.Replace("{id}", savedBlogPost.Id.ToString()), UriKind.Relative), savedBlogPost)); }
//[RequireHttps] public ActionResult CreateBlogPost() { var post = new BlogPost(); return(View(post)); }
public async Task UpdateAsync(BlogPost post) { this._context.BlogPosts.Update(post); await this._context.SaveChangesAsync(); }
public async Task <IActionResult> Seed() { // Get the default site var site = await _api.Sites.GetDefaultAsync(); site.SiteTypeId = nameof(BlogSite); await _api.Sites.SaveAsync(site); // Add media assets var bannerId = Guid.NewGuid(); using (var stream = System.IO.File.OpenRead("seed/pexels-photo-355423.jpeg")) { await _api.Media.SaveAsync(new Piranha.Models.StreamMediaContent() { Id = bannerId, Filename = "pexels-photo-355423.jpeg", Data = stream }); } var banner = await _api.Media.GetByIdAsync(bannerId); var logoId = Guid.NewGuid(); using (var stream = System.IO.File.OpenRead("seed/logo.png")) { await _api.Media.SaveAsync(new Piranha.Models.StreamMediaContent() { Id = logoId, Filename = "logo.png", Data = stream }); } // Add the site info var blogSite = await BlogSite.CreateAsync(_api); blogSite.Information.SiteLogo = logoId; blogSite.Information.SiteTitle = "Piranha CMS"; blogSite.Information.Tagline = "A lightweight & unobtrusive CMS for Asp.NET Core."; await _api.Sites.SaveContentAsync(site.Id, blogSite); // Add the blog archive var blogId = Guid.NewGuid(); var blogPage = await BlogArchive.CreateAsync(_api); blogPage.Id = blogId; blogPage.SiteId = site.Id; blogPage.Title = "Blog Archive"; blogPage.MetaKeywords = "Inceptos, Tristique, Pellentesque, Lorem, Vestibulum"; blogPage.MetaDescription = "Morbi leo risus, porta ac consectetur ac, vestibulum at eros."; blogPage.NavigationTitle = "Blog"; blogPage.Published = DateTime.Now; await _api.Pages.SaveAsync(blogPage); // Add a blog post var post = await BlogPost.CreateAsync(_api); post.BlogId = blogPage.Id; post.Category = "Piranha CMS"; post.Tags.Add("Welcome", "Fresh Start", "Information"); post.Title = "Welcome to Piranha CMS!"; post.MetaKeywords = "Welcome, Piranha CMS, AspNetCore, MVC, .NET Core"; post.MetaDescription = "Piranha is the fun, fast and lightweight framework for developing cms-based web applications with ASP.Net Core."; post.Hero.PrimaryImage = bannerId; post.Hero.Ingress = "<p>Piranha CMS is a <strong>lightweight</strong>, <strong>cross-platform</strong> CMS <string>library</string> for <code>NetStandard 2.0</code>, <code>.NET Core</code> & <code>Entity Framework Core</code>. It can be used to add CMS functionality to your existing application or to build a new website from scratch. It has an extensible & pluggable architecture that can support a wide variety of runtime scenarios.</p>"; post.Blocks.Add(new HtmlBlock { Body = "<p>Piranha CMS is a <strong>lightweight</strong>, <strong>cross-platform</strong> CMS <string>library</string> for <code>NetStandard 2.0</code>, <code>.NET Core</code> & <code>Entity Framework Core</code>. It can be used to add CMS functionality to your existing application or to build a new website from scratch. It has an extensible & pluggable architecture that can support a wide variety of runtime scenarios.</p><p>Piranha CMS is totally <strong>package based</strong> and available on <code>NuGet</code>. You can read more about the different packages available in the documentation.</p>" }); post.Blocks.Add(new HtmlBlock { Body = "<h2>Getting Started</h2><p>To log into the manager interface and start writing content simply go the URL <code>/manager</code> and login with <code>admin</code> / <code>password</code> as your username and password.</p>" }); post.Blocks.Add(new HtmlBlock { Body = "<h2>Licensing</h2><p>Piranha CMS is released under the <strong>MIT</strong> license. It is a permissive free software license, meaning that it permits reuse within proprietary software provided all copies of the licensed software include a copy of the MIT License terms and the copyright notice.</p>" }); post.Published = DateTime.Now; await _api.Posts.SaveAsync(post); var comment = new Piranha.Models.Comment { Author = "Håkan Edling", Email = "*****@*****.**", Url = "http://piranhacms.org", Body = "Awesome to see that the project is up and running! Now maybe it's time to start customizing it to your needs. You can find a lot of information in the official docs.", IsApproved = true }; await _api.Posts.SaveCommentAsync(post.Id, comment); // Add about page var page = await StandardPage.CreateAsync(_api); page.SiteId = site.Id; page.SortOrder = 1; page.Title = "About Me"; page.MetaKeywords = "Inceptos, Tristique, Pellentesque, Lorem, Vestibulum"; page.MetaDescription = "Morbi leo risus, porta ac consectetur ac, vestibulum at eros."; page.Blocks.Add(new HtmlBlock { Body = "<p>Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Vestibulum id ligula porta felis euismod semper. Nulla vitae elit libero, a pharetra augue. Donec id elit non mi porta gravida at eget metus. Donec ullamcorper nulla non metus auctor fringilla.</p>" }); page.Blocks.Add(new QuoteBlock { Body = "Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod." }); page.Blocks.Add(new ColumnBlock { Items = new List <Block> { new HtmlBlock { Body = $"<p><img src=\"{banner.PublicUrl.Replace("~", "")}\"></p>" }, new HtmlBlock { Body = "<p>Maecenas faucibus mollis interdum. Aenean lacinia bibendum nulla sed consectetur. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.</p>" } } }); page.Published = DateTime.Now; await _api.Pages.SaveAsync(page); return(Redirect("~/")); }
public async Task <IActionResult> Create([FromBody] dynamic model) { var title = (string)model.Title; var content = (string)model.Content; var accountId = (int)model.AccountId; if (string.IsNullOrEmpty(title)) { throw new ServiceException(HttpStatusCode.BadRequest, Reason.ArgumentNull, "博客日志标题不能为空。"); } if (string.IsNullOrEmpty(content)) { throw new ServiceException(HttpStatusCode.BadRequest, Reason.ArgumentNull, "博客日志内容不能为空。"); } if (accountId <= 0) { throw new ServiceException(HttpStatusCode.BadRequest, Reason.ArgumentNull, "用户帐号Id值不在有效范围。"); } var result = await this.storage.ExecuteAsync(async (connection, transaction, cancellationToken) => { var blogPost = new BlogPost { AccountId = accountId, DatePublished = DateTime.UtcNow, Content = content, IsDeleted = false, Title = title }; var affectedRows = await this.blogPostStore.InsertAsync(blogPost, connection, new Expression <Func <BlogPost, object> >[] { bp => bp.Id }, transaction, cancellationToken); if (affectedRows > 0) { var lastInsertedBlogPost = (await this.blogPostStore.SelectAsync(connection, sorting: new Sort <BlogPost, int> { { bp => bp.DatePublished, SortOrder.Descending } }, transaction: transaction, cancellationToken: cancellationToken)).FirstOrDefault(); if (lastInsertedBlogPost != null) { return(lastInsertedBlogPost.Id); } } return(0); }); if (result != 0) { this.cachingService.DeleteByPrefix(CachingKeys.BLOGPOSTS_GETBYPAGING_KEY); var archiveListCachingKey = new CachingKey(CachingKeys.BLOGPOSTS_GETARCHIVELIST_KEY); this.cachingService.Delete(archiveListCachingKey); return(Created(Url.Action("GetById", new { id = result }), result)); } return(NoContent()); }
protected internal override void PreparePost(BlogPost blogPost, ref bool?publish) { blogPost.Title = "Post as draft test"; blogPost.Contents = "foo bar"; publish = false; }