How to display one category posts by default?

Topics: Controls, Themes
Mar 9, 2012 at 9:08 AM

My blog has various categories like:

  • Life
  • Technology
  • Thoughts

But it is primarily a Tech blog. Even though I post all types of posts in the above categories, I want it to display posts of Tech category by default.

Users can select other category to see posts related to that category, but as and when blog is opened, it should display Tech category only.

Coordinator
Mar 10, 2012 at 9:36 AM

Depending on what version of BE you are running, in default.aspx.cs, in Page_Load() towards the bottom if none of the conditions above have matched (Tag, Category, Author, Date Range, etc), you can add this code.

Category techCategory = Category.Categories.Find(
	delegate(Category c) { return c.Title == "Technology"; });
	
if (techCategory != null)
{
	PostList1.Posts = techCategory.Posts.ConvertAll(
		new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
}

Mar 10, 2012 at 9:50 AM

I also want to display the categories as Tabs on top. My blog is located here.

Coordinator
Mar 15, 2012 at 12:27 PM

The categories are available via Category.Categories.  You could add a Repeater control or ListView control to your master page (site.master) and bind Category.Categories to that control.  Or you could iterate thru the categories, building up a string and outputting that string to the page.  The menu area is defined in site.master, so that's where you will want to output the categories.  Hopefully this isn't old information you are already aware of.

Jun 12, 2012 at 9:30 AM

Along the same lines, might there be a simple way to have a menu item href automatically link to an actual post when the post count for that menu item = 1? Currently the behavior is click on root menu item, and if only a single post exists, display that one post in CustomPostView, which then must be clicked again to view the actual content of that single post, would be very useful to automate this behavior when only one post option is present. 

Thanks

Jun 13, 2012 at 9:49 PM

lastuser,

Adding this code to DisplayCategories() in default.aspx.cs will do the job for you.

-Dave

private void DisplayCategories()
{
    if (!String.IsNullOrEmpty(Request.QueryString["id"]))
    {
        Guid categoryId = new Guid(Request.QueryString["id"]);
        Category cat = Category.GetCategory(categoryId);

        // Will redirect to post page if Single Post in Category

        bool singlePost = cat.Posts.FindAll(delegate(Post post)
        {
            return post.IsVisible;
        }).Count == 1;

        if (singlePost)
        {
            Post _post = cat.Posts.FirstOrDefault(p => p.IsVisible);
            Response.Redirect(_post.RelativeLink);
        }

        // End of Single Post Addition
        
        PostList1.ContentBy = ServingContentBy.Category;
        PostList1.Posts = Post.GetPostsByCategory(categoryId).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
        Page.Title = Category.GetCategory(categoryId).Title;
    }
}

Jun 15, 2012 at 3:08 PM

Thank you very much, that's much more elegant than the approach I was planning, cheers.

Nov 19, 2012 at 8:42 PM

Nice one Dave, 

Came across this thread whilst looking for something else and liked the idea.

Thought it might be useful to have this for browse by date, tag and author, so added this function in default:

 private void IfSinglePostRedirect()
    {
        if (PostList1.Posts != null && PostList1.Posts.Count == 1)
        {
            Response.Redirect(PostList1.Posts[0].RelativeLink);
        }
    }

Then you just call it after you populate PostList1.Posts in the desired display methods, i.e.

private void DisplayAuthors()
    {
        if (!string.IsNullOrEmpty(Request.QueryString["name"]))
        {
            string author = Server.UrlDecode(Request.QueryString["name"]);
            PostList1.ContentBy = ServingContentBy.Author;
            PostList1.Posts = Post.GetPostsByAuthor(author).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
            IfSinglePostRedirect();
            AuthorProfile ap = AuthorProfile.GetProfile(author);
            if (ap != null)
            {
                author = ap.DisplayName;
            }
            Title = Resources.labels.author + ": " + Server.HtmlEncode(author);
        }
    }
Seems to work well, cheers.

Mar 3, 2013 at 4:23 PM
Did you know if is it possibile to use this tecnique to display all post, but excluding certain category post?
For example, I create a 'no-homepage' category and, after, I display all posts in homepage without this category.

Many thanks in advance, have a nice day
Mar 4, 2013 at 10:32 AM
Well, I changed method: now I create a 'category' named Home, and every post labeled with this category will display in homepage, but when I open a link with another category it displays the same post as home page.
This is the code of my default.aspx.cs
Please, can someone help me to fix it?
#region Using

using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using System.Collections.Generic;
using BlogEngine.Core;
using System.Web.UI;

#endregion

public partial class _default : BlogEngine.Core.Web.Controls.BlogBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsCallback)
            return;
        
        if (Request.RawUrl.ToLowerInvariant().Contains("/category/"))
        {
            DisplayCategories();
        }
        else if (Request.RawUrl.ToLowerInvariant().Contains("/author/"))
        {
            DisplayAuthors();
        }
        else if (Request.RawUrl.ToLowerInvariant().Contains("?tag="))
        {
            DisplayTags();
        }
        else if (Request.QueryString["year"] != null || Request.QueryString["date"] != null || Request.QueryString["calendar"] != null)
        {
            if (Request.RawUrl.Contains("year="))
                Redirect();
            else
                DisplayDateRange();
        }
        else if (Request.QueryString["apml"] != null)
        {
            DisplayApmlFiltering();
        }
        else
        {           
            if (!BlogSettings.Instance.UseBlogNameInPageTitles)
                Page.Title = BlogSettings.Instance.Name + " | ";

            if (!string.IsNullOrEmpty(BlogSettings.Instance.Description))
                Page.Title += Server.HtmlEncode(BlogSettings.Instance.Description);
        }
        Category techCategory = Category.Categories.Find(
    delegate(Category c) { return c.Title == "Home"; });
    
if (techCategory != null)
{
    PostList1.Posts = techCategory.Posts.ConvertAll(
        new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
}

        AddMetaKeywords();
        base.AddMetaTag("description", Server.HtmlEncode(BlogSettings.Instance.Description));
        base.AddMetaTag("author", Server.HtmlEncode(BlogSettings.Instance.AuthorName));
        
    }

    private void DisplayApmlFiltering()
    {
        Uri url = null;
        if (Uri.TryCreate(Request.QueryString["apml"], UriKind.Absolute, out url))
        {
            Page.Title = "APML filtered list";
            try
            {
                Dictionary<Uri, XmlDocument> docs = Utils.FindSemanticDocuments(url, "apml");
                if (docs.Count > 0)
                {
                    foreach (Uri key in docs.Keys)
                    {
                        PostList1.ContentBy = ServingContentBy.Apml;
                        PostList1.Posts = Search.ApmlMatches(docs[key], 30).FindAll(delegate(IPublishable p) { return p is Post; });
                        PostList1.Posts.Sort(delegate(IPublishable ip1, IPublishable ip2) { return ip2.DateCreated.CompareTo(ip1.DateCreated); });
                        Page.Title += " for " + Server.HtmlEncode(key.Host);
                        break;
                    }
                }
                else
                {
                    divError.InnerHtml = "<h1 style=\"text-align:center\">APML document could not be found</h1><br /><br />";
                    Page.Title = "APML not found";
                }
            }
            catch (NotSupportedException)
            {
                divError.InnerHtml = "<h1 style=\"text-align:center\">The website entered doesn't contain any information about APML</h1><br /><br />";
                Page.Title = "APML not found";
            }
            catch (System.Net.WebException)
            {
                divError.InnerHtml = "<h1 style=\"text-align:center\">Sorry, I couldn't connect to your website</h1><br /><br />";
                Page.Title = "APML address invalid";
            }
            catch (XmlException)
            {
                divError.InnerHtml = "<h1 style=\"text-align:center\">The APML document is not valid XML</h1><br /><br />";
                Page.Title = "APML document error";
            }
        }
        else if (PostList1.Posts == null || PostList1.Posts.Count == 0)
        {
            divError.InnerHtml = "<h1 style=\"text-align:center\">The URL could not be resolved</h1><br /><br />";
            Page.Title = "APML not found";
        }
    }
    private void Redirect()
    {
        string year = Request.QueryString["year"];
        string month = Request.QueryString["month"];
        string date = Request.QueryString["date"];
        string page = string.IsNullOrEmpty(Request.QueryString["page"]) ? string.Empty : "?page=" + Request.QueryString["page"];
        string rewrite = null;

        if (!string.IsNullOrEmpty(date))
        {
            DateTime dateParsed = DateTime.Parse(date);
            rewrite = Utils.RelativeWebRoot + dateParsed.Year + "/" + dateParsed.Month + "/" + dateParsed.Day + "/default.aspx";
        }
        else if (!string.IsNullOrEmpty(year) && !string.IsNullOrEmpty(month))
        {
            rewrite = Utils.RelativeWebRoot + year + "/" + month + "/default.aspx"; 
        }
        else if (!string.IsNullOrEmpty(year))
        {
            rewrite = Utils.RelativeWebRoot + year + "/default.aspx";
        }

        if (rewrite != null)
        {
            Response.Clear();
            Response.StatusCode = 301;
            Response.AppendHeader("location", rewrite + page);
            Response.End();
        }
    }

    private static readonly Regex YEAR_MONTH = new Regex("/([0-9][0-9][0-9][0-9])/([0-1][0-9])", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    private static readonly Regex YEAR_MONTH_DAY = new Regex("/([0-9][0-9][0-9][0-9])/([0-1][0-9])/([0-3][0-9])", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    private void AddMetaKeywords()
    {
        if (Category.Categories.Count > 0)
        {
            string[] categories = new string[Category.Categories.Count];
            for (int i = 0; i < Category.Categories.Count; i++)
            {
                categories[i] = Category.Categories[i].Title;
            }

            string metakeywords = Server.HtmlEncode(string.Join(",", categories));
            System.Web.UI.HtmlControls.HtmlMeta tag = null;
            foreach (Control c in Page.Header.Controls)
            {
                if (c is System.Web.UI.HtmlControls.HtmlMeta && (c as System.Web.UI.HtmlControls.HtmlMeta).Name.ToLower() == "keywords")
                {
                    tag = c as System.Web.UI.HtmlControls.HtmlMeta;
                    tag.Content += ", " + metakeywords;
                    break;
                }
            }
            if (tag == null)
            {
                base.AddMetaTag("keywords", metakeywords);
            } 

        }
    }
    private void DisplayCategories()
{
    if (!String.IsNullOrEmpty(Request.QueryString["id"]))
    {
        Guid categoryId = new Guid(Request.QueryString["id"]);
        Category cat = Category.GetCategory(categoryId);

        PostList1.ContentBy = ServingContentBy.Category;
        PostList1.Posts = Post.GetPostsByCategory(categoryId).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
        Page.Title = Category.GetCategory(categoryId).Title;
    }
}


    private void DisplayAuthors()
    {
        if (!string.IsNullOrEmpty(Request.QueryString["name"]))
        {
            string author = Server.UrlDecode(Request.QueryString["name"]);
            PostList1.ContentBy = ServingContentBy.Author;
            PostList1.Posts = Post.GetPostsByAuthor(author).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
            IfSinglePostRedirect();
                       AuthorProfile ap = AuthorProfile.GetProfile(author);
            if (ap != null)
            {
                author = ap.DisplayName;
            }

            Title = "All posts by " + Server.HtmlEncode(author);
        }
    }

    private void DisplayTags()
    {
        if (!string.IsNullOrEmpty(Request.QueryString["tag"]))
        {
            PostList1.ContentBy = ServingContentBy.Tag;
            PostList1.Posts = Post.GetPostsByTag(Request.QueryString["tag"].Substring(1)).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
            base.Title = " All posts tagged '" + Request.QueryString["tag"].Substring(1) + "'";

        }
    }

    private void DisplayDateRange()
    {
        string year = Request.QueryString["year"];
        string month = Request.QueryString["month"];
        string specificDate = Request.QueryString["date"];

        if (!string.IsNullOrEmpty(year) && !string.IsNullOrEmpty(month))
        {
            DateTime dateFrom = DateTime.Parse(year + "-" + month + "-01", CultureInfo.InvariantCulture);
            DateTime dateTo = dateFrom.AddMonths(1).AddMilliseconds(-1);
            PostList1.ContentBy = ServingContentBy.DateRange;
            PostList1.Posts = Post.GetPostsByDate(dateFrom, dateTo).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
            Title = dateFrom.ToString("MMMM yyyy");
        }
        else if (!string.IsNullOrEmpty(year))
        {
            DateTime dateFrom = DateTime.Parse(year + "-01-01", CultureInfo.InvariantCulture);
            DateTime dateTo = dateFrom.AddYears(1).AddMilliseconds(-1);
            PostList1.ContentBy = ServingContentBy.DateRange;
            PostList1.Posts = Post.GetPostsByDate(dateFrom, dateTo).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; })); ;
            Title = dateFrom.ToString("yyyy");
        }
        else if (!string.IsNullOrEmpty(specificDate) && specificDate.Length == 10)
        {
            DateTime date = DateTime.Parse(specificDate, CultureInfo.InvariantCulture);
            PostList1.ContentBy = ServingContentBy.DateRange;
            PostList1.Posts = Post.GetPostsByDate(date, date).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; })); ;
            Title = date.ToString("MMMM d. yyyy");
        }
        else if (!string.IsNullOrEmpty(Request.QueryString["calendar"]))
        {
            calendar.Visible = true;
            PostList1.Visible = false;
            Title = Server.HtmlEncode(Resources.labels.calendar);
        }
    }
    private void IfSinglePostRedirect()
    {
        if (PostList1.Posts != null && PostList1.Posts.Count == 1)
        {
            Response.Redirect(PostList1.Posts[0].RelativeLink);
        }
    }
}