Exemple #1
0
        /// <summary>
        /// Returns posts, total posts and post statuses.
        /// </summary>
        /// <param name="status">The post status <see cref="EPostStatus"/></param>
        /// <param name="pageNumber">Which page, 1-based.</param>
        /// <param name="pageSize">How many rows per page</param>
        /// <returns></returns>
        /// <remarks>
        /// I did a workaround for tabs, couldn't get "statuses" to work as the tab is not initially selected.
        /// </remarks>
        private async Task <PostListVM> GetPostListVMAsync(string status, int pageNumber, int pageSize)
        {
            var postList = status.Equals("published", StringComparison.InvariantCultureIgnoreCase) ?
                           await blogPostService.GetListAsync(pageNumber, pageSize, cacheable : false) :
                           await blogPostService.GetListForDraftsAsync(); // TODO drafts need pagination too

            var coreSettings = await settingService.GetSettingsAsync <CoreSettings>();

            var postVms = from p in postList.Posts
                          select new PostVM
            {
                Id        = p.Id,
                Title     = p.Title,
                Date      = p.CreatedOn.ToLocalTime(coreSettings.TimeZoneId).ToString(POST_DATE_STRING_FORMAT),
                Author    = p.User.DisplayName,
                Category  = p.CategoryTitle,
                EditLink  = BlogRoutes.GetPostEditLink(p.Id),
                PostLink  = $"{Request.Scheme}://{Request.Host}" + BlogRoutes.GetPostRelativeLink(p.CreatedOn, p.Slug),
                ViewCount = p.ViewCount,
            };

            var postCount = await statsService.GetPostCountAsync();

            // prep vm
            return(new PostListVM
            {
                Posts = postVms,
                TotalPosts = postList.TotalPostCount,
                PublishedCount = postCount.Published,
                DraftCount = postCount.Draft,
            });
        }
Exemple #2
0
        public void GetCategoryRelativeLink_returns_url_starts_with_slash()
        {
            var slug         = "technology";
            var relativeLink = BlogRoutes.GetCategoryRelativeLink(slug);

            Assert.Equal("/blog/technology", relativeLink);
        }
Exemple #3
0
        public void GetPostPermalink_returns_relative_url_starts_with_slash()
        {
            var postId    = 1;
            var permalink = BlogRoutes.GetPostPermalink(postId);

            Assert.Equal("/post/1", permalink);
        }
Exemple #4
0
        public IActionResult PreviewPage(string parentSlug, string childSlug)
        {
            try
            {
                // slugs coming in are not url encoded, encode them for the key to tempdata
                if (!parentSlug.IsNullOrEmpty())
                {
                    parentSlug = WebUtility.UrlEncode(parentSlug);
                }
                if (!childSlug.IsNullOrEmpty())
                {
                    childSlug = WebUtility.UrlEncode(childSlug);
                }

                var key    = BlogRoutes.GetPagePreviewRelativeLink(parentSlug, childSlug);
                var pageVM = TempData.Get <PageVM>(key);

                return(pageVM == null?View("404") : View("Page", pageVM));
            }
            catch (Exception)
            {
                // when user access the preview link directly or when user clicks on other links
                // and navigates away during the preview, hacky need to find a better way.
                return(RedirectToAction("ErrorCode", "Home", new { statusCode = 404 }));
            }
        }
Exemple #5
0
        public async Task <(string viewPath, PageVM viewModel)> GetPageAsync(string parentPage, string childPage = null)
        {
            if (parentPage.IsNullOrEmpty())
            {
                parentPage = "Home";
            }

            var page = await pageService.GetAsync(parentPage, childPage);

            var coreSettings = await settingService.GetSettingsAsync <CoreSettings>();

            return("../Blog/Page", new PageVM
            {
                Id = page.Id,
                ParentId = page.ParentId,
                Author = page.User.DisplayName,
                Body = page.Body,
                Excerpt = page.Excerpt,
                CreatedOnDisplay = page.CreatedOn.ToDisplayString(coreSettings.TimeZoneId),
                UpdatedOnDisplay = page.UpdatedOn.HasValue ?
                                   page.UpdatedOn.Value.ToDisplayString(coreSettings.TimeZoneId) :
                                   page.CreatedOn.ToDisplayString(coreSettings.TimeZoneId),
                EditLink = BlogRoutes.GetPageEditLink(page.Id),
                IsParent = page.IsParent,
                AddChildLink = page.IsParent ? BlogRoutes.GetAddChildPageLink(page.Id) : "",
                Title = page.Title,
                PageLayout = (EPageLayout)page.PageLayout,
                ViewCount = page.ViewCount,
            });
        }
Exemple #6
0
        /// <summary>
        /// Returns archive information.
        /// </summary>
        /// <returns></returns>
        public async Task <Dictionary <int, List <MonthItem> > > GetArchivesAsync()
        {
            return(await distributedCache.GetAsync(BlogCache.KEY_ALL_ARCHIVES, BlogCache.Time_Archives, async() =>
            {
                var months = new Dictionary <DateTime, int>();
                var years = new Dictionary <int, List <MonthItem> >();

                var dates = await postRepository.GetPostDateTimesAsync();
                foreach (var month in dates)
                {
                    months.TryGetValue(month, out int count);
                    ++count;
                    months[month] = count;
                }

                foreach (var month in months)
                {
                    int year = month.Key.Year;
                    if (!years.Keys.Contains(year))
                    {
                        years.Add(year, new List <MonthItem>());
                    }

                    years[year].Add(new MonthItem
                    {
                        Title = month.Key.ToString("MMMM"),
                        Url = BlogRoutes.GetArchiveRelativeLink(year, month.Key.Month),
                        Count = month.Value,
                    });
                }

                return years;
            }));
Exemple #7
0
        /// <summary>
        /// Preview
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        public async Task <JsonResult> OnPostPreviewAsync([FromBody] PostVM post)
        {
            // prep blog post
            List <Tag> tags = new List <Tag>();

            foreach (var title in post.Tags) // titles
            {
                tags.Add(await _tagSvc.GetByTitleAsync(title));
            }

            var blogPost = new BlogPost
            {
                User      = await _userManager.GetUserAsync(HttpContext.User),
                UserId    = Convert.ToInt32(_userManager.GetUserId(HttpContext.User)),
                Category  = await _catSvc.GetAsync(post.CategoryId),
                CreatedOn = GetCreatedOn(post.PostDate),
                Tags      = tags,
                Slug      = post.Slug.IsNullOrEmpty() ? "untitled" : post.Slug,
                Excerpt   = post.Excerpt,
                Title     = post.Title.IsNullOrEmpty() ? "Untitled" : post.Title,
                Body      = post.Body,
            };

            // prep TempData
            var prevRelLink = BlogRoutes.GetPostPreviewRelativeLink(blogPost.CreatedOn, blogPost.Slug);

            TempData.Put(prevRelLink, blogPost);

            // return preview url
            return(new JsonResult($"{Request.Scheme}://{Request.Host}{prevRelLink}"));
        }
Exemple #8
0
        public void GetTagRelativeLink_returns_url_starts_with_slash()
        {
            var slug         = "asp-net-core";
            var relativeLink = BlogRoutes.GetTagRelativeLink(slug);

            Assert.Equal("/posts/tagged/asp-net-core", relativeLink);
        }
Exemple #9
0
        public void GetCategoryRssRelativeLink_returns_url_starts_with_slash()
        {
            var slug    = "technology";
            var rssLink = BlogRoutes.GetCategoryRssRelativeLink(slug);

            Assert.Equal("/posts/categorized/technology/feed", rssLink);
        }
Exemple #10
0
        public void GetPostEditLink_returns_relative_url_starts_with_slash()
        {
            var postId   = 1;
            var editLink = BlogRoutes.GetPostEditLink(postId);

            Assert.Equal("/admin/compose/1", editLink);
        }
        /// <summary>
        /// Returns previewing of a single post.
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="day"></param>
        /// <param name="slug"></param>
        /// <returns></returns>
        public async Task <IActionResult> Preview(int year, int month, int day, string slug)
        {
            try
            {
                // Get back blog post from TempData
                DateTime dt       = new DateTime(year, month, day);
                var      link     = BlogRoutes.GetPostPreviewRelativeLink(dt, slug);
                var      blogPost = TempData.Get <BlogPost>(link);

                // Prep it
                blogPost.Body = _shortcodeSvc.Parse(blogPost.Body);
                blogPost.Body = OembedParser.Parse(blogPost.Body);
                var blogSettings = await _settingSvc.GetSettingsAsync <BlogSettings>();

                blogSettings.DisqusShortname = ""; // when preview turn off disqus
                var vm = new BlogPostViewModel(blogPost, blogSettings, Request);

                // Show it
                return(View("Post", vm));
            }
            catch (Exception)
            {
                // when user access the preview link directly or when user clicks on other links
                // and navigates away during the preview, hacky need to find a better way.
                return(RedirectToAction("ErrorCode", "Home", new { statusCode = 404 }));
            }
        }
Exemple #12
0
        // -------------------------------------------------------------------- Private Methods

        /// <summary>
        /// Returns posts, total posts and post statuses.
        /// </summary>
        /// <param name="status">The post status <see cref="EPostStatus"/></param>
        /// <param name="pageNumber">Which page, 1-based.</param>
        /// <param name="pageSize">How many rows per page</param>
        /// <returns></returns>
        /// <remarks>
        /// I did a workaround for tabs, couldn't get "statuses" to work as the tab is not initially selected.
        /// </remarks>
        private async Task <PostListVM> GetPostListVmAsync(string status, int pageNumber, int pageSize)
        {
            var postList = status.Equals("published", StringComparison.InvariantCultureIgnoreCase) ?
                           await _blogSvc.GetPostsAsync(pageNumber, pageSize) :
                           await _blogSvc.GetPostsForDraftsAsync(); // TODO drafts need pagination too

            var postVms = from p in postList.Posts
                          select new PostVM
            {
                Id       = p.Id,
                Title    = p.Title,
                Date     = p.CreatedOn.ToString("yyyy-MM-dd"),
                Author   = p.User.DisplayName,
                EditLink = BlogRoutes.GetPostEditLink(p.Id),
                PostLink = $"{Request.Scheme}://{Request.Host}" + BlogRoutes.GetPostRelativeLink(p.CreatedOn, p.Slug),
            };

            var postCount = await _blogSvc.GetPostCountAsync();

            // prep vm
            return(new PostListVM
            {
                Posts = postVms,
                TotalPosts = postList.PostCount,
                PublishedCount = postCount.Published,
                DraftCount = postCount.Draft,
            });
        }
Exemple #13
0
        /// <summary>
        /// Displays either a list of parents or a parent with its child pages.
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public async Task OnGetAsync(int parentId)
        {
            var pageVMs = await GetPageVMsAsync(parentId);

            PagesJson    = JsonConvert.SerializeObject(pageVMs);
            ParentId     = parentId;
            AddChildLink = parentId > 0 ? BlogRoutes.GetAddChildPageLink(parentId) : "";
        }
Exemple #14
0
        private string GetPostAbsoluteUrl(Blog.Models.Page page)
        {
            var relativeUrl = page.IsParent ?
                              BlogRoutes.GetPageRelativeLink(page.Slug) :
                              BlogRoutes.GetPageRelativeLink(page.Parent.Slug, page.Slug);

            return($"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}{relativeUrl}");
        }
Exemple #15
0
        public async Task <BlogPostVM> GetBlogPostVMAsync(BlogPost blogPost)
        {
            var coreSettings = await settingService.GetSettingsAsync <CoreSettings>();

            var blogSettings = await settingService.GetSettingsAsync <BlogSettings>();

            var permalinkPart    = BlogRoutes.GetPostPermalink(blogPost.Id);
            var relativeLink     = BlogRoutes.GetPostRelativeLink(blogPost.CreatedOn, blogPost.Slug);
            var requestHostShort = request.Host.ToString().StartsWith("www.") ?
                                   request.Host.ToString().Remove(0, 4) :
                                   request.Host.ToString();
            var permalinkShort = $"{request.Scheme}://{requestHostShort}{permalinkPart}";

            var hash = "";

            if (blogPost.Tags.Count > 0)
            {
                var sb = new StringBuilder();
                for (int i = 0; i < blogPost.Tags.Count; i++)
                {
                    var tag = blogPost.Tags[i];
                    sb.Append(tag.Slug.Replace("-", ""));
                    if (i < blogPost.Tags.Count - 1)
                    {
                        sb.Append(",");
                    }
                }
                hash = sb.ToString();
            }

            return(new BlogPostVM
            {
                Title = blogPost.Title,
                Body = blogPost.Body,
                Excerpt = blogPost.Excerpt,
                Author = blogPost.User.DisplayName,
                CreatedOn = blogPost.CreatedOn,
                CreatedOnDisplay = blogPost.CreatedOn.ToDisplayString(coreSettings.TimeZoneId),
                Tags = blogPost.Tags.OrderBy(t => t.Title).ToList(),
                Category = blogPost.Category,
                ViewCount = blogPost.ViewCount,

                RelativeLink = relativeLink,
                Permalink = $"{request.Scheme}://{request.Host}{permalinkPart}",
                CanonicalUrl = $"{request.Scheme}://{request.Host}{relativeLink}",
                EditLink = BlogRoutes.GetPostEditLink(blogPost.Id),

                DisqusPageIdentifier = $"{ECommentTargetType.BlogPost}_{blogPost.Id}",
                ShowDisqus = blogSettings.AllowComments && blogSettings.CommentProvider == ECommentProvider.Disqus && !blogSettings.DisqusShortname.IsNullOrEmpty(),
                DisqusShortname = blogSettings.DisqusShortname,

                TwitterShareLink = hash.IsNullOrEmpty() ?
                                   $"https://twitter.com/intent/tweet?text={blogPost.Title}&url={permalinkShort}" :
                                   $"https://twitter.com/intent/tweet?text={blogPost.Title}&url={permalinkShort}&hashtags={hash}",
                FacebookShareLink = $"https://www.facebook.com/sharer/sharer.php?u={permalinkShort}",
                LinkedInShareLink = $"http://www.linkedin.com/shareArticle?mini=true&url={permalinkShort}&title={blogPost.Title}",
            });
        }
Exemple #16
0
        public void GetPostPreviewRelativeLink_returns_relative_link_starts_with_slash()
        {
            var createdOn    = new DateTimeOffset(2018, 9, 9, 0, 0, 0, TimeSpan.Zero);
            var slug         = "my-post";
            var relativeLink = BlogRoutes.GetPostPreviewRelativeLink(createdOn, slug);

            Assert.StartsWith("/", relativeLink);
            Assert.Equal("/preview/post/2018/09/09/my-post", relativeLink);
        }
Exemple #17
0
        public void GetArchiveRelativeLink_returns_link_starts_with_slash_and_2digit_month()
        {
            var year         = 2018;
            var month        = 9;
            var relativeLink = BlogRoutes.GetArchiveRelativeLink(year, month);

            Assert.StartsWith("/", relativeLink);
            Assert.Equal("/posts/2018/09", relativeLink);
        }
Exemple #18
0
        /// <summary>
        /// Returns preview url.
        /// </summary>
        /// <param name="pageIM"></param>
        /// <returns></returns>
        public async Task <JsonResult> OnPostPreviewAsync([FromBody] PageIM pageIM)
        {
            // title
            var title = pageIM.Title.IsNullOrEmpty() ? "Untitled" : pageIM.Title;

            // slug
            var slug = PageService.SlugifyPageTitle(title);

            // parent slug
            var parentSlug = "";

            if (pageIM.ParentId.HasValue && pageIM.ParentId > 0)
            {
                var parent = await pageService.GetAsync(pageIM.ParentId.Value);

                parentSlug = parent.Slug;
            }

            // body
            var body = PageService.ParseNavLinks(pageIM.Body,
                                                 parentSlug.IsNullOrEmpty() ? slug : parentSlug);

            // author
            var user = await userManager.GetUserAsync(HttpContext.User);

            var author = user.DisplayName;

            // date
            var coreSettings = await settingService.GetSettingsAsync <CoreSettings>();

            var date = DateTimeOffset.Parse(pageIM.PostDate).ToDisplayString(coreSettings.TimeZoneId);

            // layout
            var pageLayout = pageIM.PageLayout;

            // preview relative link (the slugs are url encoded)
            var prevRelLink = parentSlug.IsNullOrEmpty() ?
                              BlogRoutes.GetPagePreviewRelativeLink(slug) :
                              BlogRoutes.GetPagePreviewRelativeLink(parentSlug, slug);

            // put vm in tempdata with preview link as key
            var pageVM = new PageVM
            {
                Author           = author,
                Body             = body,
                CreatedOnDisplay = date,
                Title            = title,
                PageLayout       = pageLayout,
            };

            TempData.Put(prevRelLink, pageVM);

            // return preview url
            return(new JsonResult($"{Request.Scheme}://{Request.Host}{prevRelLink}"));
        }
Exemple #19
0
        private void RegisterRoutes(IRouteBuilder routes, IApplicationBuilder app)
        {
            routes.MapRoute("Home", "", new { controller = "Blog", action = "Index" });
            routes.MapRoute("Setup", "setup", new { controller = "Home", action = "Setup" });
            routes.MapRoute("About", "about", new { controller = "Home", action = "About" });
            routes.MapRoute("Contact", "contact", new { controller = "Home", action = "Contact" });
            routes.MapRoute("Admin", "admin", new { controller = "Home", action = "Admin" });

            BlogRoutes.RegisterRoutes(routes);

            routes.MapRoute(name: "Default", template: "{controller=Home}/{action=Index}/{id?}");
        }
Exemple #20
0
        public BlogPostViewModel(BlogPost blogPost, BlogSettings blogSettings, HttpRequest request)
        {
            Title            = blogPost.Title;
            Body             = blogPost.Body;
            Excerpt          = blogPost.Excerpt;
            Author           = blogPost.User.DisplayName;
            CreatedOn        = blogPost.CreatedOn;
            CreatedOnDisplay = blogPost.CreatedOnDisplay;
            Tags             = blogPost.Tags.OrderBy(t => t.Title).ToList();
            Category         = blogPost.Category;

            RelativeLink = BlogRoutes.GetPostRelativeLink(CreatedOn, blogPost.Slug);
            var permalinkPart = BlogRoutes.GetPostPermalink(blogPost.Id);

            Permalink    = $"{request.Scheme}://{request.Host}{permalinkPart}";
            CanonicalUrl = $"{request.Scheme}://{request.Host}{RelativeLink}";
            EditLink     = BlogRoutes.GetPostEditLink(blogPost.Id);

            DisqusPageIdentifier = $"{ECommentTargetType.BlogPost}_{blogPost.Id}";
            ShowDisqus           = blogSettings.AllowComments && blogSettings.CommentProvider == ECommentProvider.Disqus && !blogSettings.DisqusShortname.IsNullOrEmpty();
            DisqusShortname      = blogSettings.DisqusShortname;

            var hash = "";

            if (blogPost.Tags.Count > 0)
            {
                var sb = new StringBuilder();
                for (int i = 0; i < blogPost.Tags.Count; i++)
                {
                    var tag = blogPost.Tags[i];
                    sb.Append(tag.Slug.Replace("-", ""));
                    if (i < blogPost.Tags.Count - 1)
                    {
                        sb.Append(",");
                    }
                }
                hash = sb.ToString();
            }

            var requestHostShort = request.Host.ToString().StartsWith("www.") ?
                                   request.Host.ToString().Remove(0, 4) : request.Host.ToString();
            var permalinkShort = $"{request.Scheme}://{requestHostShort}{permalinkPart}";

            TwitterShareLink = hash.IsNullOrEmpty() ?
                               $"https://twitter.com/intent/tweet?text={Title}&url={permalinkShort}" :
                               $"https://twitter.com/intent/tweet?text={Title}&url={permalinkShort}&hashtags={hash}";
            FacebookShareLink = $"https://www.facebook.com/sharer/sharer.php?u={permalinkShort}";
            GoogleShareLink   = $"https://plus.google.com/share?url={permalinkShort}";
            LinkedInShareLink = $"http://www.linkedin.com/shareArticle?mini=true&url={permalinkShort}&title={Title}";
        }
        public async void GetCategoriesAsync_Test()
        {
            // Arrange
            SeedTestPosts(11);

            // Act
            var metaCatList = await _svc.GetCategoriesAsync(BLOG_ID, USERNAME, PASSWORD, ROOT_URL);

            var catUrl = BlogRoutes.GetCategoryRelativeLink(CAT_SLUG);

            // Assert
            Assert.Single(metaCatList);
            Assert.Equal($"{ROOT_URL}{catUrl}", metaCatList[0].HtmlUrl);
        }
Exemple #22
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
#if DEBUG
                app.UseBrowserLink();
#endif
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UsePreferredDomain();
            app.UseSetup();
            app.MapWhen(context => context.Request.Path.ToString().Equals("/olw"), appBuilder => appBuilder.UseMetablog());
            app.UseStatusCodePagesWithReExecute("/Home/ErrorCode/{0}"); // needs to be after hsts and rewrite
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseCookiePolicy();
            app.UseSession(); // for TempData only
            app.UsePlugins(env);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("Home", "", new { controller = "Home", action = "Index" });
                BlogRoutes.RegisterRoutes(endpoints);
                endpoints.MapControllerRoute(name: "Default", pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

            using var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope();
            var db = serviceScope.ServiceProvider.GetService <FanDbContext>();
            if (!db.Database.ProviderName.Equals("Microsoft.EntityFrameworkCore.InMemory"))
            {
                db.Database.Migrate();
            }
        }
Exemple #23
0
        public async Task <IViewComponentResult> InvokeAsync(Widget widget)
        {
            var recentBlogPostsWidget = (RecentBlogPostsWidget)widget;
            // ask for 1 more than number of posts to show
            var postList = await blogPostService.GetRecentPublishedPostsAsync(recentBlogPostsWidget.NumberOfPostsToShow + 1);

            // must have at least 2 posts
            if (postList.TotalPostCount < 2)
            {
                return(await Task.FromResult <IViewComponentResult>(Content(string.Empty)));
            }

            // get current url
            var relativeUrl = httpContextAccessor.HttpContext.Request.Path;
            var list        = new List <RecentPostViewModel>();

            foreach (var post in postList.Posts)
            {
                // if post url is current url then skip this post
                var postUrl = BlogRoutes.GetPostRelativeLink(post.CreatedOn, post.Slug);
                if (postUrl.Equals(relativeUrl, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                list.Add(new RecentPostViewModel
                {
                    Title   = post.Title,
                    Link    = BlogRoutes.GetPostPermalink(post.Id),
                    Author  = post.User.DisplayName,
                    Excerpt = recentBlogPostsWidget.ShowPostExcerpt ? post.Excerpt : null,
                    Date    = recentBlogPostsWidget.ShowPostDate ? post.CreatedOn.ToString("yyyy-MM-dd") : null,
                });

                if (list.Count >= recentBlogPostsWidget.NumberOfPostsToShow)
                {
                    break;
                }
            }

            return(View("~/Components/RecentBlogPosts.cshtml",
                        new Tuple <List <RecentPostViewModel>, RecentBlogPostsWidget>(list, recentBlogPostsWidget)));
        }
Exemple #24
0
 private MetaPost ToMetaPost(BlogPost blogPost, string rootUrl)
 {
     return(new MetaPost
     {
         AuthorId = blogPost.UserId.ToString(),
         Categories = new List <string> {
             blogPost.CategoryTitle
         },
         CommentPolicy = (blogPost.CommentStatus == ECommentStatus.AllowComments ||
                          blogPost.CommentStatus == ECommentStatus.AllowCommentsWithApproval) ? "1" : "0",
         Description = blogPost.Body,
         Excerpt = blogPost.Excerpt,
         PostDate = blogPost.CreatedOn,
         PostId = blogPost.Id.ToString(),
         Publish = blogPost.Status == EPostStatus.Published,
         Slug = blogPost.Slug,
         Tags = blogPost.TagTitles,
         Title = blogPost.Title,
         Link = rootUrl + BlogRoutes.GetPostRelativeLink(blogPost.CreatedOn, blogPost.Slug),
     });
 }
Exemple #25
0
        public async Task <IActionResult> PreviewPost(int year, int month, int day, string slug)
        {
            try
            {
                // Get back blog post from TempData
                DateTime dt       = new DateTime(year, month, day);
                var      link     = BlogRoutes.GetPostPreviewRelativeLink(dt, slug);
                var      blogPost = TempData.Get <BlogPost>(link);

                // Prep vm
                var blogPostVM = await blogViewModelHelper.GetBlogPostVMPreviewAsync(blogPost);

                // Show it
                return(View("Post", blogPostVM));
            }
            catch (Exception)
            {
                // when user access the preview link directly or when user clicks on other links
                // and navigates away during the preview, hacky need to find a better way.
                return(RedirectToAction("ErrorCode", "Home", new { statusCode = 404 }));
            }
        }
Exemple #26
0
        public async Task <string> GetNavUrlAsync(int id)
        {
            var cat = await GetAsync(id);

            return(BlogRoutes.GetCategoryRelativeLink(cat.Slug));
        }
Exemple #27
0
        public async Task <IViewComponentResult> InvokeAsync(Widget widget)
        {
            if (widget == null || !Request.Path.HasValue)
            {
                return(await Task.FromResult <IViewComponentResult>(Content(string.Empty)));
            }

            // slugs
            var slugs = Request.Path.Value.Split('/', StringSplitOptions.RemoveEmptyEntries);

            // if no slugs or first slug is reserved when it's not preview, return empty
            if (slugs.Length <= 0 ||
                (slugs[0].ToLower() != "preview" && Array.IndexOf(PageService.Reserved_Slugs, slugs[0].ToLower()) != -1))
            {
                return(await Task.FromResult <IViewComponentResult>(Content(string.Empty)));
            }

            // page
            Page page;

            if (slugs[0].ToLower() == "preview")
            {
                var composePageId = GetComposeUrlPageId();
                if (composePageId == 0)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content(string.Empty)));
                }

                page = await pageService.GetAsync(composePageId);
            }
            else
            {
                page = await pageService.GetAsync(slugs);
            }

            // visible only parent has children
            if (page.IsParent && !page.HasChildren)
            {
                return(await Task.FromResult <IViewComponentResult>(Content(string.Empty)));
            }

            // nav str
            string navBody;
            int    pageId;

            if (page.IsParent)
            {
                navBody = PageService.NavMdToHtml(page.Nav, page.Slug);
                pageId  = page.Id;
            }
            else
            {
                var parent = await pageService.GetAsync(page.ParentId.Value);

                navBody = PageService.NavMdToHtml(parent.Nav, parent.Slug);
                pageId  = parent.Id;
            }

            // edit link
            var editNavLink = BlogRoutes.GetPageNavEditLink(pageId);

            // wid
            var pageNavigationWidget = (PageNavigationWidget)widget;

            return(View("~/Components/PageNavigation.cshtml",
                        new PageNavigationVM {
                NavBody = navBody,
                NavEditLink = editNavLink,
                WidgetTitle = pageNavigationWidget.Title
            }));
        }
Exemple #28
0
        // -------------------------------------------------------------------- private methods

        private string GetPostAbsoluteUrl(BlogPost blogPost)
        {
            var relativeUrl = BlogRoutes.GetPostRelativeLink(blogPost.CreatedOn, blogPost.Slug);

            return($"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}{relativeUrl}");
        }
        public async Task <IActionResult> PostPerma(int id)
        {
            var post = await _blogSvc.GetAsync(id);

            return(Redirect(BlogRoutes.GetPostRelativeLink(post.CreatedOn, post.Slug)));
        }
Exemple #30
0
        /// <summary>
        /// Returns a list of <see cref="PageAdminVM"/>, when <paramref name="parentId"/> is present
        /// the returned list contains the parent and its children, otherwise a list of parents are
        /// returned.
        /// </summary>
        /// <param name="parentId"></param>
        /// <remarks>
        /// When a page or its parent is draft, its PageLink is null.
        /// </remarks>
        private async Task <List <PageAdminVM> > GetPageVMsAsync(int parentId)
        {
            var pageVMs = new List <PageAdminVM>();
            IList <Blog.Models.Page> pages;
            bool isChild = false;

            Fan.Blog.Models.Page parent = null;
            var coreSettings            = await settingService.GetSettingsAsync <CoreSettings>();

            if (parentId <= 0)
            {
                pages = await pageService.GetParentsAsync(withChildren : true);
            }
            else
            {
                parent = await pageService.GetAsync(parentId);

                pages   = parent.Children;
                isChild = true;

                pageVMs.Add(new PageAdminVM
                {
                    Id       = parent.Id,
                    Title    = parent.Title,
                    Date     = parent.CreatedOn.ToLocalTime(coreSettings.TimeZoneId).ToString(POST_DATE_STRING_FORMAT),
                    Author   = parent.User.DisplayName,
                    EditLink = BlogRoutes.GetPageEditLink(parent.Id),
                    IsDraft  = parent.Status == EPostStatus.Draft,
                    PageLink = parent.Status == EPostStatus.Draft ? null :
                               $"{Request.Scheme}://{Request.Host}" + BlogRoutes.GetPageRelativeLink(parent.Slug),
                    ChildCount = parent.Children.Count,
                    ViewCount  = parent.ViewCount,
                });
            }

            foreach (var page in pages)
            {
                var pageLink = parent != null && parent.Status == EPostStatus.Published?
                               $"{Request.Scheme}://{Request.Host}" + BlogRoutes.GetPageRelativeLink(parent.Slug, page.Slug) :
                               $"{Request.Scheme}://{Request.Host}" + BlogRoutes.GetPageRelativeLink(page.Slug);

                pageLink = page.Status == EPostStatus.Draft || (parent != null && parent.Status == EPostStatus.Draft) ? null : pageLink;

                pageVMs.Add(new PageAdminVM
                {
                    Id           = page.Id,
                    Title        = page.Title,
                    Date         = page.CreatedOn.ToLocalTime(coreSettings.TimeZoneId).ToString(POST_DATE_STRING_FORMAT),
                    Author       = page.User.DisplayName,
                    ChildrenLink = !isChild && page.Children.Count > 0 ? $"{Request.Path}/{page.Id}" : "",
                    EditLink     = BlogRoutes.GetPageEditLink(page.Id),
                    PageLink     = pageLink,
                    IsChild      = isChild,
                    IsDraft      = page.Status == EPostStatus.Draft,
                    ChildCount   = isChild ? 0 : page.Children.Count,
                    ViewCount    = page.ViewCount,
                });
            }

            return(pageVMs);
        }