<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>These Days Labs</title>
	
	<link>http://labs.thesedays.com</link>
	<description>To infinity and beyond</description>
	<lastBuildDate>Thu, 29 Nov 2012 14:13:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/TheseDaysLabs" /><feedburner:info uri="thesedayslabs" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>A dynamic page cache for Umbraco macros</title>
		<link>http://feedproxy.google.com/~r/TheseDaysLabs/~3/ao7jH94mrUo/</link>
		<comments>http://labs.thesedays.com/blog/2012/11/29/a-dynamic-page-cache-for-umbraco-macros/#comments</comments>
		<pubDate>Thu, 29 Nov 2012 14:13:32 +0000</pubDate>
		<dc:creator>Lennart Stoop</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://labs.thesedays.com/?p=1953</guid>
		<description><![CDATA[When support for Razor scripts became available in Umbraco 4.7 our team adopted it very quickly and apart from the occasional maintenance of existing XSLT scripts we never really looked back since. For a .NET developer writing a lambda expression is simply much more intuitive than writing an XPath query and the Razor engine provides [...]]]></description>
			<content:encoded><![CDATA[<p>When support for Razor scripts became available in Umbraco 4.7 our team adopted it very quickly and apart from the occasional maintenance of existing XSLT scripts we never really looked back since. For a .NET developer writing a lambda expression is simply much more intuitive than writing an XPath query and the Razor engine provides better means for extending scripts and integrating business logic.</p>
<p>However we do realize Razor for Umbraco has its flaws. It is not exactly the Razor view engine we have learned to use in ASP.NET MVC and we need to be careful with LINQ or lambda expressions as not all of the features perform equally well. Over time we learned the dos and don’ts but it did involve some trial and error and it had us fix performance issues on several occasions.</p>
<p><strong>Page level caching                          </strong></p>
<p>The document templates we create in Umbraco often contain multiple (Razor) macros that fetch common data or iterate common nodes or node trees. Having these types of operations perform separately in each macro comes with a performance penalty (especially for expensive operations) and that is why we cache commonly accessed data and nodes on page level.</p>
<p>As the templates are still running on top of ASP.NET web forms we figured a good place to cache these operations is in the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.items.aspx" target="_blank">page items collection</a>. Of course we could also have used a different cache object and the <a href="http://umbraco.com/follow-us/blog-archive/2012/10/30/getting-started-with-mvc-in-umbraco-410.aspx" target="_blank">built-in MVC features</a> of Umbraco 4.10+ will probably have us review this implementation as soon as we start using it (which is hopefully very soon ;-))</p>
<pre class="brush: csharp; title: ; notranslate">
    public abstract class PageCache
    {
        protected abstract T GetPageItem&lt;T&gt;(string key, Func&lt;T&gt; objectRetrieval);
    }
</pre>
<pre class="brush: csharp; title: ; notranslate">
    public class WebFormsPageCache : PageCache
    {
        protected override T GetPageItem&lt;T&gt;(string key, Func&lt;T&gt; objectRetrieval)
        {
            var page = HttpContext.Current.Handler as Page;
            if (page.Items[key] == null)
            {
                page.Items[key] = objectRetrieval();
            }
            return (T)page.Items[key];
        }
    }
</pre>
<p>By first creating a “master” page cache we can cache operations that will probably be used throughout the entire website, such as accessing the root node or a data repository query that is often used.</p>
<pre class="brush: csharp; title: ; notranslate">
    public class MasterPageCache : WebFormsPageCache
    {
        public DynamicNode DataNode
        {
            get
            {
                return GetPageItem&lt;DynamicNode&gt;(&quot;DataNode&quot;, delegate
                {
                    return new DynamicNode(Node.getCurrentNodeId()).AncestorOrSelf(1)
                        .ChildrenAsList.First(y =&gt; y.NodeTypeAlias == &quot;DataContainer&quot;);
                });
            }
        }

        public EventList ActiveEventList
        {
            get
            {
                return GetPageItem&lt;EventList&gt;(&quot;ActiveEventList&quot;, delegate
                {
                    return new EventRepository().GetActiveEventList();
                });
            }
        }
    }
</pre>
<p>The page cache for a specific template or document type inherits from the master page cache allowing it to further extend any of the master cache operations.</p>
<pre class="brush: csharp; title: ; notranslate">
    public class HomePageCache : MasterPageCache
    {
        public DynamicNode HomeHeaderCarousel
        {
            get
            {
                return GetPageItem&lt;DynamicNode&gt;(&quot;HomeHeaderCarousel&quot;, delegate
                {
                    return DataNode.ChildrenAsList.First(n =&gt; n.NodeTypeAlias == &quot;HomeHeaderCarousel&quot;);
                });
            }
        }

        public List&lt;DynamicNode&gt; HomeHeaderCarouselSelectedEvents
        {
            get
            {
                return GetPageItem&lt;List&lt;DynamicNode&gt;&gt;(&quot;HomeHeaderCarouselSelectedEvents&quot;, delegate
                {
                    return HomeHeaderCarousel.ChildrenAsList.Items
                            .Where(i =&gt; ActiveEventList.Items.Count(e =&gt; e.Id == i.GetPropertyValue(&quot;eventId&quot;)) &gt; 0)
                            .ToList();
                });
            }
        }
    }
</pre>
<p>Finally we can new up a page cache in a macro, and we are rest assured that the cached operations will only execute once (provided of course that other macros on the page also use a page cache).</p>
<pre class="brush: plain; title: ; notranslate">
@using System.Xml.Linq;
@using TheseDays.Sportsbetting.Business.Events;
@using TheseDays.Sportsbetting.Business.Web;
@using TheseDays.Sportsbetting.UserControls.Helpers;
@using umbraco.MacroEngines;

@{
    var pageCache = new HomePageCache();
    var maxEvents = 5;
}

@if (pageCache.HomeHeaderCarouselSelectedEvents.Count() &gt; 0)
{
    foreach (var item in pageCache.HomeHeaderCarouselSelectedEvents.Take(maxEvents))
    {
        var imagePath = XDocument.Parse(item.GetPropertyValue(&quot;image&quot;)).Descendants(&quot;umbracoFile&quot;).First().Value;
        var eventItem = pageCache.ActiveEventList.Items.First(i =&gt; i.Id == item.GetPropertyValue(&quot;eventId&quot;));

        &lt;div&gt;
            &lt;img id=&quot;item-@item.Id&quot; src=&quot;/ImageGen.ashx?width=@imgWidth&amp;image=@imagePath&quot; /&gt;
            @eventItem.Time.ToShortDateString() @eventItem.Time.ToShortTimeString() @eventItem.HomeTeamShort - @eventItem.AwayTeamShort
        &lt;/div&gt;
    }
}
</pre>
<p><strong>Resolving a page cache dynamically</strong></p>
<p>Most of the time page caches relate directly to a document type so we figured it would be cool if we could just have a page cache “magically” resolved based on that document type rather than having to new up a page cache in each macro. The Razor engine provides us with a model which has a reference to the document type and basically we would like to do something like this:</p>
<pre class="brush: plain; title: ; notranslate">
@{
    var pageCache = UmbracoPageCache.Resolve(Model.NodeTypeAlias);
}
</pre>
<p>Even though I am not too keen on using reflection and dynamic types in .NET with some experimenting I did manage to come up with a solution which is based on a very simple naming convention. A page cache is resolved when its class name starts with the node type alias of the document type. If no page cache could be resolved, a fall back will try to resolve the master page cache of which the class name should start with “Master”. This is nice if you don’t have a specific page cache setup but if you would still like to use some of the master cache operations.</p>
<p>Although it is still a bit experimental, the code snippets below show how it can be done. Note that the code uses an assembly filter which limits the assembly lookup to assemblies marked with company name &#8220;TheseDays&#8221;. </p>
<p>Feel free to use or extend the code or to post any feedback or remarks. Cheers!</p>
<pre class="brush: csharp; title: ; notranslate">
    public abstract class PageCacheResolver
    {
        protected TypeLocator _typeLocator;
        protected AssemblyFilter _assemblyFilter;
        protected Assembly _pageCacheAssembly;

        public PageCacheResolver(AssemblyFilter assemblyFilter)
            :this(assemblyFilter, new TypeLocator())
        {
        }

        public PageCacheResolver(AssemblyFilter assemblyFilter, TypeLocator typeLocator)
        {
            _assemblyFilter = assemblyFilter;
            _typeLocator = typeLocator;

            ResolvePageCacheAssembly();
        }

        protected virtual void ResolvePageCacheAssembly()
        {
            _pageCacheAssembly = new AssemblyLocator(_assemblyFilter)
                .FindAssembliesContainingSubclassesOf&lt;PageCache&gt;().First();
        }

        protected virtual dynamic ResolveByPrefix(string prefix)
        {
            if (String.IsNullOrEmpty(prefix))
                throw new ArgumentException(&quot;prefix&quot;);

            var cacheType = _typeLocator.FindSubclassesOf&lt;PageCache&gt;(_pageCacheAssembly)
                        .Where(t =&gt; t.Name.ToLower().StartsWith(prefix.ToLower()))
                        .FirstOrDefault();

            if (cacheType != null)
            {
                return _pageCacheAssembly.CreateInstance(cacheType.FullName);
            }
            else
            {
                return null;
            }
        }
    }
</pre>
<pre class="brush: csharp; title: ; notranslate">
    public sealed class UmbracoPageCache : PageCacheResolver
    {
        private UmbracoPageCache(AssemblyFilter assemblyFilter)
            :base(assemblyFilter)
        {
        }

        public static dynamic Resolve(string nodeTypeAlias)
        {
            var assemblyFilter = new AssemblyFilter();
            assemblyFilter.CustomAttributes.Add(new AssemblyCompanyAttribute(&quot;TheseDays&quot;));
            var resolver = new UmbracoPageCache(assemblyFilter);

            var cache = resolver.ResolveByPrefix(nodeTypeAlias);
            if (cache != null)
            {
                return cache;
            }
            else
            {
                throw new ApplicationException(&quot;Unable to resolve cache&quot;);
            }
        }

        protected override dynamic ResolveByPrefix(string prefix)
        {
            var cache = base.ResolveByPrefix(prefix);

            if (cache != null)
            {
                return cache;
            }
            else
            {
                // Fallback to master cache
                return base.ResolveByPrefix(&quot;master&quot;);
            }
        }
    }
</pre>
<p>Helpers classes for reflection:</p>
<pre class="brush: csharp; title: ; notranslate">
    public class TypeLocator
    {
        public IEnumerable&lt;Type&gt; FindSubclassesOf&lt;T&gt;(Assembly assembly)
        {
            var result = from t in assembly.GetTypes()
                         where t.IsSubclassOf(typeof(T))
                         select t;
            return result;
        }
    }
</pre>
<pre class="brush: csharp; title: ; notranslate">
    public class AssemblyFilter
    {
        public List&lt;Attribute&gt; CustomAttributes;

        public static AssemblyFilter DefaultFilter
        {
            get { return new AssemblyFilter(); }
        }

        public AssemblyFilter()
        {
            CustomAttributes = new List&lt;Attribute&gt;();
        }
    }
</pre>
<pre class="brush: csharp; title: ; notranslate">
    public class AssemblyLocator
    {
        protected AssemblyFilter _filter;

        public AssemblyLocator(AssemblyFilter filter)
        {
            _filter = filter;
        }

        public AssemblyLocator()
            : this(AssemblyFilter.DefaultFilter)
        {
        }

        protected IEnumerable&lt;Assembly&gt; GetFilteredAssemblies()
        {
            IEnumerable&lt;Assembly&gt; result = AppDomain.CurrentDomain.GetAssemblies();

            if (_filter.CustomAttributes.Count() &gt; 0)
            {
                result = result.Where(a =&gt; _filter.CustomAttributes
                    .All(attr =&gt; a.GetCustomAttributes&lt;Attribute&gt;().Contains(attr)));
            }

            return result;
        }

        public IEnumerable&lt;Assembly&gt; FindAssembliesContainingSubclassesOf&lt;T&gt;()
        {
            foreach (var assembly in GetFilteredAssemblies())
            {
                var result = from t in assembly.GetTypes()
                             where t.IsSubclassOf(typeof(T))
                             select t;
                if (result.Count() &gt; 0)
                {
                    yield return assembly;
                }
            }
        }
    }
</pre>
<p>And a very basic unit test:</p>
<pre class="brush: csharp; title: ; notranslate">
    [TestClass]
    public class UmbracoPageCacheShould
    {
        [TestMethod]
        public void ResolveDocumentTypePageCacheIfOneExists()
        {
            var col = UmbracoPageCache.Resolve(&quot;DocumentType&quot;);
            Assert.IsInstanceOfType(col, typeof(DocumentTypePageCache));
        }

        [TestMethod]
        public void ResolveMasterPageCacheIfDocumentTypePageCacheIsMissing()
        {
            var col = UmbracoPageCache.Resolve(&quot;Bullocks&quot;);
            Assert.IsInstanceOfType(col, typeof(MasterPageCache));
        }
    }

    public class MasterPageCache : WebFormsPageCache
    {
    }

    public class DocumentTypePageCache : WebFormsPageCache
    {
    }
</pre>
<img src="http://feeds.feedburner.com/~r/TheseDaysLabs/~4/ao7jH94mrUo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://labs.thesedays.com/blog/2012/11/29/a-dynamic-page-cache-for-umbraco-macros/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://labs.thesedays.com/blog/2012/11/29/a-dynamic-page-cache-for-umbraco-macros/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=a-dynamic-page-cache-for-umbraco-macros</feedburner:origLink></item>
		<item>
		<title>A demo application covering OO design patterns</title>
		<link>http://feedproxy.google.com/~r/TheseDaysLabs/~3/O-WqCnQD6lI/</link>
		<comments>http://labs.thesedays.com/blog/2012/11/12/a-demo-application-covering-oo-design-patterns/#comments</comments>
		<pubDate>Mon, 12 Nov 2012 14:14:05 +0000</pubDate>
		<dc:creator>Lennart Stoop</dc:creator>
				<category><![CDATA[Docs & Guides]]></category>
		<category><![CDATA[Patterns & Frameworks]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[demo]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[solid]]></category>

		<guid isPermaLink="false">http://labs.thesedays.com/?p=1870</guid>
		<description><![CDATA[Recently I was asked by some of my colleagues to organize an internal session on object-oriented programming and design. I figured it would be a great idea so I went along, did some research and decided to walk through the OO fundamentals followed by some demos and sample code illustrating the SOLID design principles. The [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I was asked by some of my colleagues to organize an internal session on <a title="Object-oriented programming" href="http://en.wikipedia.org/wiki/Object-oriented_programming" target="_blank">object-oriented programming</a> and design. I figured it would be a great idea so I went along, did some research and decided to walk through the OO fundamentals followed by some demos and sample code illustrating the <a title="SOLID design principles" href="http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)" target="_blank">SOLID design principles</a>.</p>
<p>The demo covering the fundamentals however became quite large as I ended up <a title="Refactoring code" href="http://en.wikipedia.org/wiki/Code_refactoring" target="_blank">refactoring</a> it a dozen of times, by introducing <a title="Abstraction" href="http://en.wikipedia.org/wiki/Abstraction_(computer_science)" target="_blank">abstractions</a> and adding <a title="Software design pattern" href="http://en.wikipedia.org/wiki/Software_design_pattern">design patterns</a> on the fly. Although I must admit a certain degree of complexity was added to its design, the demo does cover a lot of OO practices and design patterns and it really shows how a good design adds to <a title="Reusability" href="http://en.wikipedia.org/wiki/Reusability" target="_blank">reusability</a>, flexibility and <span style="text-decoration: underline"><a title="Extensibility" href="http://en.wikipedia.org/wiki/Extensibility" target="_blank">extensibility</a></span>.</p>
<p>That is why I decided to share the <a title="Design pattern demo on github" href="https://github.com/TheAmph/DesignPatternDemo" target="_blank">demo code on github</a> and cover its design in this blog post. The application was written in C#.NET and created in Visual Studio 2010, but of course any of the design patterns discussed can be applied in any other OO programming language.</p>
<p><strong>What the application does</strong></p>
<p>The demo&#8217;s functionality is actually very limited. When it launches, a random story is generated and shown in a console window. As you can see in the snapshot below a story unfolds at a market: the market starts, people arrive and tend to their business &#8211; salesmen sell their goods and customers shop for the items they need. Eventually the salesmen close their stalls and the market closes, end of story.</p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2012/11/01-Console-Window.png"><img class="alignnone size-full wp-image-1873" src="http://labs.thesedays.com/wp-content/uploads/2012/11/01-Console-Window.png" alt="" width="542" height="274" /></a></p>
<p><strong>A first glance at the code</strong></p>
<p>The Visual Studio solution consists of 3 projects which (kind of) demonstrate an N-layer approach:</p>
<ul>
<li><strong>Data</strong> – A class library representing the data layer which has not been implemented (yet)</li>
<li><strong>Marketplace</strong> – A class library representing the middle/business layer</li>
<li><strong>Program</strong> – A console application representing the presentation/GUI layer</li>
</ul>
<p>As shown in the code editor below the console application is initiated in the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Program.cs" target="_blank">program’s Main method</a>, which only contains a few statements that create a story. But of course, all of the magic really takes place in the <a href="https://github.com/TheAmph/DesignPatternDemo/tree/master/Marketplace" target="_blank">Marketplace project</a> ;-)</p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2012/11/02-Visual-Studio-Solution.png"><img class="alignnone size-full wp-image-1874" src="http://labs.thesedays.com/wp-content/uploads/2012/11/02-Visual-Studio-Solution.png" alt="" width="525" height="383" /></a></p>
<p><strong>Abstractions, abstractions, abstractions</strong></p>
<p>Since I wanted to cover OO fundamentals such as <a title="Inheritance" href="http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)" target="_blank">inheritance</a>, <a title="Software interface" href="http://en.wikipedia.org/wiki/Software_interface#Software_interfaces" target="_blank">interfaces</a> and <a title="Polymorphism" href="http://en.wikipedia.org/wiki/Polymorphism_(computer_science)" target="_blank">polymorphism</a> the first thing you will notice is that the code in the Marketplace class library is bloated with abstractions. There are several abstract base classes, a shitload of interfaces (when you consider the size of the application) and also the state broadcasting mechanism is completely abstracted out by event handling/subscription.</p>
<p>Another thing you may notice is that the class library’s overall structure (i.e. namespaces) is not as informative as it should be as I organized the classes in order of their appearance during the demo. Just to give you a better idea I had Visual Studio generate a class diagram which I then quickly organized manually (click to enlarge).</p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2012/11/03-Visual-Studio-Class-Diagram.png"><img class="alignnone size-full wp-image-1875" src="http://labs.thesedays.com/wp-content/uploads/2012/11/03-Visual-Studio-Class-Diagram.png" alt="" width="561" height="266" /></a></p>
<p><strong>Extensibility is king</strong></p>
<p>The Marketplace project contains most if not all of the abstractions and building blocks and it also provides several concrete classes that allow for a quick implementation of a market story in the GUI project (Program).</p>
<p>The GUI project then introduces a <a href="https://github.com/TheAmph/DesignPatternDemo/tree/master/Program/Extensibility" target="_blank">series of new concrete subclasses</a> that demonstrate the extensibility of the class library by adding new functionality or by extending existing functionality, in a variety of ways. Let’s have a look at the source code and identify the design patterns that were used.</p>
<p><strong>Template Method</strong></p>
<p>At the center of the class library an abstract class <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Inheritance/Story.cs" target="_blank">Story</a> exists which follows the <a title="Template method pattern" href="http://en.wikipedia.org/wiki/Template_method_pattern" target="_blank">template method pattern</a> allowing its child types to override a series of methods that are executed sequentially when the story’s <em>Play</em> method is called.</p>
<ul>
<li><strong>Initialize</strong> – Allows the story to perform a setup routine (i.e. instantiating the objects it requires)</li>
<li><strong>AttachListeners</strong> – Allows the story to subscribe its event listeners to any of the state notifiers that will broadcast their state changes when the story is running. The default implementation will attach a default event listener if none were attached and it will also subscribe its event listeners to itself (the story itself can also broadcast state changes)</li>
<li><strong>Run </strong>– Allows for the actual implementation of the story. The default implementation provides a loop that adheres to the story settings (start &amp; end date/time and the interval) and it introduces a fourth template method <em>RunStoryLine</em></li>
<li><strong>RunStoryLine </strong>– Allows the story to implement the code for a single story line</li>
</ul>
<p>As formulated by the <a title="Open/Closed principle" href="http://en.wikipedia.org/wiki/Open/closed_principle" target="_blank">open/closed principle</a> the template method approach allows for a very granular implementation within child types. The <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Polymorphism/MarketStory.cs" target="_blank">MarketStory</a> class for example extends the <em>Initialize</em> and <em>AttachListeners</em> methods (using the default implementation as well as adding its own implementation) whereas it completely replaces the implementation of the <em>Run</em> and <em>RunStoryLine</em> methods.</p>
<p>The GUI project introduces the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/LorumIpsumStory.cs" target="_blank">LorumIpsumStory</a> class which demonstrates just how little code it takes to implement a (simple) story. Changing the Program’s Main method by creating an instance of <em>LorumIpsumStory</em>, a different story is generated much like the one shown in the snapshot below.</p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2012/11/04-Lorum-Ipsum-Story.png"><img class="alignnone size-full wp-image-1876" src="http://labs.thesedays.com/wp-content/uploads/2012/11/04-Lorum-Ipsum-Story.png" alt="" width="542" height="274" /></a></p>
<p><strong>Factory</strong></p>
<p>Following the <a title="Single responsibility principle" href="http://en.wikipedia.org/wiki/Single_responsibility_principle" target="_blank">single responsibility principle</a> had me refactor the application on several occasions and most violations against this principle seemed to occur in the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Polymorphism/MarketStory.cs" target="_blank">MarketStory</a> class as it just had way too many responsibilities. One of the things I ended up abstracting out is the instantiation of the <em>market</em> object which takes place in the <em>Initialize</em> method.</p>
<p>The <a title="Abstract factory pattern" href="http://en.wikipedia.org/wiki/Abstract_factory_pattern" target="_blank">factory pattern</a> encourages moving the implementation required for <a title="Objects" href="http://en.wikipedia.org/wiki/Object_(computer_science)" target="_blank">object instantiation</a> into a separate class as this process can introduce extra dependencies. The <em>CreateMarket</em> method of the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Inheritance/RandomMarketFactory.cs" target="_blank">RandomMarketFactory</a> shows that instantiating a market object involves fetching data from a repository and adhering to a list of creational settings. Having this implementation and its dependencies removed from the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Polymorphism/MarketStory.cs" target="_blank">MarketStory</a> class into a factory class was just the next logical step in the refactoring process.</p>
<p><strong>Factory method </strong></p>
<p>Instead of introducing a factory class, another way of dealing with object instantiation is by moving this responsibility to the class itself. Instances of the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Model/StorySettings.cs" target="_blank">StorySettings</a> class for example are created by passing several values into its constructor.</p>
<p>If you would like to create an instance of <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Model/StorySettings.cs" target="_blank">StorySettings</a> with values that are stored within a configuration file for example you would need to read the file, fetch the values and then instantiate an object with these values. To ease this process the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Model/StorySettings.cs" target="_blank">StorySettings</a> class provides a <a title="Factory method pattern" href="http://en.wikipedia.org/wiki/Factory_method_pattern" target="_blank">factory method</a> <em>FromConfiguration</em> that will instantly instantiate an object with values read from a configuration file.</p>
<p>Note that this practice should be used with caution as it may result in dependencies that are hard to overcome, for example the dependency between <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Model/StorySettings.cs" target="_blank">StorySettings</a> and the <a title="Configuration manager class" href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx" target="_blank">.NET configuration manager</a> as well as any dependencies to the instantiated object itself.</p>
<p><strong>Dependency injection</strong></p>
<p>Having dependencies that are needed for object instantiation moved into a factory class is beneficial, but it also introduces a new dependency. For the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Polymorphism/MarketStory.cs" target="_blank">MarketStory</a> to be functional it now requires an instance that implements <span style="text-decoration: underline"><a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Inheritance/MarketFactory.cs" target="_blank">MarketFactory</a></span>. As this dependency cannot be removed the next best thing one can do is to be very explicit about it and have the dependency “injected” either via its constructor or via a property. I prefer using constructor injection over property injection because I find it to be more visible.</p>
<p>This practice is commonly known as <span style="text-decoration: underline"><a title="Dependency injection pattern" href="http://en.wikipedia.org/wiki/Dependency_injection" target="_blank">dependency injection</a></span> and is often used in combination with <a title="Inversion of control" href="http://en.wikipedia.org/wiki/Inversion_of_control" target="_blank">inversion of control</a> which provides additional means to implement the actual injection at runtime (i.e. through an <a title="IoC container discussion" href="http://stackoverflow.com/questions/871405/why-do-i-need-an-ioc-container-as-opposed-to-straightforward-di-code" target="_blank">IoC container</a> and/or via a <a title="Service locator pattern" href="http://en.wikipedia.org/wiki/Service_locator_pattern" target="_blank">service locator</a>).</p>
<p><strong>Strategy</strong></p>
<p>You may have also noticed that the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Inheritance/MarketFactory.cs" target="_blank">MarketFactory</a> class that is passed to the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Polymorphism/MarketStory.cs" target="_blank">MarketStory</a> via its constructor is an abstract base class. This construct (as well as using a non-abstract class that can be inherited or an interface for that matter) allows for passing in different concrete implementations and is also referred to as the <a title="Strategy pattern" href="http://en.wikipedia.org/wiki/Strategy_pattern" target="_blank">strategy pattern</a> which is often used throughout this demo.</p>
<p>As mentioned earlier one concrete implementation of the factory can be found in the Marketplace library: the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Inheritance/RandomMarketFactory.cs" target="_blank">RandomMarketFactory</a> class. This class implements the market creation process by fetching a random market object and some random person objects from a data repository. While doing so it also adheres to a list of <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/ConcreteClasses/MarketFactorySettings.cs" target="_blank">MarketFactorySettings</a> that indicate the exact amount of people to fetch.</p>
<p>The <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/FixedMarketFactory.cs" target="_blank">FixedMarketFactory</a> class was introduced by the GUI project and provides a slightly different implementation by fetching the first market and the first person objects from the data repository.</p>
<p><strong>Repository</strong></p>
<p>The <a title="Repository pattern" href="http://msdn.microsoft.com/en-us/library/ff649690.aspx" target="_blank">repository pattern</a> recommends using a repository class which mediates between a data store and the middle layer. The repository provides an interface which allows the data store to be queried against and it will return middle layer entities rather than raw data sets. Whether you are using a <a title="Data access object" href="http://en.wikipedia.org/wiki/Data_access_object" target="_blank">DAO</a> implementation with <a title="ADO.NET" href="http://en.wikipedia.org/wiki/ADO.NET" target="_blank">ADO.NET</a>, a micro framework like <a title="Massive SFD" href="https://github.com/robconery/massive" target="_blank">Massive</a> or any other <a title="ORM" href="http://en.wikipedia.org/wiki/Object-relational_mapping" target="_blank">ORM</a> for that matter, it is always a good practice to encapsulate this implementation.</p>
<p>I find this approach to be very elegant and in combination with <a title="Inversion of control" href="http://en.wikipedia.org/wiki/Inversion_of_control" target="_blank">inversion of control</a> it completely removes any of the dependencies between middle and data layer. If you open up the demo in Visual Studio for example, you will notice that the Marketplace project has no references to the Data project.</p>
<p>Another big advantage is that it really improves testability of the middle layer, especially for <a title="Unit testing" href="http://en.wikipedia.org/wiki/Unit_testing" target="_blank">unit testing</a>. The <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/ConcreteClasses/FakeDataRepository.cs" target="_blank">FakeDataRepository</a> demonstrates this by implementing the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Interfaces/IMarketDataRepository.cs" target="_blank">IMarketDataRepository</a> and by returning fake data. Although I did not create any unit tests for this demo, the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Inheritance/RandomMarketFactory.cs" target="_blank">RandomMarketFactory</a> had been working with fake data all along (notice the <a title="Discussion on poor man's IoC" href="http://lostechies.com/chadmyers/2009/07/14/just-say-no-to-poor-man-s-dependency-injection/" target="_blank">poor man’s IoC</a> in its parameterless constructor, newing up a <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/ConcreteClasses/FakeDataRepository.cs" target="_blank">FakeDataRepository</a> by default if none was provided).</p>
<p>In fact the demo app does not even implement a data layer at all. The GUI project has a reference to the Data project and it introduces a <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/MarketDataSql.cs" target="_blank">MarketDataSql</a> class representing a repository that allows querying against a SQL database (notice how it wraps an instance of <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Data/SqlDbProvider.cs" target="_blank">SqlDbProvider</a> which lives in the data layer).</p>
<p>The <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Data/SqlDbProvider.cs" target="_blank">SqlDbProvider</a> has not been implemented, so if you would go back to the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Program.cs" target="_blank">Program’s Main method</a> and have a story created using an instance of <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/MarketDataSql.cs" target="_blank">MarketDataSql</a>, you should end up with a <a href="http://msdn.microsoft.com/en-us/library/system.notimplementedexception.aspx" target="_blank">not implemented exception</a> being thrown.</p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2012/11/05-SqlDbProvider-NotImplementedException.png"><img class="alignnone size-full wp-image-1877" src="http://labs.thesedays.com/wp-content/uploads/2012/11/05-SqlDbProvider-NotImplementedException.png" alt="" width="579" height="320" /></a></p>
<p><strong>Singleton</strong></p>
<p>If you look at the (non-)implementation of the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Data/SqlDbProvider.cs" target="_blank">SqlDbProvider</a> class you should recognize the <a title="Singleton pattern" href="http://en.wikipedia.org/wiki/Singleton_pattern" target="_blank">singleton pattern</a> being used. I realize that the singleton is a much criticized pattern (and often righteously so) as it can introduce dependencies that are difficult to overcome (spaghetti code) a.k.a. an <a title="Anti-pattern" href="http://en.wikipedia.org/wiki/Anti-pattern" target="_blank">anti-pattern</a>.</p>
<p>It does have its advantages however, and I would like to stress out that a singleton is an excellent strategy for simple caching purposes and it can also reduce the resource costs associated with instantiating very large objects, like for example the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Data/SqlDbProvider.cs" target="_blank">SqlDbProvider</a>. <a title="Data access object" href="http://en.wikipedia.org/wiki/Data_access_object" target="_blank">Data access objects</a> and classes implementing the <a title="Provider model" href="http://en.wikipedia.org/wiki/Provider_model" target="_blank">provider model</a> tend to grow large and if the application were to be extremely database-driven instances would have to be newed up very often.</p>
<p>Also worth mentioning is that in this case the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Data/SqlDbProvider.cs" target="_blank">SqlDbProvider</a> is wrapped by the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/MarketDataSql.cs" target="_blank">MarketDataSql</a> repository class which should reduce the amount of dependencies and even if this repository were to be newed up in several locations one could surely just introduce a factory class that ensures the dependency is isolated.</p>
<p><strong>Decorator</strong></p>
<p>The entire purpose of this demo is to demonstrate how a class library or a framework can be extended by introducing new classes. The <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/MarketStoryWithGreetings.cs" target="_blank">MarketStoryWithGreetings</a> class demonstrates this by inheriting most of its behavior from <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Polymorphism/MarketStory.cs" target="_blank">MarketStory</a> and by adding new functionality in the template method <em>RunStoryLine</em>. The new functionality in this particular class will have people greeting each other randomly as shown in the output window below.</p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2012/11/11-Market-story-with-greetings.png"><img class="alignnone size-full wp-image-1900" src="http://labs.thesedays.com/wp-content/uploads/2012/11/11-Market-story-with-greetings.png" alt="" width="542" height="274" /></a></p>
<p>Although in most cases inheritance fits this job perfectly there are times where you want to mix up or combine extended functionality and you will see the number of specialized classes grow rapidly.</p>
<p>The <a title="Decorator pattern" href="http://en.wikipedia.org/wiki/Decorator_pattern" target="_blank">decorator pattern</a> takes care of this problem and encourages a different strategy for adding functionality to an existing class. The demo app demonstrates this by introducing the abstract class <span style="text-decoration: underline"><a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/MarketStoryDecorator.cs" target="_blank">MarketStoryDecorator</a></span> which basically wraps a <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Polymorphism/MarketStory.cs" target="_blank">MarketStory</a> object as the object being decorated while also providing the exact same interface by implementing the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Polymorphism/MarketStory.cs" target="_blank">MarketStory</a> and by delegating its behavior back to the decorated object. The decorator class serves as a base class for concrete decorations, of which implementations you can find in <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/MarketStoryWithReport.cs" target="_blank">MarketStoryWithReport</a> and <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/MarketStoryWithExtendedReport.cs" target="_blank">MarketStoryWithExtendedReport</a>.</p>
<p>In the snapshots below you can see how these two classes are instantiated as well as the output that is generated in the console window when the application launches (notice the reports at the end of story).</p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2012/11/06-Decorator-pattern-1.png"><img class="alignnone size-full wp-image-1878" src="http://labs.thesedays.com/wp-content/uploads/2012/11/06-Decorator-pattern-1.png" alt="" width="566" height="286" /></a></p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2012/11/07-Decorator-pattern-2.png"><img class="alignnone size-full wp-image-1879" src="http://labs.thesedays.com/wp-content/uploads/2012/11/07-Decorator-pattern-2.png" alt="" width="562" height="290" /></a></p>
<p>One drawback of this implementation is that the decorators require the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/Polymorphism/MarketStory.cs" target="_blank">MarketStory</a> being decorated to expose the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Model/Market.cs" target="_blank">Market</a> object it encapsulates as it is needed for the decorators to generate the reports. Then again this is just a small sacrifice if you consider the decorators allow us to extend functionality at runtime.</p>
<p>As for the fun part, now we can start combining these different implementations, for example if we combine the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/MarketStoryWithGreetings.cs" target="_blank">MarketStoryWithGreeting</a> with a <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/MarketStoryWithExtendedReport.cs" target="_blank">MarketStoryWithExtendedReport</a> the story will contain both greetings and an extended report, as shown in the snapshot below.</p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2012/11/08-Decorator-pattern-3.png"><img class="alignnone size-full wp-image-1880" src="http://labs.thesedays.com/wp-content/uploads/2012/11/08-Decorator-pattern-3.png" alt="" width="569" height="290" /></a></p>
<p><strong>A few more additions</strong></p>
<p>Although I pretty much covered all of the design patterns that are used throughout this demo there still are a few abstractions and extensions left unexplained.</p>
<p>For instance abstracting out the state broadcasting mechanism has introduced some complexity to the design and although purists may argue I do believe the implementation follows the <a title="Mediator pattern" href="http://en.wikipedia.org/wiki/Mediator_pattern" target="_blank">mediator pattern</a>.  Either way the most important takeaway is that the combination of <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/EventHandling/IStateEventSubscriber.cs" target="_blank">IStateEventSubscriber</a>, <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/EventHandling/IStateEventNotifier.cs" target="_blank">IStateNotifier</a> and the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/EventHandling/StateEventListener.cs" target="_blank">StateEventListener</a> implementation allow for future classes used within future stories to broadcast their state changes to the event listeners that were registered by the story.</p>
<p>An example of a new state event listener added in the GUI project is the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/FileEventListener.cs" target="_blank">FileEventListener</a> which will output the story to a text file if provided with a file path. An example is shown in the snapshot below.</p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2012/11/09-FileEventListener.png"><img class="alignnone size-full wp-image-1881" src="http://labs.thesedays.com/wp-content/uploads/2012/11/09-FileEventListener.png" alt="" width="545" height="276" /></a></p>
<p>As a final example I would like to mention the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/Patrols/PoliceOfficer.cs" target="_blank">PoliceOfficer</a> class which was added in the GUI project. It implements the behavior that is triggered by a story line and also overrides the behavior when a person is greeted. Since the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Marketplace/Concepts/ConcreteClasses/FakeDataRepository.cs" target="_blank">FakeDataRepository</a> does not provide fake data for police officers and nor does the <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/AppConfigMarketFactorySettings.cs" target="_blank">AppConfigMarketFactorySettings</a> provide a setting for the number of policemen to generate, two additional classes have been introduced to provide this functionality: <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/Patrols/FakeDataRepositoryPatrols.cs" target="_blank">FakeDataRepositoryPatrols</a> and <a href="https://github.com/TheAmph/DesignPatternDemo/blob/master/Program/Extensibility/Patrols/MarketFactorySettingsPatrols.cs" target="_blank">MarketFactorySettingsPatrols</a>. Let’s update the program and launch it one more time.</p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2012/11/10-Police-officer-patrol.png"><img class="alignnone size-full wp-image-1882" src="http://labs.thesedays.com/wp-content/uploads/2012/11/10-Police-officer-patrol.png" alt="" width="536" height="286" /></a></p>
<p><strong>Conclusion</strong></p>
<p>A well-designed OO application allows for developers maintaining the application to add or extend functionality without having to change its source code or recompile. And although you cannot guard against all future changes, a SOLID design and the proper use of design patterns will result in a more flexible and maintainable application or framework.</p>
<p>I hope both this demo and blog post contribute in helping others better understand some of the most commonly used design patterns, the problems they solve or why these problems need to be addressed in the first place.</p>
<p>Feel free to use the demo application for you own needs, or you can just fork it on <a href="https://github.com/TheAmph/DesignPatternDemo" target="_blank">github</a> if you would like to extend it or contribute. Cheers!</p>
<img src="http://feeds.feedburner.com/~r/TheseDaysLabs/~4/O-WqCnQD6lI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://labs.thesedays.com/blog/2012/11/12/a-demo-application-covering-oo-design-patterns/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://labs.thesedays.com/blog/2012/11/12/a-demo-application-covering-oo-design-patterns/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=a-demo-application-covering-oo-design-patterns</feedburner:origLink></item>
		<item>
		<title>List Categories Widget</title>
		<link>http://feedproxy.google.com/~r/TheseDaysLabs/~3/nu_dBxmr-Zg/</link>
		<comments>http://labs.thesedays.com/blog/2012/11/08/list-categories-widget/#comments</comments>
		<pubDate>Thu, 08 Nov 2012 13:45:09 +0000</pubDate>
		<dc:creator>Pieter Pelgrims</dc:creator>
				<category><![CDATA[Open source]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://labs.thesedays.com/?p=1841</guid>
		<description><![CDATA[Introduction This post deals about a WordPress plugin that improves the categories widget that comes with WordPress. As it goes with indecisive clients and lazy developers, I wrote a WordPress widget that (partially) encapsulates WP&#8217;s wp_list_categories function. I only included the parameters that were needed for the project, but you could easily add more to [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>This post deals about a WordPress plugin that improves the categories widget that comes with WordPress.</p>
<p>As it goes with indecisive clients and lazy developers, I wrote a WordPress widget that (partially) encapsulates WP&#8217;s <a href="http://codex.wordpress.org/Template_Tags/wp_list_categories" target="_blank">wp_list_categories</a> function. I only included the parameters that were needed for the project, but you could easily add more to the mix. I advice you to go through the description of the function as to avoid unexpected behaviour of the widget.</p>
<p>If changes are needed to the categories, you can make them easily through the widget interface in the back end. As the IDs of categories tend to be different over time on staging and production sites, this widget proved to be extremely useful, especially if a third party is involved to take care of writing blogposts, not to mention the role of an indecisive client. The standard <em>categories</em> widget was a bit too basic.</p>
<h2>Let&#8217;s dive straight into it!</h2>
<pre class="brush: php; first-line: 11; highlight: [11,18]; html-script: true; title: ; notranslate">namespace TheseDays;

// register the widget
add_action( 'widgets_init', function(){
     return register_widget( 'TheseDays\listCategories_Widget' );
});

class listCategories_Widget extends \WP_Widget
{</pre>
<p>To avoid collision with other widgets with the same name I used the <em>TheseDays</em> namespace. Go through the <a href="http://codex.wordpress.org/Widgets_API#Example_PHP_5.3" target="_blank">Widget API</a> fast, so you know what I&#8217;m talking about. Please note the backslash in front of the class we&#8217;re extending, you&#8217;ll get an error if you forget this because PHP (5.3 and up) will try to extend the new class from the WP_Widget class within the same namespace, more info about namespaces in the <a href="http://php.net/manual/en/language.namespaces.php" target="_blank">docs</a>.</p>
<p>&#8216;Child of&#8217; accepts only one parameter, inserting multiple will result in displaying every category (except those in the &#8216;exclude&#8217; box). The &#8216;view all&#8217; link only shows up when this parameter is present.</p>
<h2>Slugs and Regular Expression</h2>
<pre class="brush: php; first-line: 176; highlight: [176]; html-script: true; title: ; notranslate">			$category = get_category_by_slug($single);
			$categoryId = $category-&gt;term_id;
			// (integer if 0, string if ID)</pre>
<p>The widget expects input for &#8216;include&#8217; and &#8216;exclude&#8217; parameters to be a seperated list of category<strong>slugs</strong>. It gets rid of nonexisting slugs and unwanted characters. These unwanted characters and spaces serve as listsepartors but will be replaced by comma&#8217;s. This is exactly the reason to use slugs instead of the names, names can contain ampersands, spaces and what not.</p>
<pre class="brush: php; first-line: 166; highlight: [167]; html-script: true; title: ; notranslate">// source array
		preg_match_all('/([\w\-]+)/i', $string, $categories);
		$categories = $categories[0];</pre>
<p>If you wish to change this to allow more or other characters, please change the regular expression. If you wish to add unicode to the range of allowed characters, please mind <a href="http://php.net/manual/en/reference.pcre.pattern.modifiers.php" target="_blank">PCRE modifiers</a>, you should be good by adding &#8216;u&#8217; behind the &#8216;i&#8217;.</p>
<h2>Conclusion</h2>
<p>Aside from those the plugin is pretty basic and straight forward. Tell us what you think about it in the comments!</p>
<p>Here&#8217;s the full code:</p>
<pre class="brush: php; html-script: true; title: ; wrap-lines: true; notranslate">
&lt;?php
/**
 * Plugin Name: listCategories Widget
 * Plugin URI: http://labs.thesedays.com/blog/2012/11/08/list-categories-widget/
 * Description: A widget that encapsulates wp_list_categories.
 * Version: 1.2
 * Author: Pieter Pelgrims &lt;hello@pieterpelgrims.com&gt;
 * Author URI: http://www.pieterpelgrims.com/
 *
 */
namespace TheseDays;

// register the widget
add_action( 'widgets_init', function(){
     return register_widget( 'TheseDays\listCategories_Widget' );
});

class listCategories_Widget extends \WP_Widget
{
	 // Register widget
	 public function __construct()
	 {
		parent::__construct(
	 		'listcategories_widget', // Base ID
			'List Categories', // Name
			array( 'description' =&gt; __( 'A widget that allows you to easily list categories. This widget encapsulates wp_list_categories.', 'listcategories_widget' ), ) // Args
		);
	}

	// Front end output of our widget
	public function widget( $args, $instance )
	{
		extract( $args );

		// Our variables from the widget settings.
		$title		= apply_filters('widget_title', $instance['title'] );		

		$cat		= get_category_by_slug($instance['cat']);
		$cat		= $cat-&gt;term_id;

		$view		= isset( $instance['view'] ) ? $instance['view'] : FALSE;
		$count		= isset( $instance['count']) ? $instance['count']: FALSE;
		$orderby	= $instance['orderby'];
		$sort		= $instance['sort'];

		$exclude = $this-&gt;nameToId($instance['exclude']);
		$include = $this-&gt;nameToId($instance['include']);

		$cat_args = array(
			'title_li'     =&gt; __( '' ),
  			'orderby'      =&gt; $orderby,
  			'order'        =&gt; $sort,
  			'show_count'   =&gt; $count,
 			'child_of'     =&gt; $cat,
 			'exclude'	   =&gt; $exclude,
 			'include'	   =&gt; $include
		);

		// Before widget (defined by themes).
		echo $before_widget;

		// Display the widget title if one was input (before and after defined by themes).
		if ( $title )
			echo $before_title . $title . $after_title;

		echo '&lt;ul class=&quot;listcategories_widget&quot;&gt;';

		wp_list_categories( $cat_args );

		if( $instance['view'] &amp;&amp; !empty($instance['cat']))
		{
			echo &quot;&lt;li class=\&quot;view_more\&quot;&gt;&lt;a href=\&quot;?category_name=&quot;.$instance['cat'].&quot;\&quot;&gt;View all&lt;/a&gt;&lt;/li&gt;&quot;;
		}

		echo &quot;&lt;/ul&gt;&quot;;

		// After widget (defined by themes).
		echo $after_widget;
	}

	// Update the widget settings.
	public function update( $new_instance, $old_instance )
	{
		$instance			= $old_instance;
		$instance['title']	= strip_tags( $new_instance['title'] );
		$instance['cat']	= strip_tags( $new_instance['cat'] );
		$instance['view']	= $new_instance['view'];
		$instance['count']	= $new_instance['count'];
		$instance['orderby']= $new_instance['orderby'];
		$instance['sort']	= $new_instance['sort'];

		$this-&gt;nameToId($new_instance['exclude']);
		$instance['exclude'] = $new_instance['exclude'];

		$this-&gt;nameToId($new_instance['include']);
		$instance['include'] = $new_instance['include'];

		return $instance;
	}

	// Backend of the widget
	public function form( $instance )
	{
		// Set up some default widget settings.
		$defaults = array( 'title' =&gt; __('Categories', 'listcategories_widget'), 'view' =&gt; true, 'count' =&gt; true, 'orderby' =&gt; 'count', 'sort' =&gt; 'ASC'  );
		$instance = wp_parse_args( (array) $instance, $defaults ); ?&gt;

		&lt;p&gt;
			&lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;&quot;&gt;&lt;?php _e('Title:', 'hybrid'); ?&gt;&lt;/label&gt;
			&lt;input id=&quot;&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;&quot; name=&quot;&lt;?php echo $this-&gt;get_field_name( 'title' ); ?&gt;&quot; value=&quot;&lt;?php echo $instance['title']; ?&gt;&quot; class=&quot;widefat&quot;/&gt;
		&lt;/p&gt;

		&lt;p&gt;
			&lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id( 'cat' ); ?&gt;&quot;&gt;&lt;?php _e('Child of: (leave empty for all)', 'listcategories_widget'); ?&gt;&lt;/label&gt;
			&lt;input id=&quot;&lt;?php echo $this-&gt;get_field_id( 'cat' ); ?&gt;&quot; name=&quot;&lt;?php echo $this-&gt;get_field_name( 'cat' ); ?&gt;&quot; value=&quot;&lt;?php echo $instance['cat']; ?&gt;&quot; class=&quot;widefat&quot;/&gt;
		&lt;/p&gt;

		&lt;p&gt;
			&lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id( 'exclude' ); ?&gt;&quot;&gt;&lt;?php _e('Excluding:', 'listcategories_widget'); ?&gt;&lt;/label&gt;
			&lt;input id=&quot;&lt;?php echo $this-&gt;get_field_id( 'exclude' ); ?&gt;&quot; name=&quot;&lt;?php echo $this-&gt;get_field_name( 'exclude' ); ?&gt;&quot; value=&quot;&lt;?php echo $instance['exclude']; ?&gt;&quot; class=&quot;widefat&quot;/&gt;
		&lt;/p&gt;

		&lt;p&gt;
			&lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id( 'include' ); ?&gt;&quot;&gt;&lt;?php _e('Including:', 'listcategories_widget'); ?&gt;&lt;/label&gt;
			&lt;input id=&quot;&lt;?php echo $this-&gt;get_field_id( 'include' ); ?&gt;&quot; name=&quot;&lt;?php echo $this-&gt;get_field_name( 'include' ); ?&gt;&quot; value=&quot;&lt;?php echo $instance['include']; ?&gt;&quot; class=&quot;widefat&quot;/&gt;
		&lt;/p&gt;

		&lt;p&gt;
			&lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id( 'orderby' ); ?&gt;&quot;&gt;&lt;?php _e('Order By:', 'listcategories_widget'); ?&gt;&lt;/label&gt;
			&lt;select id=&quot;&lt;?php echo $this-&gt;get_field_id( 'orderby' ); ?&gt;&quot; name=&quot;&lt;?php echo $this-&gt;get_field_name( 'orderby' ); ?&gt;&quot; class=&quot;widefat&quot; style=&quot;width:100%;&quot;&gt;
				&lt;option &lt;?php if ( 'ID' == $instance['orderby'] ) echo 'selected=&quot;selected&quot;'; ?&gt; value=&quot;ID&quot;&gt;&lt;?php _e('ID','listcategories_widget'); ?&gt;&lt;/option&gt;
				&lt;option &lt;?php if ( 'name' == $instance['orderby'] ) echo 'selected=&quot;selected&quot;'; ?&gt; value=&quot;name&quot;&gt;&lt;?php _e('Name','listcategories_widget'); ?&gt;&lt;/option&gt;
				&lt;option &lt;?php if ( 'slug' == $instance['orderby'] ) echo 'selected=&quot;selected&quot;'; ?&gt; value=&quot;slug&quot;&gt;&lt;?php _e('Slug','listcategories_widget'); ?&gt;&lt;/option&gt;
				&lt;option &lt;?php if ( 'count' == $instance['orderby'] ) echo 'selected=&quot;selected&quot;'; ?&gt; value=&quot;count&quot;&gt;&lt;?php _e('Count','listcategories_widget'); ?&gt;&lt;/option&gt;
				&lt;option &lt;?php if ( 'term_group' == $instance['orderby'] ) echo 'selected=&quot;selected&quot;'; ?&gt; value=&quot;term_group&quot;&gt;&lt;?php _e('Term Group','listcategories_widget'); ?&gt;&lt;/option&gt;
			&lt;/select&gt;
		&lt;/p&gt;
		&lt;p&gt;
			&lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id( 'sort' ); ?&gt;&quot;&gt;&lt;?php _e('Sort:', 'listcategories_widget'); ?&gt;&lt;/label&gt;
			&lt;select id=&quot;&lt;?php echo $this-&gt;get_field_id( 'sort' ); ?&gt;&quot; name=&quot;&lt;?php echo $this-&gt;get_field_name( 'sort' ); ?&gt;&quot; class=&quot;widefat&quot; style=&quot;width:100%;&quot;&gt;
				&lt;option &lt;?php if ( 'ASC'  == $instance['sort'] ) echo 'selected=&quot;selected&quot;'; ?&gt; value=&quot;ASC&quot; &gt;&lt;?php  _e('Ascending','listcategories_widget'); ?&gt;&lt;/option&gt;
				&lt;option &lt;?php if ( 'DESC' == $instance['sort'] ) echo 'selected=&quot;selected&quot;'; ?&gt; value=&quot;DESC&quot;&gt;&lt;?php _e('Descending','listcategories_widget'); ?&gt;&lt;/option&gt;
			&lt;/select&gt;
		&lt;/p&gt;

		&lt;p&gt;
			&lt;input class=&quot;checkbox&quot; type=&quot;checkbox&quot; &lt;?php checked( $instance['view'], 'on' ); ?&gt; id=&quot;&lt;?php echo $this-&gt;get_field_id( 'view' ); ?&gt;&quot; name=&quot;&lt;?php echo $this-&gt;get_field_name( 'view' ); ?&gt;&quot; /&gt;
			&lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id( 'view' ); ?&gt;&quot;&gt;&lt;?php _e('Show &quot;View all&quot; link', 'listcategories_widget'); ?&gt;&lt;/label&gt;
		&lt;/p&gt;

		&lt;p&gt;
			&lt;input class=&quot;checkbox&quot; type=&quot;checkbox&quot; &lt;?php checked( $instance['count'], 'on' ); ?&gt; id=&quot;&lt;?php echo $this-&gt;get_field_id( 'count' ); ?&gt;&quot; name=&quot;&lt;?php echo $this-&gt;get_field_name( 'count' ); ?&gt;&quot; /&gt;
			&lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id( 'count' ); ?&gt;&quot;&gt;&lt;?php _e('Show post counts', 'listcategories_widget'); ?&gt;&lt;/label&gt;
		&lt;/p&gt;

	&lt;?php
	}

	// Helper function
	// @var		string	comma seperated category names, removes non-existing
	// @return	string	comma seperated category ID's
	public function nameToId(&amp;$string)
	{
		if(empty($string)) return NULL;

		// source array
		preg_match_all('/([\w\-]+)/i', $string, $categories);
		$categories = $categories[0];

		// target array
		$listOfIds	= array();

		foreach($categories as $k =&gt; $single)
		{
			// 0, if failure and ID of category on success.
			$category = get_category_by_slug($single);
			$categoryId = $category-&gt;term_id;
			// (integer if 0, string if ID)
		    if($categoryId !== 0)
		    {
		    	// Category actually exists, add it to target array
		    	$listOfIds[] = $categoryId;
		    }
		    else
		    {
		    	// Category doesn't exist, remove from source
			    unset($categories[$k]);
		    }
		}
		$string = implode(', ', $categories);
		return implode(',', $listOfIds);
	}

}

?&gt;
</pre>
<img src="http://feeds.feedburner.com/~r/TheseDaysLabs/~4/nu_dBxmr-Zg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://labs.thesedays.com/blog/2012/11/08/list-categories-widget/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://labs.thesedays.com/blog/2012/11/08/list-categories-widget/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=list-categories-widget</feedburner:origLink></item>
		<item>
		<title>Streaming Wowza content and Load Balancers</title>
		<link>http://feedproxy.google.com/~r/TheseDaysLabs/~3/lOY0dvYnjHU/</link>
		<comments>http://labs.thesedays.com/blog/2012/07/09/streaming-wowza-content-and-load-balancers/#comments</comments>
		<pubDate>Mon, 09 Jul 2012 15:04:30 +0000</pubDate>
		<dc:creator>Pieter Helsen</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>

		<guid isPermaLink="false">http://labs.thesedays.com/?p=1832</guid>
		<description><![CDATA[For a recent campaign we had to integrate a live video stream into a banner. Therefore the following code will focus mainly on AS2, but the code is easily portable to AS3. The video was streamed using Wowza Media Server (though Flash Media Server works in much the same way) and the servers itself were [...]]]></description>
			<content:encoded><![CDATA[<p>For a recent campaign we had to integrate a live video stream into a banner. Therefore the following code will focus mainly on AS2, but the code is easily portable to AS3.</p>
<p>The video was streamed using Wowza Media Server (though Flash Media Server works in much the same way) and the servers itself were behind a load balancer.</p>
<p>First, we tried using the FLVPlayback component, but the component was opening multiple connections, where only one connection was really required and it didn&#8217;t handle disconnects well. That&#8217;s why we opted for the good old NetConnection/NetStream approach.</p>
<p>However, because the content was behind  a load balancer, we got back a &#8216;NetConnection.Connect.Rejected&#8217; status code. The reason why is because the load balancer will interpret the request and then sends back a redirection link to the server it wants you to connect to.</p>
<p>We used the following code to fetch said redirection link (remember, this example uses AS2 syntax):</p>
<pre class="brush: plain; title: ; notranslate">

// define the variables to hold the NetConnection and NetStream classes.
var WowzaConnection:NetConnection = new NetConnection();
var WowzaStream:NetStream;

// initiate the connection and add an event handler
WowzaConnection.onStatus = statusHandler;
WowzaConnection.connect(&quot;rtmp://your-streamer-url/&quot;);

// this is just a quick helper function to easily close the connection
function closeConnection(){
 WowzaConnection.close();
 WowzaStream.close();
}

function cuePointHandler(infoObject:Object){
 // insert cue point processing here
 // or leave blank if you don't need to process cue points
 // be sure to add this handler however, since Flash will throw an error if it isn't available
}

function metaDataHandler(infoObject:Object){
 // insert metadata processing here
 // or leave blank if you don't need to process metadata
 // be sure to add this handler however, since Flash will throw an error if it isn't available
}

// definition of the status event handler
function statusHandler(infoObj:Object){
 trace(&quot;onStatus: &quot;+infoObj.code);
 switch(infoObj.code){
  // The connection was established. Initiate the stream and add event handlers.
  case &quot;NetConnection.Connect.Success&quot;:
  WowzaStream = new NetStream(WowzaConnection);
  WowzaStream.onCuePoint = cuePointHandler;
  WowzaStream.onMetaData = metaDataHandler;
  WowzaStream.onStatus = statusHandler;
  WowzaStream.play(&quot;streamname&quot;);

  // add the stream to a Video object placed on the stage, with it's instance name set to 'video'
  video.attachVideo(WowzaStream);
  break;
 case &quot;NetConnection.Connect.Rejected&quot;:
  // here's the reject... The load balancer rejects the connection, but passes a redirect URL
  // back through the infoObj.ex.redirect parameter.
  if (infoObj.ex.code == 302) {
   // connect to the new streamer URL after a timeout of 100ms
   // the timeout isn't necessary, but is implemented to prevent
   // unwanted behaviour
   setTimeout(function(){
    WowzaConnection.connect(infoObj.ex.redirect);
   }, 100);

 }
 break;

 }
}
</pre>
<p>And that&#8217;s about it really. The NetConnection will try to connect to the streamer URL, but will disconnect once the server throws the &#8216;NetConnection.Connect.Rejected&#8217; status. After that, it will reconnect to the redirect URL and the connection should throw a &#8216;NetConnection.Connect.Success&#8217; status.</pre>
<img src="http://feeds.feedburner.com/~r/TheseDaysLabs/~4/lOY0dvYnjHU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://labs.thesedays.com/blog/2012/07/09/streaming-wowza-content-and-load-balancers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://labs.thesedays.com/blog/2012/07/09/streaming-wowza-content-and-load-balancers/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=streaming-wowza-content-and-load-balancers</feedburner:origLink></item>
		<item>
		<title>It’s agency life Jim, but not as you know it.</title>
		<link>http://feedproxy.google.com/~r/TheseDaysLabs/~3/J_PlheW_IkU/</link>
		<comments>http://labs.thesedays.com/blog/2012/03/12/its-agency-life-jim-but-not-as-you-know-it/#comments</comments>
		<pubDate>Mon, 12 Mar 2012 14:43:04 +0000</pubDate>
		<dc:creator>Sam Serrien</dc:creator>
				<category><![CDATA[Jobs]]></category>
		<category><![CDATA[These Days]]></category>
		<category><![CDATA[thesdays]]></category>

		<guid isPermaLink="false">http://labs.thesedays.com/?p=1816</guid>
		<description><![CDATA[Check our new microsite http://playground.thesedays.com to experience agency life at These Days. Of course we don&#8217;t do this without a reason &#8230; We need loads of new geeks so if you want to come work in this environment, check out the job pages! (You can find the jobs inbetween the life tiles on playground or [...]]]></description>
			<content:encoded><![CDATA[<p>Check our new microsite <a href="http://playground.thesedays.com">http://playground.thesedays.com</a> to experience agency life at These Days. Of course we don&#8217;t do this without a reason &#8230; We need loads of new geeks so if you want to come work in this environment, check out the <a href="http://labs.thesedays.com/jobs/">job</a> pages! (You can find the jobs inbetween the life tiles on <a href="http://playground.thesedays.com">playground</a> or directly via <a href="http://labs.thesedays.com/jobs/">http://labs.thesedays.com/jobs/</a>)</p>
<p><strong>The job descriptions are boring as hell though ;-)</strong></p>
<p><img src="http://labs.thesedays.com/wp-content/uploads/2012/03/pokerface1.png" alt="" width="300" height="266" class="alignnone size-full wp-image-1823" /></p>
<img src="http://feeds.feedburner.com/~r/TheseDaysLabs/~4/J_PlheW_IkU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://labs.thesedays.com/blog/2012/03/12/its-agency-life-jim-but-not-as-you-know-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://labs.thesedays.com/blog/2012/03/12/its-agency-life-jim-but-not-as-you-know-it/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=its-agency-life-jim-but-not-as-you-know-it</feedburner:origLink></item>
		<item>
		<title>SUD – A bookmark plugin for responsive sites</title>
		<link>http://feedproxy.google.com/~r/TheseDaysLabs/~3/yOPpH5UgYnw/</link>
		<comments>http://labs.thesedays.com/blog/2012/01/31/sud-a-bookmark-plugin-for-responsive-sites/#comments</comments>
		<pubDate>Tue, 31 Jan 2012 13:36:55 +0000</pubDate>
		<dc:creator>Bram Verdyck</dc:creator>
				<category><![CDATA[Mobile development]]></category>
		<category><![CDATA[Web development]]></category>

		<guid isPermaLink="false">http://labs.thesedays.com/?p=1726</guid>
		<description><![CDATA[Responsive websites are getting more and more mainstream these days. They can be a pain in the ass for bugfixing, especially when clients are mailing bugs/changes without nothing more then a screenshot and some comments. It&#8217;s us, the developers, who have to figure out where and on which layout/browser/os these bugs manifest themselves. This can [...]]]></description>
			<content:encoded><![CDATA[<p>Responsive websites are getting more and more mainstream these days. They can be a pain in the ass for bugfixing, especially when clients are mailing bugs/changes without nothing more then a screenshot and some comments.</p>
<p>It&#8217;s us, the developers, who have to figure out where and on which layout/browser/os these bugs manifest themselves. This can be a very frustrating &amp; time-consuming task, so that&#8217;s why we made ourselves a little helper.</p>
<p>Meet: <strong>SUD</strong>. It&#8217;s a smart little bookmark widget. Some javascript code that creates a small overlayer head-up display (HUD) with a bunch of info.</p>
<p>It gives you:<br />
- A number representing the current &#8220;layout&#8221; in your responsive site (we like to number our different layouts)<br />
- The current active media query<br />
- All necessary browser info<br />
- All OS info needed</p>
<p>Here is a little screenshot:</p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2012/01/sud_boston_globe.png"><img class="alignnone size-medium wp-image-1751" src="http://labs.thesedays.com/wp-content/uploads/2012/01/sud_boston_globe-300x57.png" alt="" width="300" height="57" /></a></p>
<p>SUD is still in BETA, it&#8217;s a work in progress. You can find it on <a title="SUD on github" href="https://www.github.com/thesedays/sud/" target="_blank">github</a> if you want to see how it works.<br />
Or simply start using it now by dragging <a href="javascript:(function(){s=document.createElement('script');s.type='text/javascript';s.src='https://thesedays.blob.core.windows.net/labs-thesedays-com/sud/td.plugin.sud.min.js?v='+parseInt(Math.random()*99999999);document.body.appendChild(s);})();">this link</a> to your bookmarks bar or by creating a new bookmark with this in the link field:</p>
<pre class="brush: jscript; title: ; notranslate">javascript:(function(){s=document.createElement('script');s.type='text/javascript';s.src='https://thesedays.blob.core.windows.net/labs-thesedays-com/sud/td.plugin.sud.min.js?v='+parseInt(Math.random()*99999999);document.body.appendChild(s);})();</pre>
<p>If you want the widget to run at page load, just include this script tag:</p>
<pre class="brush: jscript; title: ; notranslate">&lt;script type=&quot;text/javascript&quot; src=&quot;https://thesedays.blob.core.windows.net/labs-thesedays-com/sud/td.plugin.sud.min.js&quot;&gt;&lt;/script&gt;</pre>
<p>Feel free to check it out and give it a go. And make sure to let us know what you think of it!</p>
<img src="http://feeds.feedburner.com/~r/TheseDaysLabs/~4/yOPpH5UgYnw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://labs.thesedays.com/blog/2012/01/31/sud-a-bookmark-plugin-for-responsive-sites/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://labs.thesedays.com/blog/2012/01/31/sud-a-bookmark-plugin-for-responsive-sites/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=sud-a-bookmark-plugin-for-responsive-sites</feedburner:origLink></item>
		<item>
		<title>Creating a progress bar in ASP.NET using SignalR</title>
		<link>http://feedproxy.google.com/~r/TheseDaysLabs/~3/2scs8DvtKFY/</link>
		<comments>http://labs.thesedays.com/blog/2011/12/05/creating-a-progress-bar-in-asp-net-using-signalr/#comments</comments>
		<pubDate>Mon, 05 Dec 2011 13:26:37 +0000</pubDate>
		<dc:creator>Lennart Stoop</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[longpolling]]></category>
		<category><![CDATA[progress bar]]></category>
		<category><![CDATA[signalr]]></category>
		<category><![CDATA[websockets]]></category>

		<guid isPermaLink="false">http://labs.thesedays.com/?p=1683</guid>
		<description><![CDATA[Introducing SignalR Whenever you need to create an interactive widget on a website you often end up writing a lot of code in having the widget updated through asynchronous calls between client and server. Moreover in most cases the widget will pull for updates while it would be much more efficient in having the server [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introducing SignalR</strong></p>
<p>Whenever you need to create an interactive widget on a website you often end up writing a lot of code in having the widget updated through asynchronous calls between client and server. Moreover in most cases the widget will pull for updates while it would be much more efficient in having the server push updates to its clients. This is where <a href="https://github.com/SignalR/SignalR" target="_blank">SignalR</a> comes in: a signaling library for ASP.NET which does all the heavy lifting for you, making it dead easy to push data from server to client(s).</p>
<p>The best way to <a href="https://github.com/SignalR/SignalR/wiki/Getting-Started" target="_blank">get started with SignalR</a> is by looking at Hubs which are a higher level implementation of a persisted connection. Check out the<a href="https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs" target="_blank"> quick start example</a> and see how easy it is. Note that in order to <a href="https://github.com/SignalR/SignalR/wiki/Faq" target="_blank">support certain browsers</a> you will need to include json2.js in your application.</p>
<p><strong>Why create a progress bar using SignalR?</strong></p>
<p>In our production department we have several (web based) collaboration tools amongst which a deployment tool for .NET based websites. The tool allows front-end developers to work against a shared development environment (not having to run websites on their local machines) and deploy websites to a staging environment which is accessible to our clients for previewing and acceptance testing.</p>
<p>Since deploying larger websites can take up to several minutes we needed to provide the user with feedback, preferably by means of a progress bar. We also needed to make sure that during website deployment the deployment could not be reinitiated and finally we thought it would be really cool if we could prompt the progress bar to other (concurrent) users as well.</p>
<p>And although this could also be accomplished with Ajax/JSON, it is just so much easier using SignalR!</p>
<p>Let’s see this in action: the screenshots below represent 3 different browser windows showing 2 simultaneous deployments. When a user visits the deployment page of a website a progress bar is prompted if the website is currently being deployed. The overview page which lists all the websites is updated as well (a rotating progress loader is shown instead of the deploy button)</p>
<div id="attachment_1686" class="wp-caption alignnone" style="width: 597px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/12/01-Progress-bar-with-SignalR-Deploy-app-1.png"><img class="size-full wp-image-1686  " src="http://labs.thesedays.com/wp-content/uploads/2011/12/01-Progress-bar-with-SignalR-Deploy-app-1.png" alt="Deploying a first website" width="587" height="190" /></a><p class="wp-caption-text">Deploying a first website</p></div>
<div id="attachment_1687" class="wp-caption alignnone" style="width: 596px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/12/02-Progress-bar-with-SignalR-Deploy-app-2.png"><img class="size-full wp-image-1687  " src="http://labs.thesedays.com/wp-content/uploads/2011/12/02-Progress-bar-with-SignalR-Deploy-app-2.png" alt="Deploying a second website" width="586" height="204" /></a><p class="wp-caption-text">Deploying a second website</p></div>
<div id="attachment_1688" class="wp-caption alignnone" style="width: 596px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/12/03-Progress-bar-with-SignalR-Manage-app-overview.png"><img class="size-full wp-image-1688    " src="http://labs.thesedays.com/wp-content/uploads/2011/12/03-Progress-bar-with-SignalR-Manage-app-overview.png" alt="Overview which lists all websites and their deployment status" width="586" height="204" /></a><p class="wp-caption-text">Overview which lists all websites and their deployment status</p></div>
<p><strong>A look at the source code</strong></p>
<p>The deployment tool is an ASP.NET MVC 3 web application so installing SignalR is a breeze with <a href="http://nuget.org/List/Packages/SignalR" target="_blank">NuGet</a> and the first thing I did after installing the package was adding the progress bar to the view which initiates the deployment.</p>
<div id="attachment_1689" class="wp-caption alignnone" style="width: 581px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/12/04-Progress-bar-with-SignalR-Deployment-View.png"><img class="size-full wp-image-1689    " src="http://labs.thesedays.com/wp-content/uploads/2011/12/04-Progress-bar-with-SignalR-Deployment-View.png" alt="Client-side code in the Deployment view" width="571" height="373" /></a><p class="wp-caption-text">Client-side code in the Deployment view</p></div>
<p>In the head section I added references to the scripts required for SignalR and the <a href="http://docs.jquery.com/UI/Progressbar" target="_blank">JQuery UI progress bar</a> as well as some JS code which initializes the <a href="https://github.com/SignalR/SignalR/blob/master/SignalR/Hubs/Hub.cs" target="_blank">Hub</a> and handles the progress updates. Instead of having the form post back to the server, the submit button triggers a client side click event which will call a method on the hub (in this case <em>run</em>). Note that Jquery itself also needs referenced (in a shared layout).</p>
<p>That’s pretty much it when it comes to client side code and as you can see below the actual implementation of the hub is written in plain old C#</p>
<div id="attachment_1690" class="wp-caption alignnone" style="width: 570px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/12/05-Progress-bar-with-SignalR-Deploy-Manager.png"><img class="size-full wp-image-1690" src="http://labs.thesedays.com/wp-content/uploads/2011/12/05-Progress-bar-with-SignalR-Deploy-Manager.png" alt="DeployManager: server-side implementation of the hub" width="560" height="628" /></a><p class="wp-caption-text">DeployManager: server-side implementation of the hub</p></div>
<p>All it takes is creating a class which derives from <em>SignalR.Hubs.Hub</em> and by doing so the <em>run</em> method that is executed in the client-side script will trigger the run method on this class, which is all handled by SignalR.</p>
<p>The actual deployment logic is implemented in the <em>WebAppManager </em>class, so the <em>run</em> method just creates a new worker thread and passes in the deployment info. The worker thread instantiates a <em>WebAppManager</em> and subscribes to the progress event which will bubble progress events back to the <em>DeployManager</em>. Finally, the <em>DeployManager</em> will update the progress to all its clients (also handled by SignalR) which causes the <em>updateProgress</em> method on all clients to fire. Isn’t that just <strong>awesome</strong>?</p>
<p>Finally, the view which lists all websites can be easily updated by adding some familiar client-side script.</p>
<div id="attachment_1691" class="wp-caption alignnone" style="width: 580px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/12/06-Progress-bar-with-SignalR-Management-View.png"><img class="size-full wp-image-1691 " src="http://labs.thesedays.com/wp-content/uploads/2011/12/06-Progress-bar-with-SignalR-Management-View.png" alt="Client-side code in the App Management view" width="570" height="419" /></a><p class="wp-caption-text">Client-side code in the App Management view</p></div>
<p>Whenever a progress update is received the script will check to see whether a website’s deploy icon (and alt/title text) needs to be switched back and forth.</p>
<p>And apart from the actual progress calculation, basically that is all there is to it!</p>
<img src="http://feeds.feedburner.com/~r/TheseDaysLabs/~4/2scs8DvtKFY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://labs.thesedays.com/blog/2011/12/05/creating-a-progress-bar-in-asp-net-using-signalr/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://labs.thesedays.com/blog/2011/12/05/creating-a-progress-bar-in-asp-net-using-signalr/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=creating-a-progress-bar-in-asp-net-using-signalr</feedburner:origLink></item>
		<item>
		<title>A blob storage hive provider for Umbraco 5 (beta)</title>
		<link>http://feedproxy.google.com/~r/TheseDaysLabs/~3/VI6S7bnguCw/</link>
		<comments>http://labs.thesedays.com/blog/2011/11/25/a-blob-storage-hive-provider-for-umbraco-5-beta/#comments</comments>
		<pubDate>Fri, 25 Nov 2011 15:05:05 +0000</pubDate>
		<dc:creator>Lennart Stoop</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Open source]]></category>
		<category><![CDATA[Umbraco]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[Windows Azure]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[blob storage]]></category>
		<category><![CDATA[hive]]></category>
		<category><![CDATA[jupiter]]></category>
		<category><![CDATA[umbraco]]></category>

		<guid isPermaLink="false">http://labs.thesedays.com/?p=1642</guid>
		<description><![CDATA[An introduction into Umbraco Hive and creating a Hive provider which stores media on Azure blob storage. Related files: download the source code &#8211; download the web application Jupiter is just around the corner With its first beta release on November 11th the road to Umbraco 5 (aka Jupiter) has brought us very close to [...]]]></description>
			<content:encoded><![CDATA[<p><em>An introduction into Umbraco Hive and creating a Hive provider which stores media on Azure blob storage.</em></p>
<p>Related files: <a href="http://labs.thesedays.com/wp-content/uploads/2011/11/ProviderSourceCode.zip">download the source code</a> &#8211; <a href="http://labs.thesedays.com/wp-content/uploads/2011/11/UmbracoBetaWebApp.zip">download the web application</a></p>
<p><strong>Jupiter is just around the corner</strong></p>
<p>With its first <a href="http://umbraco.com/follow-us/blog-archive/2011/11/11/umbraco-5-beta-1-is-out-today.aspx" target="_blank">beta release</a> on November 11<sup>th </sup>the <a href="http://umbraco.com/umbraco-5-status.aspx" target="_blank">road to Umbraco 5</a> (aka Jupiter) has brought us very close to its destination. The members of the Umbraco core team have been working really hard on stabilizing the API and many of our beloved (and improved) CMS features are well taking shape.</p>
<p>As Umbraco 5 remains open source all current and future releases are made available through <a href="http://umbraco.codeplex.com/" target="_blank">Codeplex </a>which allows developers of the <a href="http://our.umbraco.org/" target="_blank">Umbraco community</a> to explore and work with the source code, to contribute and to provide the <a href="http://our.umbraco.org/wiki/about/core-team" target="_blank">core team</a> with valuable feedback.</p>
<p>After having attended the awesome <a href="http://umb5hackaton.buug.be/" target="_blank">Umbraco v5 hackathon</a> organized by <a href="http://www.buug.be" target="_blank">BUUG</a> and hosted at our offices in Amsterdam – and also very much inspired by <a href="http://boxbinary.com/" target="_blank">Alex Norcliffe</a>’s talk at the Microsoft offices in Brussels – we really wanted to get our hands dirty and – deep dive into hive!</p>
<p><strong>Umbraco Hive</strong></p>
<p>Many of the recent Umbraco 5 talks and presentations involve <a href="http://jupiter.umbraco.org/Data-Access-in-Umbraco-5.ashx" target="_blank">Hive</a>, a completely new and extremely powerful concept in the upcoming version. Much unlike a traditional data layer in most n-tier or n-layer (web) applications Hive represents an abstraction layer for developers to plug in multiple, stackable data providers. These Hive providers can pull data (read and/or write) from nearly any data source and allow for smooth integration within the Umbraco back office as well as a transparent way of querying the data in the front-end.</p>
<p>The <a href="http://umbraco.codeplex.com/releases/view/76238" target="_blank">first beta release</a> comes with three Hive providers, created by the core team:</p>
<ul>
<li>A persistence provider that already supports SQL server and SQL CE (which uses <a href="http://sourceforge.net/projects/nhibernate/files/NHibernate/" target="_blank">NHibernate</a> as ORM)</li>
<li>An Examine provider for data indexation (which uses the <a href="http://incubator.apache.org/lucene.net/" target="_blank">Lucene.NET</a> indexer)</li>
<li>An IO provider which stores data on the local file system</li>
</ul>
<p>Basically this means Hive already supports the vast majority of (.NET) based websites.</p>
<p>By the way, didn’t I mention these providers are stackable? In a recent <a href="http://www.buug.be/en/events/umbracov5" target="_blank">demo</a> (video currently not available yet) Alex quickly swapped the Examine provider with the persistence provider, having Umbraco run entirely on a file index without using a database at all. Although that’s a neat trick by itself, the true power of Hive is the ability to query multiple, stacked providers: imagine having data stored in both a database and a file index while data is always retrieved from the file index in order to gain a performance boost… Hive will make it work.</p>
<p><strong>Community hackathons</strong></p>
<p>In many countries the <a href="http://umbraco.com/follow-us/blog-archive/2011/10/27/duug-festival-2011-and-amsterdam-v5-hackathon-wrap-up.aspx" target="_blank">ongoing v5 hackathons</a> allow Umbraco developers to come together, share experiences, learn and contribute. These sessions are the perfect opportunity to experiment with the various new concepts in v5 such as hive, hive providers, property editors, surface controllers, tree controllers and much more.</p>
<p>During the BUUG hackathon we were able to play around with the WordPress Hive provider created by <a href="http://blog.mattbrailsford.com/" target="_blank">the Karminator</a>. Basically the provider connects to a <a href="http://wordpress.org/" target="_blank">WordPress blog</a> and fetches categories and posts which are then loaded into the Umbraco back office. And even though our efforts of making the provider writeable were somewhat fruitless (#h5is) it did allow us to get familiar with Hive and understand how to create and configure a custom Hive provider.</p>
<p>The source code of the WordPress hive provider can be found on <a href="https://bitbucket.org/boxbinary/hive-wordpress-provider" target="_blank">bitbucket </a>and has also been added to the <a href="http://umbraco5contrib.codeplex.com/" target="_blank">Umbraco 5 Contrib project</a> on Codeplex which was introduced during the recent UK hackathon.</p>
<p>Since we weren’t able to attend the <a href="http://umbracoukfestival.co.uk/" target="_blank">Umbraco UK festival</a> and we didn’t want to wait until the next hackathon to further explore v5, we started a somewhat experimental side project: whether or not the websites we create are hosted on Windows Azure we often want to store resources on <a href="http://www.microsoft.com/windowsazure/features/cdn/" target="_blank">Windows Azure CDN</a> or <a href="http://www.microsoft.com/windowsazure/features/storage/" target="_blank">blob storage</a>. In Umbraco v5 style sheets, scripts, templates and media uploads are stored on the local file system. All of this is handled by the IO Hive provider, so we decided to create a Hive provider which is to save these files on blob storage, and it works!</p>
<p>As for the more technical part of this post, let’s have a closer look at the setup.</p>
<p><strong>Configuring the Blob Storage Hive provider</strong></p>
<p>When you have a closer look at the Hive configuration file you will notice that a Hive provider can be configured separately for each of the storage types known by Umbraco.</p>
<div id="attachment_1645" class="wp-caption alignnone" style="width: 593px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/11/01-Blob-storage-hive-provider-Hive-config.png"><img class="size-full wp-image-1645 " src="http://labs.thesedays.com/wp-content/uploads/2011/11/01-Blob-storage-hive-provider-Hive-config.png" alt="The hive configuration file, located in App_Data\Umbraco\Config" width="583" height="103" /></a><p class="wp-caption-text">The hive configuration file, located in App_Data\Umbraco\Config</p></div>
<p>The configuration file allows you to configure the type of the Factory class that is used by Hive to instantiate the provider’s entity repository (more on this later) as well as a reference to the provider configuration section which is located in the web.config. As shown below this configuration section allows users to further configure the Hive provider.</p>
<div id="attachment_1646" class="wp-caption alignnone" style="width: 562px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/11/02-Blob-storage-hive-provider-Web-config.png"><img class="size-full wp-image-1646 " src="http://labs.thesedays.com/wp-content/uploads/2011/11/02-Blob-storage-hive-provider-Web-config.png" alt="The umbraco configuration section in web.config" width="552" height="128" /></a><p class="wp-caption-text">The umbraco configuration section in web.config</p></div>
<p>As for the blob storage provider we allow users to configure the name of the connection string of the blob storage account (which is to be added to the connection strings section) as well as the name of the blob container.</p>
<p>Creating a custom configuration section is fully supported by the <a href="http://umbraco.codeplex.com/SourceControl/changeset/view/bde2e6f42a6f#Source%2fLibraries%2fUmbraco.Hive%2fAbstractProviderDependencyBuilder.cs" target="_blank">Umbraco v5 Framework</a> and is just a matter of creating/inheriting some classes that will allow the settings to be injected into the Entity repository (handled by <a href="http://code.google.com/p/autofac/" target="_blank">IOC</a>, very sweet). Make sure to have a look at <a href="http://labs.thesedays.com/wp-content/uploads/2011/11/ProviderSourceCode.zip">the source code</a> to find out exactly how easy it is ;-)</p>
<div id="attachment_1647" class="wp-caption alignnone" style="width: 529px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/11/03-Blob-storage-hive-provider-Dependency-helper.png"><img class="size-full wp-image-1647  " src="http://labs.thesedays.com/wp-content/uploads/2011/11/03-Blob-storage-hive-provider-Dependency-helper.png" alt="The provider dependency helper is a property of the abstract entity repository" width="519" height="198" /></a><p class="wp-caption-text">The provider dependency helper is a property of the abstract entity repository</p></div>
<p><strong>Creating the Blob Storage Hive provider</strong></p>
<p>Although we haven’t gotten around testing the provider for all storage types just yet, obviously the first thing we had in mind was having the provider handle media file uploads. The one thing which distinguishes media from other storage types is is that it uses both a persistence provider and a storage provider. This approach provides a (much needed) separation of the concept of media on the one hand and the actual physical storage on the other hand (I will come back to this in a moment).</p>
<p>As we won’t be replacing the persistence provider we were able to reuse plenty of the code written for the IO provider. So instead of walking through all the code, let’s just have a look at the key differences (and imperfections).</p>
<p>When you create a custom Hive provider you start out with creating an Entity model and a schema, allowing you to convert an arbitrary data model into a model which can be interpreted by Hive. Hive provides base entity classes for both model and schema (currently <em>TypedEntity</em> and <em>EntitySchema</em>) and base repository classes (currently <em>AbstractEntityRepository</em> and <em>AbstractSchemaRepository</em>) which allow Hive to query against model, schema and relations.</p>
<p>The main problem we faced when creating a model and schema for blob storage is that we noticed the core property editor used for uploading files in the back office creates a File model (IO provider). Since we did not want to create a custom upload property editor just yet, we decided to have our Blob model derive from the File model instead.</p>
<div id="attachment_1648" class="wp-caption alignnone" style="width: 451px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/11/04-Blob-storage-hive-provider-Typed-Entity.png"><img class="size-full wp-image-1648" src="http://labs.thesedays.com/wp-content/uploads/2011/11/04-Blob-storage-hive-provider-Typed-Entity.png" alt="The Blob typed entity which derives from Umbraco.Persistence.Model.IO.File" width="441" height="228" /></a><p class="wp-caption-text">The Blob typed entity which derives from Umbraco.Persistence.Model.IO.File</p></div>
<p>Definitely something we will need to reconsider in the future, but for the sake of getting the project of the ground quickly it seems like a fair solution. This is also the reason why we didn’t put too much effort in tailoring the Blob schema just yet (a simple schema with a node name attribute seems to work just fine).</p>
<p>Next we copy/pasted the <a href="http://umbraco.codeplex.com/SourceControl/changeset/view/bde2e6f42a6f#Source%2fLibraries%2fUmbraco.Hive.Providers.IO%2fEntityRepository.cs" target="_blank">entity repository used by the IO provider</a> and implemented most of the key logic in having data stored on blob storage. This actually all went pretty smooth and the one thing worth mentioning here is probably the use of Hive ID’s. The IO provider assembles Hive ID’s by normalizing the file path and although I’m sure it makes perfect sense we didn’t get it straight away and decided to implement our own strategy which basically comes down to: blob – container – blob name (which includes the GUID of the persisted media).</p>
<p>Although we haven’t yet fully implemented all of the entity/relation operations (and revision support for that matter) we did implement some of the relation operations which basically allow for the creation of thumbnails (<em>AddRelation</em> and <em>PerformGetChildRelations</em>). Having these implemented was amazingly straightforward by the way, so a big thumbs up to the core team! And again, you should really check out <a href="http://labs.thesedays.com/wp-content/uploads/2011/11/ProviderSourceCode.zip">the source code</a> to find out just how easy it was ;-)</p>
<div id="attachment_1649" class="wp-caption alignnone" style="width: 583px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/11/05-Blob-storage-hive-provider-Entity-repository-add-relation.png"><img class="size-full wp-image-1649 " src="http://labs.thesedays.com/wp-content/uploads/2011/11/05-Blob-storage-hive-provider-Entity-repository-add-relation.png" alt="The AddRelation method of the Entity Repository" width="573" height="218" /></a><p class="wp-caption-text">The AddRelation method of the Entity Repository</p></div>
<p>That’s basically it, and now we seriously wanted to test-drive this baby! Unfortunately the upload property editor did require a small fix in order to make it work with our blob storage provider: the code used to create a thumbnail creates a bitmap by passing in a file path. To fix this we just had to replace 1 line of code (maybe 20 characters?) which I think still is impressive considering we are reusing the existing property editor ;-)</p>
<div id="attachment_1650" class="wp-caption alignnone" style="width: 477px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/11/06-Blob-storage-hive-provider-Upload-property-editor-fix.png"><img class="size-full wp-image-1650 " src="http://labs.thesedays.com/wp-content/uploads/2011/11/06-Blob-storage-hive-provider-Upload-property-editor-fix.png" alt="A small fix in the core Upload property editor" width="467" height="127" /></a><p class="wp-caption-text">A small fix in the core Upload property editor</p></div>
<p>And it just works!</p>
<div id="attachment_1651" class="wp-caption alignnone" style="width: 571px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/11/07-Blob-storage-hive-provider-Media-section-using-blob-storage.png"><img class="size-full wp-image-1651 " src="http://labs.thesedays.com/wp-content/uploads/2011/11/07-Blob-storage-hive-provider-Media-section-using-blob-storage.png" alt="Media section in a local Umbraco v5 beta installation" width="561" height="172" /></a><p class="wp-caption-text">Media section in a local Umbraco v5 beta installation</p></div>
<div id="attachment_1652" class="wp-caption alignnone" style="width: 574px"><a href="http://labs.thesedays.com/wp-content/uploads/2011/11/08-Blob-storage-hive-provider-Cloudberry-explorer.png"><img class="size-full wp-image-1652 " src="http://labs.thesedays.com/wp-content/uploads/2011/11/08-Blob-storage-hive-provider-Cloudberry-explorer.png" alt="Cloudberry explorer showing the media files on blob storage" width="564" height="156" /></a><p class="wp-caption-text">Cloudberry explorer showing the media files on blob storage</p></div>
<p>We were actually somewhat surprised to see it work immediately as we first figured we would still have to make some changes in having the editor display the thumbnails (they&#8217;re on blob storage, so what about the URL?) and this is when we found out Umbraco 5 uses a custom mechanism for rendering media, i.e. the following URL will display an image uploaded as media:</p>
<p><em>http://umb5beta.local/Umbraco/Media/Proxy/media%24empty_root%24%24_p__nhibernate%24_</em></p>
<p><em>v__guid%24_28a171dda97048f98e6b9fa501792a5b?propertyAlias=uploadedFile</em></p>
<p>Remember the separation of the concept of media and the actual physical storage I mentioned earlier? Right!</p>
<p><strong>What’s next?</strong></p>
<p>Although we realize this is just a very basic implementation we would certainly love to see it being further developed into a solid Jupiter hive provider, and of course we love to hear your feedback and suggestions.</p>
<p>The source code is available on the <a href="http://umbraco5contrib.codeplex.com/SourceControl/network/Forks/theamph/Blobstorage">Umbraco 5 contrib project</a> (forked) or  you can just <a href="http://labs.thesedays.com/wp-content/uploads/2011/11/ProviderSourceCode.zip">download it here</a> or <a href="http://labs.thesedays.com/wp-content/uploads/2011/11/UmbracoBetaWebApp.zip">download a full web application</a> which has the provider already configured (it uses SQL CE so no need to setup a database).</p>
<p>At <a href="http://www.thesedays.com" target="_blank">These Days</a> we are already looking forward to the next release of Jupiter!</p>
<img src="http://feeds.feedburner.com/~r/TheseDaysLabs/~4/VI6S7bnguCw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://labs.thesedays.com/blog/2011/11/25/a-blob-storage-hive-provider-for-umbraco-5-beta/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		<feedburner:origLink>http://labs.thesedays.com/blog/2011/11/25/a-blob-storage-hive-provider-for-umbraco-5-beta/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=a-blob-storage-hive-provider-for-umbraco-5-beta</feedburner:origLink></item>
		<item>
		<title>responsive awareness</title>
		<link>http://feedproxy.google.com/~r/TheseDaysLabs/~3/WK9xYU38Bb8/</link>
		<comments>http://labs.thesedays.com/blog/2011/10/11/responsive-awareness/#comments</comments>
		<pubDate>Tue, 11 Oct 2011 08:19:51 +0000</pubDate>
		<dc:creator>onehundred_be</dc:creator>
				<category><![CDATA[CSS3]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Innovation]]></category>

		<guid isPermaLink="false">http://labs.thesedays.com/?p=1588</guid>
		<description><![CDATA[It&#8217;s 2011, the way we consume the internet has changed quite a bit over the past few years. We&#8217;re now dealing with a whole new range of web capable devices: smartphones, tablets and TV&#8217;s, just to name a few. Yet for the last couple of years websites are designed and built for a 1024 px [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s 2011, the way we consume the internet has changed quite a bit over the past few years. We&#8217;re now dealing with a whole new range of web capable devices: smartphones, tablets and TV&#8217;s, just to name a few. Yet for the last couple of years websites are designed and built for a 1024 px screen resolution. This so called standard is no longer accurate and if we keep making products for this old screen resolution, a lot of people will feel discriminated. When someone gets their hands on a brand new device and they are still presented with an interface which is no longer relevant, chances are they won&#8217;t be very happy.</p>
<p>That&#8217;s why it&#8217;s time for responsive awareness. The presentation included in this blogpost exists out of three parts and is intended for everybody with an interest in responsive web design and development, designers and front-end developers. Are you ready to make the switch? Do you want to deliver optimal user experience at all times? Get responsive already.</p>
<h2>Demo</h2>
<p><a href="http://playground.thesedays.com/responsive" target="_blank">check it out</a></p>
<p>Look ma, <strong>no javascript</strong>. Without scripting however IE6, IE7 &amp; IE8 won&#8217;t display properly. If you would like to see this work in every browser known to mankind simply include <a href="https://github.com/scottjehl/Respond" target="_blank">respond.js</a>. While viewing the demo, screen resolutions are displayed in the upper left corner. Depending on your screen size you can see up to <strong>seven different layouts</strong>.  The css is dynamic thanks to less.</p>
<h2>Presentation</h2>
<p>This presentation aims to shed light on do&#8217;s and don&#8217;ts for both designers and front-end developers. You can expect some tips on how to approach a responsive project, how to optimize the website for speed and plenty more.</p>
<div style="width: 425px">
<iframe src="http://www.slideshare.net/slideshow/embed_code/9629824" width="590" height="481" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe><br/><br/>
</div>
<img src="http://feeds.feedburner.com/~r/TheseDaysLabs/~4/WK9xYU38Bb8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://labs.thesedays.com/blog/2011/10/11/responsive-awareness/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://labs.thesedays.com/blog/2011/10/11/responsive-awareness/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=responsive-awareness</feedburner:origLink></item>
		<item>
		<title>Introducing Dude Where’s My Velo</title>
		<link>http://feedproxy.google.com/~r/TheseDaysLabs/~3/jPv2epdzyyU/</link>
		<comments>http://labs.thesedays.com/blog/2011/07/26/introducing-dude-where%e2%80%99s-my-velo/#comments</comments>
		<pubDate>Tue, 26 Jul 2011 15:27:13 +0000</pubDate>
		<dc:creator>Keegan Street</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Mobile development]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[sass]]></category>

		<guid isPermaLink="false">http://labs.thesedays.com/?p=1450</guid>
		<description><![CDATA[Dude Where’s My Velo is a new HTML5 web app you can open on your phone to find the nearest velo city-bike in Antwerp. The interface is a full window Google Map with colour-coded markers representing the location of bike stations and the availability of velos. Geolocation is used to center the map and show [...]]]></description>
			<content:encoded><![CDATA[<p><em><a href="http://www.dudewheresmyvelo.be" target="_blank">Dude Where’s My Velo</a></em> is a new HTML5 web app you can open on your phone to find the nearest velo city-bike in Antwerp. The interface is a full window Google Map with colour-coded markers representing the location of bike stations and the availability of velos.</p>
<p>Geolocation is used to center the map and show the user’s exact position in Antwerp. As you ride around the city your new location is automatically represented on the map.</p>
<p>The serverside part of the application is built with NodeJS to be blazing fast. It constantly scrapes data from the official velo-antwerpen.be website and stores it as a JSON file. NodeJS is fast because it is an event driven server. After the server sends out a scraping request it will rest, and CPU usage will go down to zero, until it receives a response. This allows it to manage many simultaneous tasks.</p>
<p>On the client side, scripts and stylesheets are included as inline code to reduce the number of HTTP requests made and improve the performance of the app.</p>
<p>All code for the project is <a href="https://github.com/keeganstreet/dudewheresmyvelo.be" target="_blank">open source and available on GitHub</a>, so if you’d like to improve something about the website, feel free to make your own changes and submit a pull request.</p>
<p>There are a number of reasons we built this as an HTML5 web app rather than a native app.</p>
<p>The most important reason is cross-device support. The Google Maps SDK we use already supports iPhone, Android, BlackBerry 6 and Dolfin 2 (Samsung Beda). As other manufacturers improve their mobile web browsers, <em>Dude Where’s My Velo</em> will automatically support those devices. We are expecting good support for Windows Mobile and Nokia devices later this year.</p>
<p>The second reason for web over native is bug fixes and feature updates. Web apps can be updated as quickly and easily as normal websites. Changes don’t have to be approved or reviewed by third parties.</p>
<p>So check it out now. Visit <a href="http://www.dudewheresmyvelo.be" target="_blank">dudewheresmyvelo.be</a> on your phone or computer. We would also like to give a shout out to <a href="https://www.dotcloud.com/" target="_blank">DotCloud</a> who are hosting the app for free. Happy cycling!</p>
<p><a href="http://labs.thesedays.com/wp-content/uploads/2011/07/DWMV-post.jpg"><img class="alignnone size-medium wp-image-1451" src="http://labs.thesedays.com/wp-content/uploads/2011/07/DWMV-post-159x300.jpg" alt="" width="159" height="300" /></a></p>
<img src="http://feeds.feedburner.com/~r/TheseDaysLabs/~4/jPv2epdzyyU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://labs.thesedays.com/blog/2011/07/26/introducing-dude-where%e2%80%99s-my-velo/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://labs.thesedays.com/blog/2011/07/26/introducing-dude-where%e2%80%99s-my-velo/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=introducing-dude-where%25e2%2580%2599s-my-velo</feedburner:origLink></item>
	</channel>
</rss>
