<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rssdatehelper="urn:rssdatehelper"><channel><title>The Offroadcode blog</title><link>http://offroadcode.com</link><pubDate></pubDate><generator>umbraco</generator><description>We write about a wide range of topics from web design and development to how we work and manage our varied client projects. Stay up to date with our thoughts on the web.</description><language>en</language><item><title>Hacking the Umbraco Content Tree picker to hide content to make it easier for editors</title><link>http://offroadcode.com/blog/2013/3/4/hacking-the-umbraco-content-tree-picker-to-hide-content-to-make-it-easier-for-editors/</link><pubDate>Mon, 04 Mar 2013 00:00:00 GMT</pubDate><guid>http://offroadcode.com/blog/2013/3/4/hacking-the-umbraco-content-tree-picker-to-hide-content-to-make-it-easier-for-editors/</guid><description><![CDATA[ <p>Lets say your extending umbraco's functionality be it for a package, or just a custom dashboard for your clients logic, sometimes you wish to render a content tree <em>somewhere</em> in the backend, his posts aims to explain how.</p>
<p>So, imagine we have a dialog box which chooses a person to give a cookie (chocolate chip or double choc chip, it doesnt matter) to and you only want to show the part of the tree which contains People via a content picker tree. This will work by using the built in content picker which will render a tree. However by default it will show <strong>all </strong>the content for the whole site. We want to just allow users to select a person from the authors folder and not see any of the other content in our picker. In other words, we want to be able to set a start node for our content tree to start from.</p>
<p>This is going to need some code so we will be assuming you are comfy with that, no UI only fixes here guys sorry.</p>
<p>To achieve this we need to re-use/extend a custom tree that comes with uComponents called a FilteredContentTree by adding an override for our StartNodeID. With a little magic and slight of hand on application start up we can get this content tree to do as we require.</p>
<p>Many thanks to Lee Kelleher and Jereon Breuer for their help in<a href="http://our.umbraco.org/forum/developers/extending-umbraco/36187-Custom-Content-Picker"> our original post on this</a>.</p>
<h1 dir="ltr">Steps</h1>
<h2 dir="ltr">Create our new tree filter.</h2>
We need to first define a filter to use, this is a simple class which extends the exiting FilteredContentTree class as used by the Multinode Tree Picker that comes with uComponents. If you are using Umbraco 4.8+ then this class is in the namespace <em>umbraco.editorControls.MultiNodeTreePicker</em>, previous versions will have to reference the uComponents dlls and use the appropriate namespace, (since parts of uComponents got merged into the core of Umbraco in version 4.8). <br /> <br />
<pre class="brush:csharp">using umbraco.controls.Tree;
using umbraco.editorControls.MultiNodeTreePicker;
namespace Orc.example.plugin.dialogs.TreeExample
{
    public class ExampleContentTree : FilteredContentTree
    {
        // Just do what the base class would do, nothing custom here
        public ExampleContentTree(string app) : base(app) { }

        // Set out start node here
        public override int StartNodeID
        {
            get { 
                   // Change this to be your default start node or logic to work it out
                   return 1077;  
            }
        }
    }
}</pre>
<br /><br />This model will only render the tree starting from node id 1077. You could replace the getter with some logic to find the correct node to use e.g. from a settings file etc. for ease of demonstration we hard coded it.<br />
<h2 dir="ltr">Insert tree filter into collection on app start-up</h2>
Now we need to add our new tree into the collection of available trees, called the TreeDefinitionCollection, This collection keeps all the available tree's for umbraco to render. We do this on application startup by having another simple c# class file in our project (Umbraco will find this and run it on start up automagically): <br />
<pre class="brush:csharp">using System.Linq;
using Umbraco.Core;
using Umbraco.Web;
using umbraco.cms.presentation.Trees;

namespace Orc.example.plugin.dialogs.TreeExample
{
    public class CustomTreeExampleInitializer : IApplicationEventHandler
    {
        public void OnApplicationInitialized(UmbracoApplication app, ApplicationContext ctx)
        {
            // get a handle on the main content tree
            var contentTree = TreeDefinitionCollection.Instance.Single(x =&gt; x.Tree.Alias.ToUpper() == "CONTENT");

            // create our tree type
            var filteredTreeType = typeof (ExampleContentTree);

            // make the definition (sorry about all the attributes, horrid ain't it?
            var filteredContentTreeDefinition = new TreeDefinition(filteredTreeType,
                                                         new umbraco.BusinessLogic.ApplicationTree(true, false, 0, contentTree.Tree.ApplicationAlias, filteredTreeType.Name, null, null, null, null, null, null),
                                                         contentTree.App);
            // add it to the collection
            TreeDefinitionCollection.Instance.Add(filteredContentTreeDefinition);
        }
    }
}
</pre>
<br />This will stash the ExampleContentTree into the tree collection ready to get pulled out when rendered with the control.<br />
<h2 dir="ltr">Rendering the tree</h2>
<p>We need an .aspx page that we can render a user control on. We will use this for the dialog box that pops up when users try to select a person. On my page, I have a PropertyPanel called TreeContainer, this is where we will inject the tree picker CustomTreeControl into.</p>
<p>We define a custom user control which we will use to render the tree on the page, this custom control specifies the tree filter to use in the TreeType property.</p>
<pre class="brush:csharp">public class ExampleContentTreeControl : CustomTreeControl
{
    public ExampleContentTreeControl()
    {
        ShowContextMenu = false;
        Height = 300;
        TreeType = typeof (ExampleContentTree).Name;
        // We use this in a bit, you can change the name 
        // if you like, its just a JS method in your code
        FunctionToCall = "onNodeSelected"; 
    }
}
</pre>
<p>In the code behind for your usercontrol or page, you can insert the tree by using something like this:</p>
<pre class="brush:csharp">TreeContainer.Controls.Add(new ExampleContentTreeControl());</pre>
<p>This will render a tree into the page with your custom start node. But there is a problem we cannot retrieve the selected node server side on postback as the tree control doesn't specify a value, it was never designed to do that bit. So we have to do some simple javascript hackery to work around it by using the FunctionToCall property on the CustomTreeControl to save the value of the selected node via javascript into a hidden field that our server side code can access.</p>
<h2 dir="ltr">Attach javascript so that we get the value server side</h2>
<p>Firstly we add a server side hidden field (here called "SelectedNode") to our page, its this that we will read the selected node id from on postback.</p>
<p>Next we add the following javascript code into our page:</p>
<pre class="brush:html">&lt;script type="text/javascript"%&gt; 
    function onNodeSelected(id)
    {
            document.getElementById("&lt;%= SelectedNode.ClientID %&gt;").value = id;
    }
&lt;/script&gt;
</pre>
<p>Note the “&lt;%= SelectedNode.ClientID %&gt;” will get the client ID of the hiddenfield as it is a control element.</p>
<p>We've set this function to be called in our control definition above (go back and double check so you know what we are doing).</p>
<h2 dir="ltr">Retrieving the Node Id from the server.</h2>
<p>When you are ready to get the selected node id, you simply access the SelectedNode control and retrieve its value, as the javascript has set the hidden field to be the node id.</p>
<h2 dir="ltr">More Examples</h2>
<p>If you wish to see more detailed examples, please visit the gist <a href="https://gist.github.com/4250818">here</a></p>
<p> </p>
<p>If you have any questions, leave a comment below! (or tweet me @steroberts89)</p>]]></description></item><item><title>Quickie: Include empty folders in Mercurial/Kiln</title><link>http://offroadcode.com/blog/2013/2/27/quickie-include-empty-folders-in-mercurialkiln/</link><pubDate>Wed, 27 Feb 2013 00:00:00 GMT</pubDate><guid>http://offroadcode.com/blog/2013/2/27/quickie-include-empty-folders-in-mercurialkiln/</guid><description><![CDATA[ <p>We sometimes have folders that we want to appear when we check out a project from source control. Lets say we have a data folder that something should get saved into for instance or a folder structure you always like to have when checking out a base project or similar.</p>
<p>Trouble we have here is Mercurial tracks files, not folders. It will remember folders only if they have a file in them. So empty folders are simply ignored which is great in one way but rubbish when you really want that folder structure. For an Umbraco site we like to have the App_Code folder or it can give us a <a title="Yellow Screen Of Death" href="https://www.google.co.uk/search?q=ysod&amp;hl=en&amp;safe=off&amp;source=lnms&amp;tbm=isch&amp;sa=X&amp;ei=SxguUYuHE8uJhQedjYH4Bw&amp;ved=0CAoQ_AUoAQ&amp;biw=1920&amp;bih=1075">YSOD</a>. Its a easy to fix error but a nasty one when you are in a hurry. It would be better if when we cloned a project that those required folders are just included.</p>
<p>So a quick and simple solution we use here is to simply commit an empty dummy text file that by convension we call "showinkiln.txt". We know then that when we see this we know what its for and leave it be. Mercurial will store that file and therefore the folder that its in. This work well with subfolders too, it will create all the parent folders it need to accommodate this one file.</p>
<p>Short and sweet.</p>
<p><img src="/media/15232/mezer_02-27_14-32-07.jpg" width="402" height="128" alt="showinkiln"/></p>]]></description></item><item><title>Why should I use uSiteBuilder?</title><link>http://offroadcode.com/blog/2013/2/21/why-should-i-use-usitebuilder/</link><pubDate>Thu, 21 Feb 2013 00:00:00 GMT</pubDate><guid>http://offroadcode.com/blog/2013/2/21/why-should-i-use-usitebuilder/</guid><description><![CDATA[ <p>You don't <strong>need </strong><a href="http://usitebuilder.codeplex.com/">uSiteBuilder </a>to make websites with Umbraco, its a nice to have not a requirement. Without it you can just use the standard built in Umbraco UI to point and click your way to a great and powerful site. The difference is <a href="/blog/2012/7/18/using-usitebuilder/">uSiteBuilder allows us to define all the fields and document types that we would use in a site in code</a> (c# code in our case) rather than building them using the mouse by pointing and clicking. Its not a requirement to do it via code. If fact using the UI is probably quicker and simpler.</p>
<p>So why do we use a method that takes longer and is more complicated? We are not daft, there must be a good payoff for these apparent drawbacks. For me there are a number of ways that uSiteBuilder proves its worth.</p>
<h2>Source control</h2>
<p>Having our fields and document types in code means we can put them into source control so the day they were changed/created is date stamped and has (hopefully) a nice message explaining why it was added. This is super handy for finding out who added something, when and why. A nice bit of audit that hopefully we will never need, but if we do we have a trail to find it. Documenting all your changes and the whole build through out its life. If you are not using source control I would say you should be even if you are a solo developer. Which brings me nicely onto my next bonus.</p>
<h2>Developing as part of a Team</h2>
<p>Solo developers might not see any value in uSiteBuilder and I would agree with them. Being the only developer you can keep all the site in your head, don't need to communicate anything about its inner workings to anyone else and are safe in the knowledge that no one else is going to "touch your stuff". As a result use the UI if you like, its fast and easy.</p>
<p>If you work in a team though then things are a bit different. You need to know "why" someone added a field and possibly when. You might need to know it in a hurry too and they are off this week on holiday with no phone signal...damn. Thanks to our code being in source control we can still get all this information and start fixing whatever it is.</p>
<p>When John Bear adds a new field for a new feature he is working on it will automatically get added to my version of the site the next time I sync my changes. This avoids that horrid "I've just pulled in the latest code and I'm getting nothing but errors, what am I missing" conversation everytime you do a pull from source control which nearly always is resolved with an answer something like "..oh yeah you need to create a checkbox field called 'foo' on the 'bar' doctype...here let me do it". If you added that field in manually you now have to add it in again manually to all the existing cuts of the database. Boring, tiresome and error prone (you spelt the alias for that field correct right? Right?)</p>
<h2>Easy deployment</h2>
<p>Want to put a new mod live? Just upload the DLLs and uSiteBuilder will add any fields and new document types it needs for you when the site restarts (or on demand if you are using<a href="http://our.umbraco.org/projects/backoffice-extensions/usitebuilder-admin"> Stephen Rogers' awesome uSiteBuilder Admin package</a>). No need to keep a list of fields to manually create later. No nasty re-syncing the database from dev and live and visa versa. Horrid job that one, often forgotten though until deployment time and only really fixed by eyeballing it. Manually creating fields is quick and easy at first but catches up with you if you are working on a site long term. If it's a quick "in and out" build for a 6 page site that you are never planning to return to then manual might be the way to go.</p>
<h2>Strongly typed objects for your templates</h2>
<p>uSiteBuilder gives you real C# objects for all the document types you store in Umbraco so that you can use them in your templates (Razor only although I did do a dirty proof of concept to pass them into XSLT) which means you get intellisense and compile time sanity checking. All good stuff for speeding up developement time of your templates. Again, this might not be much use to you if you are just firing out another 10 page brochure site. Why bother if it's doing nothing clever. We've learn over the years though that very few sites are as simple as they first appear and even fewer never change something throughout their lifespan.</p>
<p>You can also unit test your document types now you have them in code form. Talk about code quality! You can't really do that with a manual build.</p>
<h2>Document your document types</h2>
<p>As your document types are now classes you can decorate them with standard C# documentation techniques so you get some nice descriptions for all your fields and with intellisence you can discover new features/methods added to classes by others on the team. Keeps everything in one nice place and makes coding fast. So slow to setup, but bigger gains later...a recurring theme.</p>
<h2>Summing up</h2>
<p>As a company we build medium to large Umbraco sites as part of a team and doing custom development work along the way. We use source control day to day and pass functionality between ourselves depending on our specialities. The sites we build tend to have a long life time and our client relationships lasting even longer resulting in frequent revisits and reworking of existing sites. As a result all the above benefits outweigh the initial perceived high time cost of setup and delay in "getting to the good stuff" than uSiteBuilder appear to get in the way of at first glance.</p>
<p>If you are a solo developer working on small sites that are "fire and forget" quick turn around jobs then all the above is probably of little to no use to you and as a result you probably don't need to be using uSiteBuilder for any other reason that curiosity. So don't feel like you are missing out. Its horses for courses, use the right tool for the job. That said it never hurts to use new code and techniques and it will certainly be another string to your bow should you need to get hired or freelance with a larger Umbraco agency so it's worth giving it a go. Don't get stuck with the uSiteBuilder (or any other type of) dogma though, stick to what works for you. Just make sure you try some new stuff out once in a while to see if there might be a new way of working out there that suits you better.</p>
<h2>Get involved</h2>
<p>As we are pretty vocal about uSiteBuilder we have become the current custodians of the source code for it. If you use it and like it then please help us improve it by joining in with its development and reporting issues and sharing the load. The best places for this are on our google group page https://groups.google.com/forum/#!forum/usitebuilder-developers see you there!</p>
<p>We hope to have a new release of uSiteBuilder out soon with lots of mods and improvements as well as some fixes for Umbraco v6 support. Fun times ahead.</p>
<p>Still want to know more, check out my talk at the 2012 Umbraco UK Festival, "<a href="http://www.youtube.com/embed/1MXpP4oSXqM">a crash course in uSiteBuilder</a>".</p>]]></description></item><item><title>Mobile friendly images, creating Responsive/Adaptive Images with ImageGen</title><link>http://offroadcode.com/blog/2013/1/31/mobile-friendly-images,-creating-responsiveadaptive-images-with-imagegen/</link><pubDate>Thu, 31 Jan 2013 00:00:00 GMT</pubDate><guid>http://offroadcode.com/blog/2013/1/31/mobile-friendly-images,-creating-responsiveadaptive-images-with-imagegen/</guid><description><![CDATA[ <p>The general idea is based on Matt Wilcox's excellent work on <a href="http://adaptive-images.com/">adaptive images</a> so go read how that works first then come back. Done? Good. So all we've done here is just got it working with an Umbraco site using ImageGen. I think we where the first .net version of this technique but we never got it pushed out to you guys as we hoped a better standard solution would have come around by now.</p>
<p>The code for this is up on BitBucket and you can download it from here <a href="https://bitbucket.org/Offroadcode/adaptiveimages-for-umbraco">https://bitbucket.org/Offroadcode/adaptiveimages-for-umbraco</a> and it includes the DLL you will need too.</p>
<p>So the gist is, if you visit a site with this enabled it will automatically resize your images to one of a number of fixed widths (aka breakpoints). We know what images you can display by sending a cookie with your screen size included in it with every request. We then allow the browser to do any additional resizing needed (as browsers do an awesome job of this these days).</p>
<p>We have a http module that watches all requests coming in and checks to see if its an image that we have in the media folder of Umbraco. If so then we try to do our resize magic. All we do is workout what size our images should be (our breakpoints are hardcoded in, feel free to change them) and then pass the right querystring to ImageGen to get it to create it for us and return it. ImageGen handles caching of the images for us by writing them to disk, winning!</p>
<p>So straight into the action. First up cut and paste this little bit of javascript into the top of your page below the &lt;head&gt; tag.</p>
<code>
<pre class="brush: html">&lt;script&gt;document.cookie='resolution='+Math.max(screen.width,screen.height)+'; expires=; path=/';&lt;/script&gt;</pre>
</code>
<p>Then you need to add drop our DLL into your /bin/ folder and then wire up our little module by opening web.config in the root of your website and adding in the following lines.</p>
<p>In web.config search for the &lt;httpHandlers&gt; element and add this one:</p>
<code>
<pre class="brush: csharp">&lt;add name="AdaptiveImageModule" type="AdaptiveImages.AdaptiveImageModule, AdaptiveImageModule" /&gt;</pre>
</code>
<p>Then search for &lt;modules&gt; element and add this line:</p>
<code>
<pre class="brush: csharp">&lt;add name="AdaptiveImageModule" type="AdaptiveImages.AdaptiveImageModule" /&gt;</pre>
</code>
<p>And thats about it. You markup to change, no querystrings to add to you images, your whole site will no serve adaptive images (assuming they are in the media folder). Simple, we like to keep these things simple.</p>
<p>To test it we need to keep an eye out to see which files ImageGen will generate for us. First up hit one of your images (something about 1000px wide will do) in your media folder via your browser, this should render just fine and at the original size if you check the media folder you will see ImageGen has added a /cached/ folder inside your media items folder, this is where it stores its cached images. You should see you image in there.</p>
<p>Next up we need to hit it with a device with a smaller screen. You can't test this by just resizing your browser, thats not how it works. The cookie sends the max size of your screen and its this that we work off. So you will need to use a real device like your phone. If you visit the same image in your phone you will get what looks like the same image but it will actually be smaller (well it should be) and we can check this by looking in the /cached/ folder for another ImageGen cached image with the right pixel size (for an iphone it would be 480 across).</p>
<p>Thats about it. It should just work. We've been using it for a while on several of our sites and its not caused any issues for us as yet. It seems to work well enough that we even forget we did it.</p>
<p>Before anyone asks, no it does not do retina images or anything fancy like that but the code is here, feel free to amend it to your hearts content.</p>
<p>Final word, hopefully there will be a standard way to do this that the browsers can adopt so that this sort of homegrow solution is no longer needed. In the meantime treat this as a nice to have, not an essential, part of your site.</p>
<p>Cheers</p>
<p>Pete</p>]]></description></item><item><title>Mobile tip: Prevent iPhones from guessing telephone numbers</title><link>http://offroadcode.com/blog/2012/8/2/mobile-tip-prevent-iphones-from-guessing-telephone-numbers/</link><pubDate>Thu, 02 Aug 2012 00:00:00 GMT</pubDate><guid>http://offroadcode.com/blog/2012/8/2/mobile-tip-prevent-iphones-from-guessing-telephone-numbers/</guid><description><![CDATA[ <p>iPhones are great and smart but sometimes they are too smart! In this case mine was guessing that a date range was infact a telephone number, so it wrapped it in a link and when I clicked it it would ask if I wanted to call that number. Super smart if your on a old website's contact us page, utter rubbish when on a mobile site and the number in question is not a telephone number.</p>
<p>So we did disabled auto formating for telephone numbers using this little snippet in the head tag of the whole site:</p>
<pre class="brush:html">&lt;meta name="format-detection" content="telephone=no"&gt;
</pre>
<p>Simple as that. Still want to have numbers click able? Easy, just add a link around them and use the tel:// protocol instead of the usual http:// and the phone (or any other smart device) will do the rest.</p>
<pre class="brush:html">&lt;a href="tel://01484 643078"&gt;Ring Offroadcode for a new website&lt;/a&gt;
</pre>
<p>A small one but a good one. We'll be adding this to our <a href="https://github.com/Offroadcode/Starter-Kit">web starter kit</a> asap for you.</p>]]></description></item><item><title>Using USiteBuilder</title><link>http://offroadcode.com/blog/2012/7/18/using-usitebuilder/</link><pubDate>Wed, 18 Jul 2012 00:00:00 GMT</pubDate><guid>http://offroadcode.com/blog/2012/7/18/using-usitebuilder/</guid><description><![CDATA[ <h3>Benefits of using uSiteBuilder</h3>
<p>USiteBuilder provides a "code first" approach that as Umbraco developers we've really been missing out on. If you <a href="http://usitebuilder.vegaitsourcing.rs/" title="uSiteBuilder" target="_blank">review the uSiteBuilder website</a>, the main advantages are listed as;</p>
<ul>
<li>Design your document types as classes in Visual Studio.</li>
<li>Design your templates as master pages in Visual Studio.</li>
<li>Use code-behind in your templates.</li>
<li>Use web user controls instead of xslts and macros.</li>
<li>Use strongly typed templates to render a specific document type.</li>
<li>Use strongly typed user controls to render a specific document type.</li>
</ul>
<p>USiteBuilder allows you to write code that will <span>synchronize </span>with your Umbraco site, create/update a document types, document type properties and MasterPages. You can also subclass document types and specify other key parameters relating to your document type.</p>
<h3>A few USiteBuilder caveats...</h3>
<p>For the most part, uSiteBuilder does a damn good job of providing a code first approach. However, it's not without a few caveats;</p>
<ul>
<li>If you download the production release (1.2 at the time of writing) there is no way to stop the start-up uSiteBuilder <span>synchronization</span> from happening. You can however use one of the nightly releases where there is the option to suppress the <span>synchronization</span>. Depending on the size of your site and number of document types, this <span>synchronization</span> can increase your apps initial start time.</li>
<li>We've been using the ContentHelper (which is outlined below) to help us get strongly typed objects for use in macros. If you suppress the <span>synchronization</span>, the ContentHelper will not return any strongly typed objects.</li>
<li>USiteBuilder has been designed for use with brand new projects. We've been using uSiteBuilder on existing projects and we've found that you can't decorate a document types with a specific document type alias. Also, we've found uSiteBuilder can in some cases, duplicate document type properties due to the older Umbraco naming convensions (especially properties with "lowerCase" names alias' versus "UpperCase" alias'.</li>
</ul>
<h3>Using USiteBuilder in existing Umbraco projects</h3>
<p>If you want to use uSiteBuilder in your existing projects, you can use <a href="https://twitter.com/@Richie_Green" title="Rich Green">Rich Greens</a> <a href="http://our.umbraco.org/projects/developer-tools/usitebuilder-import" title="uSiteBuilder Import">uSiteBuilder Import</a>. This will give you a kick start on creating the document types and MasterPages for use with uSiteBuilder. It's trivial to set up and once pointed at your existing Umbraco database, uSiteBuilder Import will attempt to generate the classes you need. It's not perfect, but it does give you decent headstart.</p>
<p>We've found that we needed to tweak the classes after generation. We'd strongly suggest reviewing all document type classes that are generated using uSiteBuilder Import to ensure that all your properties are present and correct (especially if you are using custom datatypes).</p>
<h3>Generated Document Types</h3>
<p>Below is a sample of a generated Blog document type;</p>
<pre class="brush:csharp">using Vega.USiteBuilder;

namespace Orc.OurSite.USiteBuilder.DocTypes
{
    [DocumentType(Name = "Blog Post", IconUrl = "doc.gif", AllowedTemplates = new string[] { "OrcBlogPost"  })]
    public partial class BlogPost : Vega.USiteBuilder.DocumentTypeBase
    {
        [DocumentTypeProperty(UmbracoPropertyType.RichtextEditor, Name = "Content", Description = "", Tab = "Content", Mandatory = false)]
        public string bodyText { get; set; }

        [DocumentTypeProperty(UmbracoPropertyType.Tags, Name = "Tags", Description = "Comma delimited list of tags for this post", Tab = "Content", Mandatory = false)]
        public string tags { get; set; }

        [DocumentTypeProperty(UmbracoPropertyType.TrueFalse, Name = "Close comments", Description = "Enable/Disable comments for this post", Tab = "Options", Mandatory = false)]
        public string closeComments { get; set; }

        [DocumentTypeProperty(UmbracoPropertyType.Upload, Name = "Blog Photo", Description = "Choose a relevent photo for this post", Tab = "Content", Mandatory = false)]
        public string blogPhoto { get; set; }

        [DocumentTypeProperty(UmbracoPropertyType.DatePicker, Name = "Post Date", Description = "The date this post was published", Mandatory = false)]
        public string PostDate { get; set; }

    }
}
</pre>
<p>So, <span>let’s </span>de-construct the code above. Firstly, we put the class into our namespace of <strong><em>Orc.OurSite.USiteBuilder.DocTypes</em></strong> and inherit using <strong><em>Vega.USiteBuilder.DocumentTypeBase</em></strong>. We also decorate the constructor with the <strong><em>DocumentTypeAttribute</em></strong>, which allows us to define name, icon and MasterPage templates that this document type can use. Each of the properties within our class are decorated with the the <strong><em>DocumentTypePropertyAttribute</em></strong> allowing us to easily define the type, name, description, tab it will display on and if it is mandatory.</p>
<h3>Custom DataTypes</h3>
<p><em>"But what about my custom DataTypes?!"</em> we here you cry... well, that's taken care of by specifying <strong><em>UmbracoPropertyType.Other</em></strong> and giving the name of your <em>DataType</em>, for example;</p>
<pre class="brush:csharp"> 
DocumentTypeProperty(UmbracoPropertyType.Other, Name = "Name Of Your Custom DataType", Description = "", Mandatory = false)]
public string someCustomDataType { get; set; }
 
</pre>
<h3>Document Type Inheritance</h3>
<p>Now don't forget that you could also inherit from a "base" Document Type. This is exceptionally useful when you consider that you might want Document Types to have some common properties. You might decide, for example, that you want all Document Types to include some SEO information like a H1, Browser Title and Meta Description. You could then create a base class that inherits <strong><em>Vega.USiteBuilder.DocumentTypeBase</em></strong> and then start inheriting from that;</p>
<pre class="brush:csharp">using Vega.USiteBuilder;

namespace Orc.OurSite.USiteBuilder.DocTypes
{
    // create a "base" class with some properties defined in our "SEO" tab. 
    // it *MUST* inherit from  Vega.USiteBuilder.DocumentTypeBase
    [DocumentType(Name = "Base DocType", IconUrl = "doc.gif")]
    public partial class BaseDocType : Vega.USiteBuilder.DocumentTypeBase // Inherit from DocumentTypeBase 
    {
        [DocumentTypeProperty(UmbracoPropertyType.Textstring, Name = "Page H1", Tab="SEO")]
        public string pageH1 { get; set; }

        [DocumentTypeProperty(UmbracoPropertyType.Textstring, Name = "Browser Title", Tab="SEO")]
        public string browserTitle { get; set; }

        [DocumentTypeProperty(UmbracoPropertyType.TrueFalse, Name = "Meta Description", Tab="SEO")]
        public string metaDescription { get; set; }

    }
    
    // now let's in inherit from the BaseDocType above
    [DocumentType(Name = "Blog Post", IconUrl = "doc.gif", AllowedTemplates = new string[] { "OrcBlogPost" })]
    public partial class BlogPost : BaseDocType  
    {
        // blog post properties here
    }

}
</pre>
<h3>Using partial classes and defining custom methods</h3>
<p>You may have noticed that we specified <strong><em>partial</em></strong> in the constructor of our document type classes. This allows us to create a partial class that contains the definition for the document type and another partial class for custom methods. If at anytime, we need to regenerate our classes from uSiteBuilder Import, we can do this safely and just replace the .cs files that specify the definition for the document type.</p>
<pre class="brush:csharp">using Vega.USiteBuilder;

namespace Orc.OurSite.USiteBuilder.DocTypes
{        
    // This 'partial' class should just be the doc type definition
    [DocumentType(Name = "Blog Post", IconUrl = "doc.gif", AllowedTemplates = new string[] { "OrcBlogPost" })]
    public partial class BlogPost : BaseDocType  
    {
        // blog post properties here
    }
}
</pre>
<p>Now, in another, separate .cs file, but <strong><em>within the same namespace;</em></strong></p>
<pre class="brush:csharp">namespace Orc.OurSite.USiteBuilder.DocTypes
{        
    // This 'partial' class should just be the doc type custom methods
    public partial class BlogPost : BaseDocType  
    {
        public void HasPreviousPost() { }

        public void HasNextPost() { }
    }
}
</pre>
<h3>Using Vega.USiteBuilder.ContentHelper within templates</h3>
<p>Now that you have your classes all set up and ready to go, lets get some content on to a page.</p>
<p>It's important to note that that for each Razor macro (.cshtml) you create, it already contains;</p>
<ul>
<li><strong><em>Model</em></strong>, which is of type dynamic</li>
<li><strong><em>CurrentModel</em></strong> is of type umbraco.MacroEngines.DynamicNode</li>
</ul>
<p>Normally you'd use these to walk over nodes and find DynamicNode content, often by <a title="DynamicNode Methods" href="http://our.umbraco.org/wiki/reference/code-snippets/razor-snippets/dynamicnode-(and-model)-members-and-properties">using the associated methods to find children, media, descendents and ancestors</a>. This can be tricky at times, especially if you're creating custom code. When using these methods, because of their dynamic nature, you sometimes have to remember the properties that you want to output. So, what you really need is the Vega.USiteBuilder.ContentHelper to return your strongly typed objects and ultimately give you better intellisense within Visual Studio.</p>
<h3>An example "BlogPost" Razor Macro</h3>
<p>Let us start with a simple example. We start with a namespace declarations to our document types and to uSiteBuilder. We can then invoke the ContentHelper to fetch us the strongly typed instance by passing in the type and Model id.</p>
<pre class="brush:csharp">@using Orc.OurSite.USiteBuilder.DocTypes
@using Vega.USiteBuilder

@{ 
    BlogPost blogPost = ContentHelper.GetByNodeId&lt;BlogPost&gt;(Model.Id);
}

</pre>
<p>And now you can start to write your HTML5 markup, using your strongly-typed instance properties and methods;</p>
<pre class="brush:html">&lt;h1&gt;@blogPost.Name&lt;/h1&gt;

@Html.Raw(blogPost.bodyText)

&lt;time&gt;@blogPost.CreateDate.ToString("dd MMMM, yyyy")&lt;/time&gt;

&lt;ul class="blog-navigation"&gt;
    @if (blogPost.HasPreviousPost) 
    {
        &lt;li class="previous"&gt;
            &lt;a href="@blogPost.PreviousPost.NiceUrl"&gt;Previous Post&lt;/a&gt;
        &lt;/li&gt;
    }
    @if (blogPost.HasNextPost)
    {
        &lt;li class="next"&gt;
            &lt;a href="@blogPost.NextPost.NiceUrl"&gt;Next Post&lt;/a&gt;
        &lt;/li&gt;
    }
&lt;/ul&gt;
</pre>
<h3>Conclusion</h3>
<p>USiteBuilder provides an important step in building your Umbraco Sites using a "code first" approach. Using the Vega.USiteBuilder.ContentHelper, you can quickly and easily build templates that return strongly typed objects for use in Razor Macros. Overall, USiteBuilder is an excellent way of controlling and creating document type properties, without using the usual Umbraco UI.</p>
<p>Further resources and references can be found at;</p>
<ul>
<li>Tutorials and Resources from the uSiteBuilder Website - <a target="_blank" href="http://usitebuilder.vegaitsourcing.rs/">http://usitebuilder.vegaitsourcing.rs/</a></li>
<li>The uSiteBuilder source code on Codeplex - <a href="http://usitebuilder.codeplex.com/">http://usitebuilder.codeplex.com/</a></li>
<li>The uSiteBuilder Importer Package - <a href="http://our.umbraco.org/projects/developer-tools/usitebuilder-import">http://our.umbraco.org/projects/developer-tools/usitebuilder-import</a></li>
</ul>]]></description></item><item><title>Kickstarting validation in Umbraco</title><link>http://offroadcode.com/blog/2012/7/9/kickstarting-validation-in-umbraco/</link><pubDate>Mon, 09 Jul 2012 00:00:00 GMT</pubDate><guid>http://offroadcode.com/blog/2012/7/9/kickstarting-validation-in-umbraco/</guid><description><![CDATA[ <p>The example uses some of the advanced features of Umbraco and techniques that will be familiar to users of ASP.NET MVC. Ultimately, this tutorial will give you a solid foundation to allow you to easily pass information to the server, validate it and respond accordingly.</p>
<p>Ideally you'll have a local test project that you can use as a sandbox, so that you can play about and see how some of the techniques outlined will work. Alternatively, you can do what we did and start with a <a href="http://umbraco.codeplex.com/releases/view/81011" title="Download Umbraco" target="_blank">fresh install of Umbraco Web 4.7.2</a>. We configured this fresh install to use SQL CE 4 using the "Simple Website" theme. Normally, we'd add code to a separate C# library, but for convenience, we've added code for this post in the App_Code folder.</p>
<h3>Diving into the code</h3>
<p>We're like you, sometimes we just want to see the code upfront... so <a title="Download the example zip file" href="/downloads/kickstarting-validation-example.zip">here is a downloadable ZIP with everything you need to get going</a>. You'll find the good stuff in the following folders;</p>
<ul>
<li>/macroscripts/contactform.cshtml</li>
<li>/_assets/js/</li>
<li>/App_Code/</li>
</ul>
<p>Note that we created our own masterpage for the contact form. This is because the theme we're using would have meant using nested forms.</p>
<p><strong><a title="Download the example project..." href="/downloads/kickstarting-validation-example.zip">DOWNLOAD THE UMBRACO EXAMPLE PROJECT (10Mb)</a></strong></p>
<h3>Adding Javascript Libraries</h3>
<p>So, to start, let us add some javascript to our master page. These files will be the latest (and ideally minified) versions of <a target="_blank" title="Download jQuery" href="http://www.jquery.com">jQuery</a>, the <a target="_blank" title="Download the jQuery Validate Plugin" href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery Validate</a> plug-in and <a title="Download JSON2.js" href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js">JSON2.js</a>. For those that are not familiar with JSON2, it creates a global JSON object containing two methods: stringify and parse. Note that <a title="JSON methods in modern browsers" href="http://caniuse.com/json">modern browsers already have these methods</a> for dealing with JSON. Also, the order of the files should be; jQuery, jQuery Validate and JSON2.</p>
<pre class="brush: javascript">  &lt;script src="/_assets/js/lib/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt;
  &lt;script src="/_assets/js/lib/jquery.validate.min.js" type="text/javascript"&gt;&lt;/script&gt;
  &lt;script src="/_assets/js/lib/json2.js" type="text/javascript"&gt;&lt;/script&gt;
</pre>
<h3>Constructing the Form</h3>
<p>For this demonstration, we'll be using a simple "Contact Us" form with some basic fields (of which some will be 'required fields'). We can create the form as a MacroScript using Razor which will allow us just enter some simple HTML.</p>
<pre class="brush: html">&lt;form id="contact-us"&gt;
    
    &lt;fieldset&gt;
        
        &lt;h3&gt;Your Details&lt;/h3&gt;
        
        &lt;p&gt;
            &lt;label for="Title"&gt;Title&lt;/label&gt;
            &lt;select id="Title" name="Title"&gt;
                &lt;option value="Mr" selected="selected"&gt;Mr&lt;/option&gt;
                &lt;option value="Mrs"&gt;Mrs&lt;/option&gt;
                &lt;option value="Miss"&gt;Miss&lt;/option&gt;
            &lt;/select&gt;
        &lt;/p&gt;

        &lt;p&gt;
            &lt;label for="FirstName"&gt;First Name*&lt;/label&gt;
            &lt;input type="text" id="FirstName" name="FirstName"&gt;
        &lt;/p&gt;
        
        &lt;p&gt;
            &lt;label for="Surname"&gt;Surname*&lt;/label&gt;
            &lt;input type="text" id="Surname" name="Surname"&gt;
        &lt;/p&gt;
</pre>
<p>For each of the fields, you'll need to ensure that you have an <strong><em>id</em></strong> and a <em><strong>name</strong></em>. These are required by the jQuery Validate plug-in. Once you have your fields set up, you'll need some HTML to display a "please wait" (for when we're processing the form) and somewhere to display the response after submitting the form to the server. We've used some inline styles to hide the content and style it, you should take the time to style up these elements properly for a better user experience.</p>
<pre class="brush: html">    &lt;p&gt;
            &lt;label for="Message"&gt;Message*&lt;/label&gt;
            &lt;textarea rows="5" cols="50" id="Message" name="Message"&gt;&lt;/textarea&gt;
        &lt;/p&gt;
        
        &lt;input type="submit" value="Contact Us" /&gt;

    &lt;/fieldset&gt;
    
    &lt;p class="please-wait" style="display:none;"&gt;
        &lt;img src="/_assets/images/loading.gif" /&gt; Please wait...
    &lt;/p&gt;
    
    &lt;div class="response" style="margin-top:1em; display:none;"&gt;
        &lt;h3 class="response-title"&gt;&lt;/h3&gt;
        &lt;p class="response-message"&gt;&lt;/p&gt;
    &lt;/div&gt;

&lt;/form&gt;

</pre>
<p>Now we've got our form HTML ready to go, we can start adding some code. To reiterate, for convenience of this blog post we've simply added our code to the App_Code folder. We'd normally add any logic to a separate C# library and include that namespaced library via a post-build event.</p>
<h3>DTO's and Data Annotation</h3>
<p>In order to process the form on the server we want to create a <a target="_blank" title="Data Transfer Objects" href="http://en.wikipedia.org/wiki/Data_transfer_object">Data Transfer Object</a> (or DTO). We can then decorate the DTO with some basic <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v=vs.100).aspx" title="Data Annotations" target="_blank">.NET DataAnnotations</a>. It's really important that the properties of the DTO match the name and id of the HTML element, so you have a property of "FirstName" and the HTML element has an id and name of "FirstName". If they do not match, you won't be able to deserialize the form into the DTO.</p>
<pre class="brush:csharp">using System.ComponentModel.DataAnnotations;

namespace DataTransferObjects
{
    /// &lt;summary&gt;
    /// Summary description for ContactFormDto
    /// &lt;/summary&gt;
    public class ContactFormDto
    {
        /// &lt;summary&gt;
        /// Title of the person, e.g. Mr, Mrs, Miss...
        /// &lt;/summary&gt;
        public string Title { get; set; }

        /// &lt;summary&gt;
        /// First Name [Required]
        /// &lt;/summary&gt;
        [Required(ErrorMessage = "Please enter your first name")]
        public string FirstName { get; set; }

        /// &lt;summary&gt;
        /// Surname [Required]
        /// &lt;/summary&gt;
        [Required(ErrorMessage = "Please enter your surname")]
        public string Surname { get; set; }
</pre>
<p>To allow us to validate the DTO, we're going to borrow some of the basic code from the <a title="The original xVal project" href="http://xval.codeplex.com/">original xVal project by Steve Sanderson</a>. This was the idea of using a <em><strong>DataAnnotiationsValidationRunner </strong></em>to run through all the properties on an instance and check the validity of the values of the properties using Data Annotatiations they were decorated with (<em>don't worry to much about the code below, it works just fine!</em>)</p>
<pre class="brush:csharp">using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace DataValidation
{
    public static class DataAnnotationsValidationRunner
    {
        public static IEnumerable&lt;ErrorInfo&gt; GetErrors(object instance)
        {
            return from prop in TypeDescriptor.GetProperties(instance).Cast&lt;PropertyDescriptor&gt;()
                   from attribute in prop.Attributes.OfType&lt;ValidationAttribute&gt;()
                   where !attribute.IsValid(prop.GetValue(instance))
                   select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);
        }
    }
}
</pre>
<p>So, we now have a method that will check an instance and return an enumerable list of <em>ErrorInfo</em> instances. The <em>ErrorInfo </em>class simply consists of a <em>PropertyName</em>, <em>ErrorMessage </em>and <em>Instance;</em></p>
<pre class="brush:csharp">namespace DataValidation
{
    public class ErrorInfo
    {
        public ErrorInfo(string propertyName, string errorMessage, object instance)
        {
            PropertyName = propertyName;
            ErrorMessage = errorMessage;
            Instance = instance;
        }

        public string PropertyName { get; set; }
        public string ErrorMessage { get; set; }
        public object Instance { get; set; }
    }
}
</pre>
<h3>POSTing data to the server</h3>
<p>With our basic JS libraries, Validation and HTML set up, we can now consider how to pass the form input to the server and validate it. The easiest way to do this is via the <a target="_blank" href="http://our.umbraco.org/wiki/reference/umbraco-base/simple-base-samples">RESTful interface that Umbraco provides</a>. It's fairly trivial to set up a simple class and decorate it with the interface methods;</p>
<pre class="brush:csharp">namespace Rest
{
    [RestExtension("Validation")]
    public class Base
    {

        private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
        
        [RestExtensionMethod(returnXml = false)]
        public static string ContactForm()
        {
</pre>
<p>This will give us the url of <em>/base/Validation/ContactForm</em> where we can post data to. Now we have a place on the server that we post the data, process the form and pass back a response. <br /><br />We still need to pass the data to the server though, so let's leverage the power of jQuery and its AJAX methods to help us. We'll need to create and add a new "contact-form.js" file in which we can add some javascript methods that will help us. The basic idea is to serialize the form data and POST it to the server in a string of JSON. To do this, we can extend jQuery with a simple <em>serializeObject </em>function that will run through the form elements and create a key / value pair for each element.</p>
<pre class="brush:javascript">/*
* handy jQuery serializeObject extension
* usage : $("#myForm").serializeObject();
*/
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
</pre>
<p>It's a common practise to start using jQuery to manipulate the DOM via a handler when its loaded (usually referred to as "on document ready"). It's considered best practise to create some variables to hold jQuery references to DOM elements. This stops repeated calls to find elements in the DOM thus speeding up execution.</p>
<pre class="brush:javascript">/*
* Document Ready
*/

$(function () {

    var contactForm = $("#contact-us");
    var pleaseWait = $(".loading");

    var response = $(".response");
    var responseTitle = $(".response-title");
    var responseMessage = $(".response-message");
</pre>
<p>So, for our example, we need to initialise the form and set up some basic parameters for the jQuery Validate to fire when the submit button is pressed. It's important to attach the instance of the jQuery Validate to our jQuery form reference (highlighted).</p>
<pre class="brush:javascript">   /*
    * Initialise the Contact Form
    */
    var initContactForm = function () {

        contactForm.validator = contactForm.validate({

            // this is the html element that will wrap error messages
            errorElement: "span",

            // this is where we'll place the error message
            errorPlacement: function (error, element) {
                error.appendTo(element.parent());
            },

            // set up form submit event
            submitHandler: submitContactForm

        });

    };
</pre>
<p>For the submitHandler we've created a single function (<em>submitContactForm</em>) that will POST the data to server. Note how were using the <em>JSON.stringify</em> and <em>contactForm.serializeObject </em>to create a string of JSON from the form elements. This string is what will get passed to the server.</p>
<pre class="brush:javascript">/*
 * Submit the Contact Form via AJAX
 */
var submitContactForm = function () {

	// show the fact the form is loading;
	pleaseWait.show();
	response.hide();
	responseTitle.empty().hide();
	responseMessage.empty().hide();

	// now serialize the form data;
	var json = JSON.stringify(contactForm.serializeObject());

	// post to server
	$.ajax({
	    type: "POST",
	    url: "/base/Validation/ContactForm",
	    data: json,
	    success: function (formResultDto) {

		// do stuff

	    }
	});
	
}
</pre>
<p>Below is an example of the stringify'd JSON that will be passed to the server;</p>
<p><img src="/media/14584/json_string.gif" width="512" height="196" alt="json string"/></p>
<h3>Validation on the server</h3>
<p>Now that we've passed the string to the server (to our "base" <em>Validation.ContactForm</em> method), we need to deserialize it into a contactFormDto instance and then validate that instance. First we grab the string from the Form object and then attempt to deserialize it. This is done by <a href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx" title="Javascript Serializer" target="_blank">the native .NET JavaScriptSerializer</a> and telling it to deserialize the string into our ContactFormDto type.</p>
<p><img src="/media/14589/contact_form_deserialized.gif" width="647" height="282" alt="contact dto deserialized"/><br /><br /><br />Next we check for any errors. If there are errors we create a simple <em>FormResultDto</em>, that consists of a <em>Title</em>, <em>Message </em>and an enumerable list of <em>ErrorInfo</em> instances. This will be serialized and sent back to the client.</p>
<pre class="brush:csharp">// create a response that will be serialized and sent back
var formResponse = new FormResultDto();

// grab the json from Form object
var json = HttpContext.Current.Request.Form[0];
            
// try and deserialize
var contactFormDto = Serializer.Deserialize&lt;ContactFormDto&gt;(json);
if ( contactFormDto != null )
{
   // try and validate;
   var errors = DataAnnotationsValidationRunner.GetErrors(contactFormDto);
   if (errors.Any()) {
         formResponse.Title = "Sorry";
         formResponse.Message = "Please ensure you've entered all the fields correctly";
         formResponse.Errors = errors;
         return Serializer.Serialize(formResponse);
   }
}</pre>
<p>Now, of course, if there were no errors, you can continue processing your data. At this point, your form info is nicely wrapped up in a handy DTO instance, this means you can pass it further down into your business logic or data layers. Sweet.</p>
<p>At this point, after successful validation, you'll just pass back a 'successful' FormResultDto.</p>
<pre class="brush:csharp">// after processing, let the user know what's up
formResponse.Title = "Thank you";
formResponse.Message = "Your details were submitted successfully. You'll hear from us soon.";
formResponse.Errors = null;
return Serializer.Serialize(formResponse);
</pre>
<h3>Dealing with the response</h3>
<p>So, back over on the client, we need to show the response from the server. We can do this within the success method of our original AJAX request. Now we deserialize the formResultDto on the client using jQuery parseJSON method. Based on the response we can then show errors and / the message.</p>
<pre class="brush:javascript">// post to server
$.ajax({
    type: "POST",
    url: "/base/Validation/ContactForm",
    data: json,
    success: function (formResultDto) {

	var formResult = $.parseJSON(formResultDto);

	// got errors?
	if (formResult.Errors != null) {
	    showErrors(formResult.Errors);
	};

	// got message?
	if (formResult.Title != null &amp;&amp; formResult.Message != null) {

	    pleaseWait.hide();

	    response.show();
	    responseTitle.show().text(formResult.Title);
	    responseMessage.show().text(formResult.Message);

	}

    }
});
</pre>
<p>If we need to show the errors, we can pass the errors back to the validator to show. We can also work out what the first error is and set the form to focus on it, giving a better usability experience for the user.</p>
<pre class="brush:javascript">/* 
* Show Errors
*/
var showErrors = function (formErrors) {

	var e = {};
	var firstError = "";

	for (var i in formErrors) {
		var error = formErrors[i];
		if (i == 0) firstError = error.PropertyName;
		e[error.PropertyName] = error.ErrorMessage;
	}

	contactForm.validator.showErrors(e);
	$("#" + firstError).focus();

};
</pre>
<p>Finally you'll see the errors displayed neatly under the form elements.</p>
<p><img src="/media/14619/contact_form_errors.gif" width="469" height="443" alt="contact form errors"/></p>
<h3>Taking it further...</h3>
<p>So, the above steps provide a really neat way of passing form data to the server, wrapping it up in some simple instances and dealing with processing and validation. You could now take the example further by perhaps improving on the following;</p>
<ul>
<li>Extending the jQuery Validate initialization to include <a href="http://stackoverflow.com/questions/3890396/jquery-validate-with-multiple-rules#answers-header" title="multiple rules and messages" target="_blank">rules and messages for clientside validation</a></li>
<li>Using <a href="http://diveinto.html5doctor.com/forms.html" title="HTML5 attributes" target="_blank">addtional HTML5 attributes</a> for the form elements</li>
<li>Use some more of the Data Annotations to decorate your properties, for example, <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute.aspx" title="Range Attribute" target="_blank">Range</a> or <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.regularexpressionattribute.aspx" title="Regex Attribute" target="_blank">RegEx</a> Attributes</li>
<li>It doesn't have to necessarily be form information that you pass back to the server, it could be from some other UI interaction, such as sending latitude and longitude to update a map in real time, or perhaps some other form of look-up</li>
<li>Implement better error handling for production use</li>
</ul>
<p>We hope that you've learnt something from the guide above and of course, if you spot any errors, please let us know.</p>]]></description></item><item><title>Codegarden 2012 talk</title><link>http://offroadcode.com/blog/2012/6/14/codegarden-2012-talk/</link><pubDate>Thu, 14 Jun 2012 00:00:00 GMT</pubDate><guid>http://offroadcode.com/blog/2012/6/14/codegarden-2012-talk/</guid><description><![CDATA[ <p>For more information about any of the topics covered in Pete's mobile development with Umbraco talk at Codegarden 2012 today, please bookmark this page. We'll be adding the slides mentioned in the talk as soon as possible.</p>
<h2>Resources</h2>
<ul>
<li><a href="http://our.umbraco.org/projects/developer-tools/asset-compressor" title="Asset compressor">Umbraco Asset compressor</a></li>
<li><a href="https://github.com/Offroadcode/Starter-Kit" title="Starter kit">Offroadcode "Starter Kit" on GitHub</a></li>
</ul>
<p>If you have any questions in the meantime, please send a tweet to either <a title="@peteduncanson" href="http://twitter.com/peteduncanson">@peteduncanson</a> or <a title="@welcomebrand" href="http://twitter.com/welcomebrand">@welcomebrand</a>.</p>
<p>In the meantime, here are some additional design and development resources from <a title="HTML5 and Mobile resources" href="/blog/2011/11/3/html5-and-mobile-resources/">Pete's talk from the UK Umbraco festival last year</a>.</p>
<p>Thanks! #H5YR.</p>]]></description></item><item><title>Setting up TeaCommerce and Google Analytics</title><link>http://offroadcode.com/blog/2012/5/30/setting-up-teacommerce-and-google-analytics/</link><pubDate>Wed, 30 May 2012 00:00:00 GMT</pubDate><guid>http://offroadcode.com/blog/2012/5/30/setting-up-teacommerce-and-google-analytics/</guid><description><![CDATA[ <p><a href="http://www.teacommerce.dk/en.aspx">TeaCommerce</a> is not a full blown ecommerce system. For that fact alone I really like it. It stops short of second guessing what you might need by bloating itself with 101 features and instead just gives you a core chunk of functionality which you can build on top of. All the nasty bits you might have to code up yourself are taken care of, its just the custom bits that you then have to focus on. I like this approach, it leads to very few work arounds and hacks which can only be a good thing.</p>
<p>Using it in your templates is really easy too thanks to their <a href="http://anders.burla.dk/umbraco/tea-commerce-xslt-extensions/">well thought out XML API</a>. We are using XSLT here which gets back the current users basket data in XML format. So it should be easy to parse it out into our Google Analytics tracking.</p>
<p>GA allows us to track the complete make up of an order by passing non-personal data through to it on our thank you page of our check out process. This is really handy for seeing the value of visits to the site. When we know how much money transaction is generating we can work out all sort of additional data so it is an important peice of the ecommerce puzzle.</p>
<p>So heres the code then I'll explain it a little more:</p>
<pre>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE xsl:stylesheet [ &lt;!ENTITY nbsp "&amp;#x00A0;"&gt; ]&gt;
&lt;xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns:msxml="urn:schemas-microsoft-com:xslt"
  xmlns:umbraco.library="urn:umbraco.library" xmlns:teacommerce="urn:teacommerce" 
  exclude-result-prefixes="msxml umbraco.library teacommerce"&gt;


&lt;xsl:output method="xml" omit-xml-declaration="yes"/&gt;

&lt;xsl:param name="currentPage"/&gt;

&lt;xsl:template match="/"&gt;
  &lt;!-- 
  For testing use something like this, make sure the id is a valid order that actually bought something!
  &lt;xsl:variable name="Order" select="teacommerce:GetSpecificOrderXml(1190)" /&gt;
  --&gt;
  
  &lt;!-- Get the current users basket --&gt;
  &lt;xsl:variable name="Order" select="teacommerce:GetFinalizedOrderXml()" /&gt;

  &lt;!-- shortcut variable --&gt;
  &lt;xsl:variable name="orderID" select="$Order/@id" /&gt;
  
  &lt;!-- Needed to make values in our JS safe for rendering --&gt;
  &lt;xsl:variable name="blacklist"&gt;&amp;apos;\&lt;/xsl:variable&gt;
&lt;!--  
  Quick test of my character blacklist setup, used for making values JS safe(ish)
  
  &lt;xsl:variable name="testString"&gt;Pete&amp;apos;s amazing hack\s&lt;/xsl:variable&gt;
  [&lt;xsl:value-of select="translate( $testString, $blacklist, '' )" /&gt;] --&gt;
  
  
&lt;script type="text/javascript"&gt;
  &lt;!-- 
  For testing comment out the script tags and uncomment the pre tags
  &lt;pre&gt; --&gt;
  &lt;xsl:if test="$Order/@paymentStatus='Captured'"&gt;
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXXX-X']); // Your GA id here
    _gaq.push(['_trackPageview']);
    _gaq.push(['_addTrans',
      '&lt;xsl:value-of select="$orderID" /&gt;',           // order ID - required
      'Cutting Edge Knives',  // affiliation or store name
      '&lt;xsl:value-of select="$Order/@totalPriceFormattedNoSymbol" /&gt;',          // total - required
      '&lt;xsl:value-of select="$Order/@totalVATFormattedNoSymbol" /&gt;',           // tax
      '&lt;xsl:value-of select="$Order/shipping/@feeFormattedNoSymbol" /&gt;',              // shipping
      '&lt;xsl:value-of select="translate( $Order/properties/billing_Town, $blacklist, '' )" /&gt;',       // city
      '',     // state or province (we don't collect this)
      '&lt;xsl:value-of select="translate( $Order/properties/billing_Country, $blacklist, '' )" /&gt;'             // country
    ]);
  
    &lt;xsl:for-each select="$Order/orderLine"&gt;  
      _gaq.push(['_addItem',
        '&lt;xsl:value-of select="$orderID" /&gt;',           // order ID - required
        '&lt;xsl:value-of select="translate( @nodeId, $blacklist, '' )" /&gt;',           // SKU/code - required (we use nodeId for our SKU's)
        '&lt;xsl:value-of select="translate( properties/fullName, $blacklist, '' )" /&gt;',        // product name
        '&lt;xsl:value-of select="translate( umbraco.library:GetXmlNodeById(@nodeId)/typeOfKnife, $blacklist, '' )" /&gt;',   // category or variation (knife type here for us, chef, paring, etc)
        '&lt;xsl:value-of select="@unitPriceFormattedNoSymbol" /&gt;',          // unit price - required
        '&lt;xsl:value-of select="@quantity" /&gt;'               // quantity - required
      ]);
    &lt;/xsl:for-each&gt;
  
    _gaq.push(['_trackTrans']); //submits transaction to the Analytics servers
  
    (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
  &lt;/xsl:if&gt;
&lt;!-- &lt;/pre&gt; --&gt;
&lt;/script&gt;
&lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;
</pre>
<p>So we get the current users order XML and then render it out in <a href="https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce">GA's suggested format for product tracking</a>. The XML returned contains just about everything you could need. One of the bits I love is how TeaCommerce includes all the formatted values you might every want to use. You can see I've used totalVATformattedNoSymbol to give me the total VAT cost minus the pound sign (as GA does not care for currency symbols). This is just one of about 12 different attributes for getting the price out in all its various formats. Saves me having to write my own clean up scripts, helpers, etc. Nice work.</p>
<p>For testing we found it useful to use an existing order xml, using the "GetSpecificOrderXml" method. Luckily this method returns and order in same XML format so its perfect for testing. For speed we also rendered out our code in a &lt;pre&gt; tag rather than a &lt;script&gt; tag to save us having to view source all the time.</p>
<p>To prevent any of our output values from breaking our completed javascript output (for instance by including a single quote in the value) I simply remove single quotes and black slashed (as it could be a JS escape sequence for instance). I do this is the translate method in XSLT and use a handy variable to store my blacklist of characters to remove. This is a handy as if we ever need to add anther character I only have the one place to do it, nice and DRY. This should be good enough.</p>
<p>One word of warning, TeaCommerce uses id's for everything. These are the internal database ids that is uses NOT your product ids (aka SKU's). Watch out for that one. We simply use the nodeId of the product inside Umbraco as our SKU's which keeps things nice and easy. We don't have any variants though so you might have to use the productID instead. Check you TeaCommerce xml to see what you can use.</p>
<p>So if you use TeaCommerce you should be able to cut and paste the above into a macro and give yourself a really good head start for tracking products.</p>
<p>Hope it helps someone. Let us know if you found it useful.</p>]]></description></item><item><title>Code Smart, simple tricks to make programming easier, part 1</title><link>http://offroadcode.com/blog/2012/4/30/code-smart,-simple-tricks-to-make-programming-easier,-part-1/</link><pubDate>Mon, 30 Apr 2012 00:00:00 GMT</pubDate><guid>http://offroadcode.com/blog/2012/4/30/code-smart,-simple-tricks-to-make-programming-easier,-part-1/</guid><description><![CDATA[ <p>All the posts in this series are purposefully short. They are intended to focus on one simple style/trap/habit and make you think about it. Bite size examples which you can chew on a while. They may also be blatantly obvious, but then this is normally the case...once its pointed out to you.</p>
<p>So I've just seen this code in a project we've inherited:</p>
<pre>if ( Session["loggedIn"] != null ) { 
  someValue = Session["loggedIn"].ToString();
}</pre>
<p>It works a treat and does what it needs to on the face of it.</p>
<p>This session variable is accessed via a string ("loggedIn"). Trouble is this is referred to a few times through out the code (only twice in my example though). Its screaming out for a typo. You know one of those nasty ones that take an age to debug, something like..."logedIn", "loggedin", etc. something understandable in how it happened but still daft that it happened at all. This is a classic case of not following the <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY principle</a>.</p>
<p>So don't do it. Change it! Refactor it and remove the chance of a cock up before it even happens. There are lots of ways of doing this, for starters declare the string once at the top of the method:</p>
<pre>string loggedInKey = "loggedIn";
if ( Session[loggedInKey ] != null ) { 
  someValue = Session[loggedInKey ].ToString();
}
</pre>
<p>There are other ways to do it, setting it as a project wide constant for example or a property on a class. I'll leave those up to you. The point though is you now have one place where the value is declared, you now have the compiler on your side, it will do the eye balling for you and double check.</p>
<p>A simple change to your coding style, such a little detail, yet possibly several hours saved by removing a silly error before it even happens. All this for next to no extra effort up front.</p>
<p><strong>Code smarter not harder</strong>.</p>
<p>More tips/observations to follow.</p>]]></description></item></channel></rss>
