My Blog Was Hacked :(

As you can probably tell, if you visited within the last two weeks or so. It also turns out that my hosting is a ridiculous, rubbish piece of junk; I don’t really want to talk about them apart from the fact that they had the gall to try and charge me money for a backup of my stuff – which is cute, as they advertise as having a “complete backup solution” and “no hidden fees”. So yeah. That.

So…I have control back now, I wrestled and got it back, but I can’t be confident everything has been cleaned, so the long term plan is to move all my content off WordPress and move to Azure websites. Watch this space; but at least now all the old content, all the SharePoint tips and other assorted things I’ve blathered on about for the last two years or so is now available again.

Dear script kiddies / hackers – y u do that 2 me :(

Orchard CMS: HQL, Or How To Query Based On Content Fields

I know, I know; you’re thinking – “Why do I even *need* to write my own queries, when there’s a perfectly awesome Query and Projection module in Orchard I can leverage? Well, if you’re building an event calendar, for example, you might want to generate your queries on the fly based on query string parameters; in which case, I don’t know if creating a bunch of Query items is the nicest way to go. (If there’s a nicer, better way of working with parameters/tokens in Queries, let me know; ie if you can add your own custom Tokens / handling to the Query Edit page to have more than Url.Absolute, but I digress)

EDIT: Pretty much immediately after I wrote this post, I noticed that there *is* a Request / Query String you can hook into when using your queries.

Orchard Query with Request

Which pretty much makes this post a little redundant for the original problem it was supposed to solve, but I’ll leave it if you’re interested in the internals. But basically, you can create a Query that varies based on query string, which you can use in a Projection. Problem solved!

So after much step-through debugging and source code diving, I present to you “how Orchard handles Projections / Queries in the back end and how you can too, with HQL”.

Let’s say I want to get a bunch of content items, where the field MyDate lies in a specific month.

First of all, you create a HQL query:

[sourcecode language="c-sharp"]
var matchingEventItems = ContentManager.HqlQuery().ForType("EventItem").ForVersion(VersionOptions.Published);
[/sourcecode]

Then you add some where conditions (you can also add sort conditions, but I leave that as an exercise to work out from the Orchard source code; it’s pretty similar to the Where conditions)

[sourcecode language="c-sharp"]

year = 2013; //just imagine I pulled these in from the query string ;)
month = 3;

long minTicks = new DateTime(year, month, 1).ToUniversalTime().Ticks;
long maxTicks = new DateTime(year, month, 1).AddMonths(1).AddDays(-1).ToUniversalTime().Ticks;

matchingItems = matchingItems.Where(
a => a.ContentPartRecord<FieldIndexPartRecord>().Property("IntegerFieldIndexRecords", "MyContentTypeMyDate"), //gone through "safename", whatever that is – see ContentFieldsFilter.cs in projections
p => p.And(
x => x.Eq("PropertyName", "MyContentType.MyDate."), //this comes from the following code in Orchard Source, but I don’t know what storage name is for; propertyName = String.Join(".", part.Name, field.Name, storageName ?? "");
y => y.And(
date => date.Ge("Value", minTicks),
date => date.Le("Value", maxTicks)
)
)
);

[/sourcecode]

It’s a little bit like CAML from SharePoint, in which you provide lots of Ands, Ors and Eqs to build up your query tree. Note that you’ll need to add a reference to Orchard.Projections for your module (so don’t forget to add a dependency too).

And finally, you slice it to actually execute and get some items for your query. You’ll get back IEnumerable, which you can then use to your hearts’ content. For example, you could pull out the Title for all these items:

[sourcecode language="c-sharp"]
foreach(var item in items)
{
string theTitle = item.As<TitlePart>().Title;
}
[/sourcecode]

If you’re looking to make different queries, the parameters / syntax for the HQL might be a little different – I suggest you put a breakpoint in ProjectionPartDriver and step through to see what’s required.

Orchard CMS: Using A Static ViewModel For Your Driver Display Method

If you look at all the documentation about rendering shapes in Orchard, you’ll see that while the Model for the partial view gets specified for the Editor methods (via shapeHelper.EditorTemplate()), all the examples I came across for Display relied on a dynamic method and generated model. For example:

[sourcecode language="c-sharp"]
protected override DriverResult Display(
MapPart part, string displayType, dynamic shapeHelper)
{
return ContentShape("Parts_Map",
() => shapeHelper.Parts_Map(
Longitude: part.Longitude,
Latitude: part.Latitude));
}
[/sourcecode]

The code above results in a generated model being passed to the view partial, with two properties Longitude and Latitude.

But what if you’ve already got a ViewModel you had in mind for use? I don’t think it’s documented (yet), but if you take a look in CoreShapes.cs, you’ll find where EditorTemplate is implemented, along with its friends, DisplayTemplate() and Partial(). These methods accept a model parameter, so you can happily pass in your view model. Like the EditorTemplate method, DisplayTemplate expects to find the partial view in /Views/DisplayTemplates/, but Partial searches from the base View folder.

[sourcecode language="c-sharp"]
protected override DriverResult Display(MyPart part, string displayType, dynamic shapeHelper)
{

MyPartViewModel model = new MyPartViewModel();

return ContentShape("Parts_MyPart",
() =>
{
return shapeHelper.Partial(
TemplateName: "Parts/MyPart",
Model: model);
}
);

}
[/sourcecode]

The above code will pass the MyPartViewModel through to /Views/Parts/MyPart.cshtml, easy as that.

Orchard CMS: How To Create Content In Your Module Migrations.cs

While I’m on an Orchard streak, here’s something else that I felt sounded easy on paper, but wasn’t well documented.

In the form of a question – “How can I create content (pages, widgets, whatever) when my module is activated?”

To create all content (which again makes judicious use of dynamic objects, since Orchard has no idea what sort of content is being created at compile time / the extension possibilities are endless), Orchard provides the ContentManager class. This magical class is referenced by name in the documentation around content in Orchard, but I didn’t find it very well explained.

So looking at it from a few steps back; the ContentManager class is an implementation of the IContentManager interface – however, you don’t create an instance of the ContentManager class as you may have been expecting. Instead, Orchard loves Inversion of Control and Dependency Injection with the use of the AutoFac library which sounds really complicated, and I guess in a certain light it is, but you don’t have to fully understand the intricacies to be able to get what you want (which in this instance, is a ContentManager class to use).

The steps to get a ContentManager class are:

  1. Have a parameter in your constructor that accepts the type of dependable interface you’re after – in this case, we want IContentManager.
  2. In your constructor, assign the parameter to a variable for later use.

So within our migrations code for our module:

[sourcecode language="c-sharp"]

//variable to store the content manager
private readonly IContentManager _contentManager;

//constructor parameter accepting IDependency classes
public Migrations(IContentManager contentManager)
{
_contentManager = contentManager;
}

public int Create()
{
//we can now use _contentManager!

return 1;
}

[/sourcecode]

So great – we have a ContentManager. How can we use it to, for example, create a List? Simple; call the .Create() method (which has a few overloads, the simplest of which is a string for the Content Type name) and then modify any parts or fields you want (by calling the .As<T>() extension method), then .Publish() it.

For example, you can throw the following into your Create() method in migrations.cs:

[sourcecode language="c-sharp"]

var eventList = _contentManager.Create("List");
eventList.As<TitlePart>().Title = "Sample List";
_contentManager.Publish(eventList);

[/sourcecode]

And there you have it, content creation on module activation! I guess in some instances you could probably be using Recipes as well; but that’s a discussion for another time…

Orchard is great – a lot of really smart thought went into it, and it shows – it’s just a shame that to work out how to do this I had to trawl through a trillion pages, and pieced it together with this blog post, and a half example in the Widgets module. Who knows – maybe you aren’t supposed to do it this way any more, but if not, there’s no documentation about that either ;)

Orchard CMS: Conditional Field Rendering

Following the theme of “wow, that should be easy, but it’s not as fast or easy as you’d think”, here’s my post / answer to the question “How can I show / hide a field on a content type based on the value of another field”?

If you’ve read about shapes in Orchard, and how they combine with the placement.info file to generate the output of your page, you’ll quickly realise that what you really want to find out is how to access content fields from within your .cshtml / shapes. (If you haven’t read about them, I’ll wait here while you do, the links are here and also here…absorb it slowly) And once you understand how Orchard renders things normally, you can then throw in how it can render alternate shapes, if you so desire. Once we can do that, we can pretty much do it all with good old Razor syntax and we’re good to go.

Example time! Let’s say you have a Content Type called MyContentType, with a field named Message, and you want another field called SecretMessage to only appear if Message has not been specified. How I managed something like this was to create an alternate in my module for SecretMessage, in Views\Fields\Common.Text-MyContentType-SecretMessage.cshtml (alternates can happily live in your Theme as well, it’s up to you). Within your alternate, you can then access Model.ContentItem.MyContentType (if you’ll remember from my previous post, fields are added to a hidden part with the same name as the content type) which will by the magic of .NET 4.0 / dynamic objects / the Clay library also have a property called Message you can test for. So it’ll kind of look like:

[sourcecode language="c-sharp"]
@if (HasText(name) && HasText(Model.Value) && !HasText(Model.ContentItem.MyContentType.Message.Value)) {
<p class="text-field"><span class="name">@name:</span> <span class="value">@(new MvcHtmlString(Html.Encode((HtmlString) Model.Value).ReplaceNewLinesWith("<br />$1")))</span></p>
}
[/sourcecode]

Simple, right? It is, once you find out how. (Perhaps Orchard just needs a list of common things that developers would like to do, and the recommended ways to do them – due to the speed of its development and the lack of clarity with the documentation, I’m not actually sure what I’m posting about here is the ‘right‘ way, but it works, so I’m sticking with it until told otherwise.)

Enabling the Shape Tracing module will really help you out here, as well as with most other layout / rendering tasks – at first sight, it seems really involved for such a trivial task, but it’s really all in service of Orchard being crazily customizable and flexible. Good luck!

Orchard CMS: Adding a field to a custom content type in your module / migrations.cs

While it sounds simple, I didn’t quite find all the documentation I needed in once place, and there were a few gotchas, so I thought I’d make a post (if only for my own future reference).

A few notes on fields, content types and content parts before we continue:

  • When we add a field to a content type via the Admin Interface in Orchard, it looks nice and independent, but in the background all fields are tied to a Content Part; specifically, a Content Part that has the same name as the Content Type.
  • Fields aren’t stored in the database directly, unlike the properties defined in your Model and handled by the driver for custom Content Parts.

So how do we go about adding a Content Field to your custom Content Type? Most of what you need for a custom content type is available on the Orchard Documentation site here – you can follow along and codegen a simple module. Within the migrations.cs for your module (which is run when your module is activated), you can then simply add fields to the content part of the same name (make sure you are adding fields to a content part with the same name as your content type or you will get weird mapping errors), then add the special content part to the content type.

Sample code:

[sourcecode language="c-sharp"]
namespace MyCustomModule {
public class Migrations : DataMigrationImpl
{

public int Create()
{
//the part name has to match the Content Type name if you’re adding Fields
ContentDefinitionManager.AlterPartDefinition("CustomItem",
builder => builder
.WithField("MyLink", cfg => cfg
.OfType("LinkField")
.WithDisplayName("My Link"))
.WithField("Description", cfg => cfg
.OfType("TextField")
.WithDisplayName("Description")
.WithSetting("TextFieldSettings.Flavor", "html"))
);

// add parts to ContentType
ContentDefinitionManager.AlterTypeDefinition(
"CustomItem"
, cfg =>
cfg
.DisplayedAs("My Content Type")
.WithPart("TitlePart")
.WithPart("CustomItem") //don’t forget to add the part with the fields to your content type
.WithPart("CommonPart")
.Draftable()
.Creatable()
);

return 1;
}
}
}
[/sourcecode]

Note that you don’t need to make a Model, or anything – the field data will persist for you automatically.

And a final note, that to set the flavor for the text field, you want to call .WithSetting(“TextFieldSettings.Flavor”, “html”), not .WithSetting(“Flavor”, “html”) as mentioned in this StackOverflow question. I guess this is the price you pay when the development of Orchard moves so quick! (If you’re wondering, the code is I used is valid for Orchard 1.6)

Hope this helps someone out there, it’s not too hard once you get what you need to be doing, but it sure took me a while to get there.

Orchard CMS: Planting My First Orchard

Tried to set up Orchard CMS today, and went a little bit crazy trying to get it to run; even though in the end, none of the problems turned out to be very difficult.

First of all, it just kept throwing back 500 Server codes; so to see what’s *actually* going wrong, head into Orchard.Web, edit the Web.config and make sure:

  • in system.WebServer you have <httpErrors errorMode=”Detailed”/> (and remove the other passthrough property)
  • in system.Web you have <customErrors mode=”Off”>

And then once I did that, the actual error:

HTTP Error 500.21 – Internal Server Error
Handler “NotFound” has a bad module “ManagedPipelineHandler” in its module list

Bingo! Something I can work with. Unlike some suggestions on the internet to use aspnet_iisreg -i, on Windows 8, you just need to turn on HTTP activation for .NET Framework 4.5 Advanced Services, WCF Services:

enablenet45

Having done that, you’ll likely then get:

Server Error in ‘/’ Application.
——————————————————————————–
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type ‘Orchard.Web.MvcApplication’.

Source Error:

Line 1: %@ Application Codebehind=”Global.asax.cs” Inherits=”Orchard.Web.MvcApplication” Language=”C#” %

To which you just need to build the solution in Visual Studio, and then boom! Orchard planted!

If only the WebInstaller checked the Windows Features stuff for you…

Thank You Internet (For Stopping Logitech Double/Single Click Randomness)

So today I turned on my laptop, and used my mouse, and noticed something weird going on with my trusty Logitech mouse; for some weird reason, it kept registering a fair number of single clicks as double clicks. Needless to say, this makes things like highlighting text crazy frustrating; but thank you internet for your long memory.

Came across this post from an apparently now-retired Logitech employee where he explains that:

This can be caused by static energy trapped inside the capacitors in the mouse. To drain this static energy, please plug the Unifying receiver into a different USB port and follow this procedure:

1. Shut off the mouse and remove the batteries.
2. Press all the buttons repeatedly for 30 seconds. This will drain all the static energy that may be trapped in the mouse.
3. Put the batteries back in the mouse and turn it on.
4. Wait a few seconds for it to re-connect and test the buttons.

If this does not fix your issue, please contact the customer support team in your region for more assistance, including a possible warranty replacement.

And what do you know, it works, it actually works!

Thank you internet.

Some Things You Can’t Buy

To mark the end of the Lunar New Year, the Lantern Festival, held on the first full moon of the year, is generally a pretty exciting occasion in most of Taiwan. This year, I was lucky (or crazy enough) to join the 40,000 people descending on the sleepy mountain town of Shifen in the Pingxi district, where for the Lantern Festival an endless stream of locals and tourists set off sky lanterns en masse.

Sky lanterns are essentially bamboo frames with a paper shell, filled with burning paper money – the hot air pushes out from the bottom and it rises like an uncontrolled hot air balloon. On the sides of the sky lanterns, people write wishes in ink before setting them up into the sky.

IMG_5383 (2)

It’s a pretty moving sight (if you can, for a moment, set aside the environmental concerns) to watch a constant stream of hopes and dreams float off into the sky – and for one day and one night we come together to hope for a better, happier, healthier new year.

IMG_5519 (2)