If you’ve ever tried to test Orchard part drivers, you may have been blocked by the fact that the methods on drivers are protected. That, fortunately, doesn’t mean they are untestable. Those methods are still accessible through explicit interface implementations. In particular, drivers implement IContentPartDriver, which is defined as follows.
public interface IContentPartDriver : IDependency {
DriverResult BuildDisplay(BuildDisplayContext context);
DriverResult BuildEditor(BuildEditorContext context);
DriverResult UpdateEditor(UpdateEditorContext context);
void Importing(ImportContentContext context);
void Imported(ImportContentContext context);
void Exporting(ExportContentContext context);
void Exported(ExportContentContext context);
IEnumerable<ContentPartInfo> GetPartInfo();
void GetContentItemMetadata(GetContentItemMetadataContext context);
}
By casting your driver to this interface, you get public access to these methods.
For example, here is some code I wrote recently to test the import and export methods of a driver:
[Test]
public void ImportGetAllDefinedProperties() {
var doc = XElement.Parse(@"
<data>
<UspsShippingMethodPart
Name=""Foo""
Size=""L""
WidthInInches=""10""
LengthInInches=""11""
HeightInInches=""12""
MaximumWeightInOunces=""1.3""
Priority=""14""
International=""true""
RegisteredMail=""true""
Insurance=""false""
ReturnReceipt=""true""
CertificateOfMailing=""true""
ElectronicConfirmation=""true""/>
</data>
");
var driver = new UspsShippingMethodPartDriver(null)
as IContentPartDriver;
var part = new UspsShippingMethodPart();
Helpers.PreparePart<UspsShippingMethodPart, UspsShippingMethodPartRecord>(
part, "UspsShippingMethod");
var context = new ImportContentContext(
part.ContentItem, doc, new ImportContentSession(null));
driver.Importing(context);
Assert.That(part.Name, Is.EqualTo("Foo"));
Assert.That(part.Size, Is.EqualTo("L"));
Assert.That(part.WidthInInches, Is.EqualTo(10));
Assert.That(part.LengthInInches, Is.EqualTo(11));
Assert.That(part.HeightInInches, Is.EqualTo(12));
Assert.That(part.MaximumWeightInOunces, Is.EqualTo(1.3));
Assert.That(part.Priority, Is.EqualTo(14));
Assert.That(part.International, Is.True);
Assert.That(part.RegisteredMail, Is.True);
Assert.That(part.Insurance, Is.False);
Assert.That(part.ReturnReceipt, Is.True);
Assert.That(part.CertificateOfMailing, Is.True);
Assert.That(part.ElectronicConfirmation, Is.True);
}
[Test]
public void ExportSetsAllAttributes() {
var driver = new UspsShippingMethodPartDriver(null)
as IContentPartDriver;
var part = new UspsShippingMethodPart();
Helpers.PreparePart<UspsShippingMethodPart, UspsShippingMethodPartRecord>(
part, "UspsShippingMethod");
part.Name = "Foo";
part.Size = "L";
part.WidthInInches = 10;
part.LengthInInches = 11;
part.HeightInInches = 12;
part.MaximumWeightInOunces = 1.3;
part.Priority = 14;
part.International = true;
part.RegisteredMail = true;
part.Insurance = false;
part.ReturnReceipt = true;
part.CertificateOfMailing = true;
part.ElectronicConfirmation = true;
var doc = new XElement("data");
var context = new ExportContentContext(part.ContentItem, doc);
driver.Exporting(context);
var el = doc.Element("UspsShippingMethodPart");
Assert.That(el, Is.Not.Null);
Assert.That(el.Attr("Name"), Is.EqualTo("Foo"));
Assert.That(el.Attr("Size"), Is.EqualTo("L"));
Assert.That(el.Attr("WidthInInches"), Is.EqualTo("10"));
Assert.That(el.Attr("LengthInInches"), Is.EqualTo("11"));
Assert.That(el.Attr("HeightInInches"), Is.EqualTo("12"));
Assert.That(el.Attr("MaximumWeightInOunces"), Is.EqualTo("1.3"));
Assert.That(el.Attr("Priority"), Is.EqualTo("14"));
Assert.That(el.Attr("International"), Is.EqualTo("true"));
Assert.That(el.Attr("RegisteredMail"), Is.EqualTo("true"));
Assert.That(el.Attr("Insurance"), Is.EqualTo("false"));
Assert.That(el.Attr("ReturnReceipt"), Is.EqualTo("true"));
Assert.That(el.Attr("CertificateOfMailing"), Is.EqualTo("true"));
Assert.That(el.Attr("ElectronicConfirmation"), Is.EqualTo("true"));
}
The Attr method, in case you're wondering, is an extension method I blogged about yesterday.
The Helper class that I’m using here massages a fake part to behave like a real part. It gives the part a fake record, and adds a fake content item around it. It might not be enough in all situations, but it does make the fake convincing enough in this case.
public static ContentItem PreparePart<TPart, TRecord>(
TPart part, string contentType, int id = -1)
where TPart: ContentPart<TRecord>
where TRecord: ContentPartRecord, new() {
part.Record = new TRecord();
var contentItem = part.ContentItem = new ContentItem
{
VersionRecord = new ContentItemVersionRecord
{
ContentItemRecord = new ContentItemRecord()
},
ContentType = contentType
};
contentItem.Record.Id = id;
contentItem.Weld(part);
return contentItem;
}
I really like jQuery’s pattern of attribute getters and setters. They are fluent and work really well with HTML and XML DOMs. If you specify a value in addition to the name, it’s setting, otherwise it’s getting. In C#, we have an OK API for XML, XElement, but it’s not as easy to use as jQuery’s attr methods. It is also missing the flexibility of Javascript with regards to parameter types. To recreate the simplicity of attr in C#, I built a set of extension methods for the most common simple types:
var el = new XElement("node");
el.Attr("foo", "bar")
.Attr("baz", 42)
.Attr("really", true);
var answer = el.Attr("baz");
The element built by this code looks like this:
<node foo="bar" baz="42" really="true"/>
And the answer variable will contain “42”.
Even with this API, there is still a fair amount of repetition in code that reads and writes XML from and to objects. You could rely on serialization in those cases, of course, but when you need a little more control, and the types are not necessarily serializable, or if you just want to do it manually, you need something more. This is why I also built ToAttr and FromAttr. Both are extension methods that take an object and an expression for what property of the object to get or set from XML attributes. The methods will infer the type and name from the property.
This is especially useful when writing the import and export methods in an Orchard part driver:
protected override void Importing(
UspsShippingMethodPart part,
ImportContentContext context) {
var el = context.Data.Element(typeof(UspsShippingMethodPart).Name);
if (el == null) return;
el.FromAttr(part, p => p.Name)
.FromAttr(part, p => p.Size)
.FromAttr(part, p => p.WidthInInches)
.FromAttr(part, p => p.LengthInInches)
.FromAttr(part, p => p.HeightInInches)
.FromAttr(part, p => p.MaximumWeightInOunces)
.FromAttr(part, p => p.Priority)
.FromAttr(part, p => p.International)
.FromAttr(part, p => p.RegisteredMail)
.FromAttr(part, p => p.Insurance)
.FromAttr(part, p => p.ReturnReceipt)
.FromAttr(part, p => p.CertificateOfMailing)
.FromAttr(part, p => p.ElectronicConfirmation);
}
protected override void Exporting(
UspsShippingMethodPart part, ExportContentContext context) {
context.Element(typeof (UspsShippingMethodPart).Name)
.ToAttr(part, p => p.Name)
.ToAttr(part, p => p.Size)
.ToAttr(part, p => p.WidthInInches)
.ToAttr(part, p => p.LengthInInches)
.ToAttr(part, p => p.HeightInInches)
.ToAttr(part, p => p.MaximumWeightInOunces)
.ToAttr(part, p => p.Priority)
.ToAttr(part, p => p.International)
.ToAttr(part, p => p.RegisteredMail)
.ToAttr(part, p => p.Insurance)
.ToAttr(part, p => p.ReturnReceipt)
.ToAttr(part, p => p.CertificateOfMailing)
.ToAttr(part, p => p.ElectronicConfirmation);
}
There is no need to specify attribute names or types here, everything is inferred from the expression. Both methods manipulate XML looking like this:
<UspsShippingMethodPart
Name="Foo"
Size="L"
WidthInInches="10"
LengthInInches="11"
HeightInInches="12"
MaximumWeightInOunces="1.3"
Priority="14"
International="true"
RegisteredMail="true"
Insurance="false"
ReturnReceipt="true"
CertificateOfMailing="true"
ElectronicConfirmation="true"/>
UPDATE: You may notice that there is still quite some repetition of the part parameter in the import/export code above. In order to remove this repetition, I’ve added a small class that aggregates the XML element with a context and has simpler ToAttr and From Attr methods. With this new helper class, we can rewrite the driver’s import/export code to be even more concise:
protected override void Importing(
UspsShippingMethodPart part, ImportContentContext context) {
var el = context.Data.Element(typeof (UspsShippingMethodPart).Name);
if (el == null) return;
el.With(part)
.FromAttr(p => p.Name)
.FromAttr(p => p.Size)
.FromAttr(p => p.WidthInInches)
.FromAttr(p => p.LengthInInches)
.FromAttr(p => p.HeightInInches)
.FromAttr(p => p.MaximumWeightInOunces)
.FromAttr(p => p.Priority)
.FromAttr(p => p.International)
.FromAttr(p => p.RegisteredMail)
.FromAttr(p => p.Insurance)
.FromAttr(p => p.ReturnReceipt)
.FromAttr(p => p.CertificateOfMailing)
.FromAttr(p => p.ElectronicConfirmation);
}
protected override void Exporting(
UspsShippingMethodPart part, ExportContentContext context) {
context.Element(typeof (UspsShippingMethodPart).Name)
.With(part)
.ToAttr(p => p.Name)
.ToAttr(p => p.Size)
.ToAttr(p => p.WidthInInches)
.ToAttr(p => p.LengthInInches)
.ToAttr(p => p.HeightInInches)
.ToAttr(p => p.MaximumWeightInOunces)
.ToAttr(p => p.Priority)
.ToAttr(p => p.International)
.ToAttr(p => p.RegisteredMail)
.ToAttr(p => p.Insurance)
.ToAttr(p => p.ReturnReceipt)
.ToAttr(p => p.CertificateOfMailing)
.ToAttr(p => p.ElectronicConfirmation);
}
You can find the code for this helper class here:
https://gist.github.com/bleroy/5384405
And I have a small test suite for the whole thing here:
https://gist.github.com/bleroy/5385284
I was setting up a new Raspberry Pi under Raspbian on a Samsung monitor the other day. If you don’t do anything, Raspbian and the Pi will attempt to detect the modes supported by your monitor and will make a choice of what seems best to it. And sometimes it gets that very wrong. In those cases, you’ll need to find what the right mode is and to set it up.
It took me quite a few attempts before I succeeded, mostly misled by misinformed forum and blog posts. The right post, the one that has all the correct info does exist however: http://www.raspberrypi.org/phpBB3/viewtopic.php?f=26&t=5851. Let me distil this to a short set of instructions, in case you don’t want to dive in and assimilate all that information. Here is what worked for me…
From the command-line, logged-in as root…
1. Get the list of what’s supported by your monitor:
tvservice -d edid
edidparser edid
2. Find the mode that you want in the resulting list (for me it was “HDMI:EDID DMT mode (82) 1920x1080p @ 60 Hz with pixel clock 148 MHz” with a score of 124,416, which wasn’t the highest, explaining why I had a lower resolution by default). The mode number is the one between parentheses: 82.
3. Edit the config file:
nano /boot/config.txt
Find the section about HDMI, uncomment it and set the right group and mode from step 2. If your mode description contains “DMT”, the group should be 2, and if it contains “CEA”, it should be 1, so for me that was:
hdmi_group=2
hdmi_mode=82
Exit the editor with CTRL+X, followed by Y.
4. Reboot:
shutdown -r now
It is often useful to see what database queries were made during a specific request in Orchard. There are quite a few ways to do this (you can trace right from SQL Server, or you can use Mini-Profiler for instance), but this morning Sébastien showed me a really easy one that I thought I’d share.
Find the log4net.config file in /src/Orchard.Web/Config and edit it to add the following tag:
<logger name="NHibernate.SQL">
<priority value="DEBUG" />
</logger>
Restart the application, then hit the URL you want to test, and look at your logs in App_data/logs. You should see new entries looking like this:
2013-04-03 18:57:30,367 [17] NHibernate.SQL -
SELECT warmupsett0_.Id as Id575_0_,
warmupsett0_.Urls as Urls575_0_,
warmupsett0_.Scheduled as Scheduled575_0_,
warmupsett0_.Delay as Delay575_0_,
warmupsett0_.OnPublish as OnPublish575_0_
FROM VuLu_Orchard_Warmup_WarmupSettingsPartRecord warmupsett0_
WHERE warmupsett0_.Id=@p0;
@p0 = 1 [Type: Int32 (0)]
(only not as nicely formatted)
To disable the SQL trace, just edit log4net.config and set the value to ERROR instead of DEBUG.
Today my five-year-old told me that when she was four, she thought that what came after ninety-nine was… tenty. You know, because seventy, eighty, ninety, tenty.
At first I thought it was just funny and charming, but then I realized it was actually a really good idea. Tenty is only nonsensical if you’re counting in base ten (or lower), but it makes total sense for higher bases.
How do people usually read 0xA0? “A-zero”? How unimaginative! Let’s read that “tenty” from now on!
Here are some more examples of how to read hexadecimal in a non-boring way:
- 0xB3 is eleventy-three
- 0xCA is twelvety-ten
- 0xD9 is thirteenty-nine
- 0xEC is fourteenty-twelve
- 0xFF is fifteenty-fifteen
- 0xF04A is fifteen hexathousand forty-ten
- 0x4B2AC0AA is forty-eleven hexamillion, two hexahundred tenty-twelve hexathousand tenty-ten
- and of course, seven-eleven will have to change their logo to 0x7B.
Is this the greatest thing or what?
If your hosted environment does not give you a staging site and the means to swap it easily with the production environment like Azure Cloud Services do, or if you don’t have a staging database, or if you just need to take your site offline for the public while you perform data updates in the admin, you may be wondering what solutions you have, if any.
IIS has an app_offline.htm feature that you can use, that will serve a static page for all requests but that’s rather brutal as it does not just take the site offline for your users, it also does so for you. While that file exists, you can do absolutely nothing with your site. You cannot access the admin, you cannot preview your changes, nothing. So when you flip the switch back, it’s anyone’s guess whether the changes you blindly made actually work, even if they did on your machine…
We need a better solution. Well, I happen to have one...
All you have to do is create a new theme named “Offline” with just one /Views/Layout.cshtml file containing a message along the lines of “We are updating the site. We apologize for the inconvenience. Please come back in a few minutes.” You can add stylesheets to make it pretty if you want to. It’s a full theme, you can go crazy.
The important thing is that this theme has one layout, and that this layout does nothing but display its message. It has no zones, so no dynamic content is going to be served to the public from the site no matter what URL is hit.
Once you have made this theme current, all your visitors are seeing it, but you can still access the admin of the site and do whatever you want.
Better, you can use the “Theme Preview” feature of Orchard to check what your changes look like while your users continue to see the “offline” page. Just go to Themes, and click Preview on your regular theme…
Once you are satisfied with your changes and judge the site to be ready to be taken back online, just restore your theme as the current. The “Offline” theme can sit there and do nothing until the next time you need it.
I’ve used this technique successfully last time I updated an Orchard site. It worked great. I hope it helps others…
I’m writing a lot of JavaScript these days, and for testing I mostly use QUnit. When I need to quickly stub a piece of the code that I’m testing, I like to use the following micro-library. What it does is enable you to replace a bunch of methods on an object with stub versions, in a easily reversible way.
I use RequireJS, but if you don’t, just remove the define and outer function.
define(function() {
var stub = function(obj, stubs) {
obj._stubbed = obj._stubbed || {};
for (var name in stubs) {
obj._stubbed[name] = obj[name];
obj[name] = stubs[name];
}
};
stub.restore = function(obj) {
if (!obj || !obj._stubbed) return;
for (var name in obj._stubbed) {
obj[name] = obj._stubbed[name];
}
delete obj._stubbed;
};
return stub;
});
Here is how you would replace two methods bar and baz on an object foo:
stub(foo, {
bar: function() {
return "stubbed bar";
},
baz: function(glop) {
return "stubbed baz " + glop;
}
});
And here is how you can put everything back in place once you’re done:
stub.restore(foo);
I hope this helps...
The multi-tenancy feature in Orchard enables you to host multiple sites within the same Orchard instance. It’s not a a security feature, just a way to improve site density, and to enable you to save on hosting costs. Nevertheless, a request to a specific existing tenant should never be answered with a page from another tenant. Ever.
There is however a fallback mechanism that enables one tenant to handle all requests that weren’t identified by another tenant. While this could be considered useful in some scenarios, I’m hereby declaring it bad practice.
If for any reason a tenant fails to start, for example, requests to that tenant are going to fall back. Even if you were in a scenario where you considered fallback to be useful, this is an unexpected and positively undesirable result. It’s much better to fail with an error message or a 404 than to fail with a fallback to a different site than the one the client asked for.
So here is my recommendation:
Always have a host or URL prefix configured on all tenants, in particular the default tenant.
This way, no fallback will ever happen, and requests will only be handled by a tenant that recognizes its own host name.
Here is, for example, the new configuration of the default tenant on my hosted web sites:

Note that I have multiple hosts configured here, including the host that I use on my dev machine for local development, but the point here is to specify something on all tenants.
This is important.
Placement.info is an XML file that orchestrates the different parts of a content item and sends each of the shapes they create into specific local content zones. If the previous sentence sounded confusing to you, fear not, this post is for you.
When writing an Orchard theme, more often than not, you know exactly what parts exist in your content type, and you know where you want them to render. Placement can be extremely powerful, but it’s rather abstract and it reverses the usual logic of placing contents on a page. What most people really want to do is write a template with simple markup and placeholders inside that markup for the rendering of specific parts such as title, summary, tags, etc. Placement forces you to dispatch those part shapes from a completely separate file.
In the Summer of 2011, I wrote a little article to explain how to write custom templates for specific content types in Orchard, without using placement.info:
So you don’t want to use placement.info?
The solution worked, but relied on a hack that will break with the next version of Orchard (1.7).
Sébastien Ros gave me a little trick the other day that enables the same thing, in a simpler, less hacky form. It still uses placement somewhat, but in a very simple way.
The idea is to create one local zone per part instead of the usual header, content and footer zones. Here we are going to send the relevant shapes to those zones through placement:
<Match ContentType="BlogPost">
<Match DisplayType="Summary">
<Place Parts_Common_Body_Summary="Summary:0"
Parts_Tags_ShowTags="Tags:0"
Parts_Common_Metadata_Summary="MetadataSummary:0"
Parts_Comments_Count="CommentsCount:0" />
</Match>
</Match>
This sends shapes into Summary, Tags, MetadataSummary and CommentsCount zones. Those do not yet exist.
Caveat: when naming your custom zones, be careful not to collide with existing properties or zones on the Model, lest you end up with unexpected and confusing results. Using longish and very explicit names usually works well for that.
The template can now simply create and render those zones. Here is my Content-BlogPost.Summary.cshtml template:
@using Orchard.ContentManagement
@{
var blogPost = Model.ContentItem;
}
<article class="content-item blog-post">
<header><h1><a href="@Url.ItemDisplayUrl((IContent)blogPost)">
@blogPost.TitlePart.Title
</a></h1></header>
@Display(Model.Summary)
<footer>
@Display(Model.Tags)
@Display(Model.MetadataSummary)
@Display(Model.CommentsCount)
</footer>
</article>
Notice how in the case of the title, I’m not even using the shape given by the part, but I’m accessing the properties directly on the TitlePart. The other parts are rendered through the special zone that we created using the Display function. And that is all. You can now focus on building your template, and it will be pretty obvious what will render where…
If you want to create a simple widget in Orchard, such as a box of social links, you have three possibilities:
- Find a module on the gallery or write one yourself, but there is overhead associated with modules, which may make this overkill.
- Use an HTML widget and paste a bunch of HTML and Javascript, hoping administrators of the site don’t break it accidentally. I don’t like this, it feels like a hack.
- Create a simple widget, following the instructions in this post.
First, let’s create a content type (in the admin, go to Content / Content Types and click “Create new type”) and call it “Social Links”.
Add the widget and identity parts. Those are the only ones you really need:

Uncheck creatable and draftable, add the “Widget” stereotype (with an upper-case ‘W’: I made the mistake, as you can see, of using a lower-case ‘w’ on my first try, and it did prevent the widget from being seen as such):

Now when you add a widget, the social links widget appears in the list:

It’s a simple, apparently featureless widget, which minimizes the chances of accidentally messing it up.
All that’s left to do now is to add a template to the theme that will render what we want. We’ll take advantage of shape alternates. Using shape tracing, we quickly discover that we can name our template Widget-SocialLinks.cshtml to target it narrowly enough:

Once the file has been added to the Views folder of my theme, I can paste in the code from Facebook, Twitter, or whatever else I want in there.

Done. Fastest and simplest way to create a new widget.
More Posts
Next page »