Adding a summary to Orchard blog posts - refining the code

After putting together my post yesterday about adding a Summary field to blog posts, Sébastien Ros dropped a comment pointing out a tidier way to access the Summary property, giving this:

post.ContentItem.BlogPost.Summary.Value

Instead of this:

post.ContentItem.BlogPost.Fields[0].Value

As far as length of code goes, it's not gaining much. The big benefit here is code clarity, whether or not it takes shorter/longer to execute is something that might need to be measured (but not for the level of traffic my blog gets!), but the maintainability of the code has just shot up by a huge factor. No magic numbers, no retrieving from what looks like an array (but isn't), in fact the only way this could be clearer with regards to what it's doing is if the Summary property was accessed from a Fields property of the BlogPost.

Now, I decided to do a quick check and see if I could pare the original code back to something like:

var summaryText = post.ContentItem.BlogPost.Summary?.Value;

i.e. Use the null propagating operator and strip out all the gubbins and distill the code down to the minimum required. Unfortunately, Visual Studio (and IIS at runtime) threw a wobbly at this. Through the wonders of search, I found a solution that works, Using C# 6.0 features in ASP.NET Razor view engine - which is basically Roslyn-up Orchard. The very short version is:

PM> Install-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform

Yup, install a NuGet package. Once that's done, and the solution is re-built, the bit of code I have for rendering the summary field into recent post lists has shrunk down to a much tidier:

var summaryText = post.ContentItem.BlogPost.Summary?.Value;

<li>
    <h5>
        @Html.ItemDisplayLink(title, contentItem)<br />
        @if (!string.IsNullOrWhiteSpace(summaryText))
        {
            @summaryText
            <br />
        }
        <small>@T("Posted") @date.ToShortDateString()</small>
    </h5>
</li>

This is all working in my local copy of Orchard, running in Visual Studio, so the next step (for the null propagating operator tweak) is to Beyond Compare what I've got locally to what's on the server and synch it up to get it working, then I can push my updated theme to it.

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment