<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns: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/"
	>

<channel>
	<title>var Matt = new Hero();</title>
	<atom:link href="http://www.fidelitydesign.net/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.fidelitydesign.net</link>
	<description>C#, ASP.NET MVC, MEF, Javascript...and anything else that interests me.</description>
	<lastBuildDate>Sun, 24 Jun 2012 11:16:38 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4</generator>
		<item>
		<title>Using Xml and jQuery to configure your unobtrusive client side scripts.</title>
		<link>http://www.fidelitydesign.net/?p=555</link>
		<comments>http://www.fidelitydesign.net/?p=555#comments</comments>
		<pubDate>Fri, 09 Mar 2012 10:08:55 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[unobtrusive]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=555</guid>
		<description><![CDATA[Using xml in your html, to configure your external scripts.]]></description>
			<content:encoded><![CDATA[<p>Part of my day job is to maintain an online purchase path, and through my recent efforts to refactor and streamline the code, I&#8217;ve come across a technique that better enables me to build my scripts in such a way that they are truly unobstrusive. But what do I mean by all this? Ok, say you have some code such as:</p>
<p>Script.js:</p>
<pre class="prettyprint">
(function($) {

  var serviceUrl = window.ScriptConfig.serviceUrl;
  // Where ScriptConfig is declared on your target page.

})(window.jQuery);
</pre>
<p>Page.html:</p>
<pre class="prettyprint">
&lt;script type="text/javascript"&gt;
  window.ScriptConfig = {
    serviceUrl: "/path/to/service"
  };
&lt;/script&gt;
&lt;script type="text/javascript" src="/script.js"&gt;&lt;/script&gt;
</pre>
<p>The problem with the above scenario, is that the ordering of scripts to config is really important, otherwise you&#8217;re attempting to use values in your script which are still potentially undefined. Also, if you&#8217;re trying to achieve a semantically clean page (where the page&#8217;s responsibility is to represent data, no presentation, not logic) &#8211; this kinda violates that.</p>
<p>What you can do though, is instead of relying on your scripts to be javascript, lets set them to &#8220;text/xml&#8221;:</p>
<pre class="prettyprint">
&lt;script id="scriptConfig" type="text/xml"&gt;
  &lt;config serviceUrl="/path/to/service" /&gt;
&lt;/script&gt;
</pre>
<p>Essentially, by using xml in your script tags, you can then take advantage of your browsers xml parser to read the document in and configure your scripts. Let&#8217;s change our script:</p>
<pre class="prettyprint">
(function($) {
  
  var serviceUrl;
  
  $(function() {
    var xml = $.parseXML($("#scriptConfig").html());
    
    serviceUrl = $(xml).find("config").attr("serviceUrl");
  });

})(window.jQuery);
</pre>
<p>Now, in our script file, we can use jQuery&#8217;s parseXML function to build an Xml DOM. Because this is a DOM object, we can then use jQuery itself to interrogate the model to find elements, attributes.</p>
<p>Note: You have to use &#8220;html()&#8221;, and not &#8220;text()&#8221; as the latter does not work in IE.</p>
<p>This also allows us to have a completely script free page <img src='http://www.fidelitydesign.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555&amp;title=Using+Xml+and+jQuery+to+configure+your+unobtrusive+client+side+scripts." ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555&amp;title=Using+Xml+and+jQuery+to+configure+your+unobtrusive+client+side+scripts." ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555&amp;title=Using+Xml+and+jQuery+to+configure+your+unobtrusive+client+side+scripts." ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555&amp;headline=Using+Xml+and+jQuery+to+configure+your+unobtrusive+client+side+scripts." ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Using+Xml+and+jQuery+to+configure+your+unobtrusive+client+side+scripts.&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Using+Xml+and+jQuery+to+configure+your+unobtrusive+client+side+scripts.&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Using+Xml+and+jQuery+to+configure+your+unobtrusive+client+side+scripts.&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Using+Xml+and+jQuery+to+configure+your+unobtrusive+client+side+scripts.&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Using+Xml+and+jQuery+to+configure+your+unobtrusive+client+side+scripts.&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555&amp;title=Using+Xml+and+jQuery+to+configure+your+unobtrusive+client+side+scripts.&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D555" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&#038;p=555</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Expressive Configuration Files with Evaluators</title>
		<link>http://www.fidelitydesign.net/?p=514</link>
		<comments>http://www.fidelitydesign.net/?p=514#comments</comments>
		<pubDate>Thu, 17 Nov 2011 18:47:58 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[evaluators]]></category>
		<category><![CDATA[expressions]]></category>
		<category><![CDATA[xaml]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=514</guid>
		<description><![CDATA[Expressive Configuration Files with Evaluators I&#8217;ve not played around too much with WPF, but one of the things I do like about it, is the expressive binding syntax you can use to declaratively apply binding to elements, e.g: &#60;ListBox Name="entryListBox" ItemsSource="{Binding Source={StaticResource RssFeed}, XPath=//item}" /&#62; It lead me to think, could we provide something similar, [...]]]></description>
			<content:encoded><![CDATA[<h4>Expressive Configuration Files with Evaluators</h4>
<p>I&#8217;ve not played around too much with WPF, but one of the things I do like about it, is the expressive binding syntax you can use to declaratively apply binding to elements, e.g:</p>
<pre class="prettyprint">
  &lt;ListBox Name="entryListBox" ItemsSource="{Binding Source={StaticResource RssFeed}, XPath=//item}" /&gt;
</pre>
<p>It lead me to think, could we provide something similar, but apply it to something such as a configuration file, or really any string content? Here is what I am aiming to achieve:</p>
<pre class="prettyprint">
  &lt;configuration&gt;
    &lt;appSettings&gt;
      &lt;!-- Simple Values --&gt;
      &lt;add key="MyFirstSetting" value="First" /&gt;
      &lt;add key="MySecondSetting" value="{AppSetting MyFirstSetting}" /&gt;
      
      &lt;!-- A connection string lookup --&gt;
      &lt;add key="DefaultDatabaseConnection" value="Test" /&gt;
      
      &lt;!-- Other settings --&gt;
      &lt;add key="DatabaseServer" value="192.168.0.1,1724" /&gt;
      
      &lt;add key="Database" value="Test" /&gt;
      &lt;add key="Database_Staging" value="Staging" /&gt;
      &lt;add key="Database_Production" value="Production" /&gt;
      
      &lt;add key="MachineType" value="Staging" /&gt;
      
      &lt;!-- Composite expressions --&gt;
      &lt;add key="SomeSetting" value="MySecondSetting" /&gt;
      &lt;add key="SomeCompositeSetting" value="{AppSetting {AppSetting SomeSetting}}" /&gt;
    &lt;/appSettings&gt;
    
    &lt;connectionStrings&gt;
      &lt;add name="Test" connectionString="Server=(local);Database=Test;Integrated Security=true;" /&gt;
      &lt;add name="Main" connectionString="Server={AppSetting DatabaseServer};Database={AppSetting Database};Integrated Security=true" /&gt;
    &lt;/connectionStrings&gt;
  &lt;/configuration&gt;
</pre>
<p>The idea being that we could evaluate these expressions at runtime without having to worry about composing variables from say, the Application settings, or connection strings, etc.</p>
<p>The way I approached this, was to define a interface, the IEvaluator. This would allow me from the start to make the mechanism extensible. The interface looks like this:</p>
<pre class="prettyprint">
public interface IEvaluator
{
    #region Properties
    string Name { get; }
    #endregion

    #region Methods
    string Evaluate(string value);
    #endregion
}
</pre>
<p>It&#8217;s a simple interface, promoting a name (which will directly correlate to the left-hand value, e.g. &#8220;AppSetting&#8221; in &#8220;{AppSetting MyFirstSetting}&#8221;), and the method which will evaluate the actual argument itself. Here is an example evaluator, the AppSettingEvaluator:</p>
<pre class="prettyprint">
public class AppSettingEvaluator : EvaluatorBase
{
    #region Properties
    public override string Name { get { return "AppSetting"; } }
    #endregion

    #region Methods
    protected override string EvaluateCore(string value)
    {
        return From.AppSetting(value);
    }
    #endregion
}
</pre>
<p>I&#8217;ve implemented a base class which handles the caching of any results, and this method simply uses a From.AppSetting(&#8230;) method call which is a simple utility function. The evaluator mechanism itself is driven through a regular expression, that will match a pattern like &#8220;{&lt;key&gt; &lt;value&gt;}&#8221;, and allow us to extract those values and replace. We also provide a list of evaulators (bundling our AppSettingEvaluator and ConnectionStringEvaluator as standard, but it does provide a mechanism to register your own:</p>
<pre class="prettyprint">
public static class Evaluator
{
    #region Fields
    private static readonly Regex ExpressionRegex = new Regex(
        "\{(?&lt;key&gt;[a-z]*?)\s(?&lt;value&gt;[^{^}]*?)\}",
        RegexOptions.IgnoreCase
        | RegexOptions.Singleline
        | RegexOptions.CultureInvariant
        | RegexOptions.IgnorePatternWhitespace
        | RegexOptions.Compiled
        );

    private static readonly IList&lt;IEvaluator&gt; _evaluators = new List&lt;IEvaluator&gt;()
    {
        new AppSettingEvaluator(),
        new ConnectionStringEvaluator()
    };
    #endregion

    #region Methods
    public static void AddEvaluator(IEvaluator evaluator)
    {
        if (evaluator == null)
            throw new ArgumentNullException("evaluator");

        _evaluators.Add(evaluator);
    }

    public static string Evaluate(string value)
    {
        if (string.IsNullOrEmpty(value))
            return value;

        if (!HasExpression(value))
            return value;

        value = ExpressionRegex.Replace(value, m =&gt;
        {
            string key = m.Groups["key"].Value;
            string val = m.Groups["value"].Value;

            var evaluator = _evaluators.Where(e =&gt; key.Equals(e.Name)).FirstOrDefault();
            if (evaluator == null)
                return string.Format("[{0} {1}]", key, val);

            return evaluator.Evaluate(val);
        });

        return Evaluate(value);
    }

    public static bool HasExpression(string @string)
    {
        if (string.IsNullOrWhiteSpace(@string))
            return false;

        return ExpressionRegex.IsMatch(@string);
    }
    #endregion
}
</pre>
<p>The bulk of the work is done by the static Evaluate method, which uses our regular expression, and applies replacements based on the keys found. If we don&#8217;t have an evaluator, we re-write the values with square braces &#8220;[&lt;key&gt; &lt;value&gt;]&#8221; to highlight that it was not matched, and also to safeguard from infinite loops.  We use this method recursively to ensure that we can support composite expressions, e.g. &#8220;{ConnectionString {AppSetting DefaultDatabaseConnection}}&#8221;.</p>
<h4>Automatically Evaluating in Custom Configuration Sections</h4>
<p>The next logic step for me, was to see how we could automatically apply these expression evaluations to custom configuration sections. Given that configuration is read once and cached for the lifetime of the application, the initial hit would be the first time the configuration is read. Although we can&#8217;t make modifications to the stable set of configuration sections, for appSettings, connectionStrings etc, we could potentially provide custom evaluation for our own configuration sections. The way we do this, is we need to subclass ConfigurationSection, and intercept the xml being read before it is processed. To do this, we need to override the DeserializeElement(&#8230;) method of the ConfigurationElement type. We do this at the ConfigurationSection stage, as it will apply the change to the entire configuration section, not individual elements. Here is how it looks:</p>
<pre class="prettyprint">
public abstract class EvaluatedConfigurationSectionBase : ConfigurationSection
{
    #region Methods
    protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
    {
        string content = reader.ReadOuterXml();
        content = Evaluator.Evaluate(content);

        var manager = new XmlNamespaceManager(reader.NameTable);
        var context = new XmlParserContext(reader.NameTable, manager, null, reader.XmlSpace);
        var newReader = new XmlTextReader(content, XmlNodeType.Element, context);

        newReader.Read();
        base.DeserializeElement(newReader, serializeCollectionKey);
    }
    #endregion
}
</pre>
<p>With that, we can implement a custom configuration section:</p>
<pre class="prettyprint">
public class TestConfigurationSection : EvaluatedConfigurationSectionBase
{
    #region Fields
    private const string TestPropertyAttribute = "testProperty";
    private const string TestElementElement = "testElement";
    #endregion

    #region Properties
    [ConfigurationProperty(TestPropertyAttribute, IsRequired = true)]
    public string TestProperty
    {
        get { return (string)this[TestPropertyAttribute]; }
    }

    [ConfigurationProperty(TestElementElement, IsRequired = false)]
    public TestConfigurationElement TestElement
    {
        get { return (TestConfigurationElement)this[TestElementElement]; }
    }
    #endregion
}
</pre>
<p>There is nothing special about this class, its standard implementation of a custom configuration section. We haven&#8217;t had to mark anything to be evaluated, it&#8217;s just handled for us automatically. Here is what it would look like in config:</p>
<pre class="prettyprint">
&lt;test testProperty="{ConnectionString {AppSetting DefaultDatabaseConnection}}"&gt;
  &lt;testElement testProperty="{ConnectionString Main}" /&gt;
&lt;/test&gt;
</pre>
<p>Now, when I read those values:</p>
<pre class="prettyprint">
  var config = (TestConfigurationSection)ConfigurationManager.GetSection("test");
</pre>
<p>The values of config.TestProperty, and config.TestElement.TestProperty are automatically evaluated for us, just the once. Neat!</p>
<h4>Custom Evaluators</h4>
<p>Let&#8217;s look at a custom evaluator. Historically, I&#8217;ve found myself typing Type names out in full multiple times in configuration files (although less and less these days), so I came up with a solution, named types. This is a configuration section that represents a mapping between a shortname and the full type name, e.g.:</p>
<pre class="prettyprint">
&lt;namedTypes&gt;
  &lt;add name="String" type="System.String" /&gt;
  &lt;add name="CompositionContainerFactory" type="My.Namespace.For.A.CompositionContainerFactory, My.Assembly" /&gt;
&lt;/namedTypes&gt;
</pre>
<p>We&#8217;ll skip over the configuration section implementation, and jump to the evaluator:</p>
<pre class="prettyprint">
public class NamedTypeEvaluator : EvaluatorBase
{
    #region Properties
    public override string Name { get { return "NamedType"; } }
    #endregion

    #region Methods
    protected override string EvaluateCore(string value)
    {
        return NamedTypes.GetNamedType(value);
    }
    #endregion
}
</pre>
<p>We can register this evaluator:</p>
<pre class="prettyprint">
Evaluator.AddEvaluator(new NamedTypeEvaluator());
</pre>
<p>And assuming we use it somewhere, e.g., in an application setting:</p>
<pre class="prettyprint">
&lt;appSettings&gt;
  &lt;!-- Container Factory Type --&gt;
  &lt;add key="ContainerFactory" value="{NamedType CompositionContainerFactory}" /&gt;
&lt;/appSettings&gt;
</pre>
<p>This value can automatically be evaluated for us.  I think the obvious next step is to compose evaluators from your inversion of control (IoC) container or service locator, so you introduce a dynamic plug and play system.</p>
<p>The project is attached, let me know your thoughts.</p>
<p><a href='http://www.fidelitydesign.net/wp-content/uploads/2011/11/ExpressiveConfig.zip'>Expressive Configuration files with Evaluators</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514&amp;title=Expressive+Configuration+Files+with+Evaluators" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514&amp;title=Expressive+Configuration+Files+with+Evaluators" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514&amp;title=Expressive+Configuration+Files+with+Evaluators" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514&amp;headline=Expressive+Configuration+Files+with+Evaluators" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Expressive+Configuration+Files+with+Evaluators&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Expressive+Configuration+Files+with+Evaluators&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Expressive+Configuration+Files+with+Evaluators&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Expressive+Configuration+Files+with+Evaluators&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Expressive+Configuration+Files+with+Evaluators&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514&amp;title=Expressive+Configuration+Files+with+Evaluators&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D514" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&#038;p=514</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Glimpsing into MEF</title>
		<link>http://www.fidelitydesign.net/?p=492</link>
		<comments>http://www.fidelitydesign.net/?p=492#comments</comments>
		<pubDate>Fri, 04 Nov 2011 00:25:15 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[glimpse]]></category>
		<category><![CDATA[MEF]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=492</guid>
		<description><![CDATA[I&#8217;ve been playing around with Glimpse recently, and knowing that my favourite tech at the moment is the Managed Extensibility Framework (MEF), I decided to put together a Glimpse plugin that would allow you a glimpse (ahem) into what is going on inside your composition container. The plugin is implemented as a series of decorators [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been playing around with Glimpse recently, and knowing that my favourite tech at the moment is the Managed Extensibility Framework (MEF), I decided to put together a Glimpse plugin that would allow you a glimpse (ahem) into what is going on inside your composition container. The plugin is implemented as a series of decorators around the primitive MEF types (currently we are concentraing on Catalogs), and a custom implementation of a CompositionContainer that supports the Glimpse mechanism.</p>
<h3>How does it work?</h3>
<p>At the core of the plugin, we have our custom container, the GlimpseCompositionContainer. This is a subclass of the standard CompositionContainer, it supports the ability to grab information about your catalogs. We do this during construction of the container by building a set of descriptors for the catalogs. So, the first step to get started (in fact, the only step), is to swap your declaration of your container to:</p>
<pre class="prettyprint">
var catalog = new AggregateCatalog(
  new DirectoryCatalog("bin"));
  
var container = new GlimpseCompositionContainer(catalog);
</pre>
<p>The GlimpseCompositionContainer is designed to replace your current container. If Glimpse is not enabled, the container simply behaves like the standard CompositionContainer. When it is enabled, we decorate any of the catalogs using our GlimpseCatalog.</p>
<p>The GlimpseCatalog is responsible for providing details on the exports that are being required for composition. So for each requested contract, a set of possible definitions may be returned.</p>
<h3>Getting this data to Glimpse</h3>
<p>Because Glimpse is designed to display data to the client, data is collected through the lifetime of the request, and pushed down to client on render. We currently collect data in two places:</p>
<ol>
<li>Catalog information (presented on the MEF Container tab) displays the list of catalogs, and the parts available for each catalog. This is collected and stored in the runtime cache (as the container should essentially be declared once for the lifetime of the applicaiton.</li>
</ol>
<div><a href="http://www.fidelitydesign.net/wp-content/uploads/2011/11/MEF-Container.png"><img src="http://www.fidelitydesign.net/wp-content/uploads/2011/11/MEF-Container-300x133.png" alt="" title="MEF Container" width="300" height="133" class="aligncenter size-medium wp-image-497" /></a></div>
<ol start="2">
<li>Import information (presented on the MEF Imports tab) displays the list of requests to the composition container, along with any matching exports. This is collected for each request, and is stored in the Request.Items collection.</li>
</ol>
<div><a href="http://www.fidelitydesign.net/wp-content/uploads/2011/11/MEF-Imports.png"><img src="http://www.fidelitydesign.net/wp-content/uploads/2011/11/MEF-Imports-300x133.png" alt="" title="MEF Imports" width="300" height="133" class="aligncenter size-medium wp-image-502" /></a></div>
<p>With this information to hand, we can start visualising what our composition system is made of.</p>
<h3>The sample Application</h3>
<p>On the <a href="https://github.com/Antaris/Glimpse.MEF">Github</a> project I&#8217;ve built a sample project which demonstrates the sort of information we can start getting from our app. In the sample app, I&#8217;ve reused the MefDependencyResolver and MefControllerFactory from my previous MVC+MEF projects (see <a href="http://www.fidelitydesign.net/?p=259">here</a>) which gives us a quick demonstration of how it all works.</p>
<p>With a dependency resolver and a controller factory plugged in, we can start exporting our controllers:</p>
<pre class="prettyprint">
namespace Glimpse.MEF.Sample.Controllers
{
    using System;
    using System.ComponentModel.Composition;
    using System.Web.Mvc;

    using Models;
    using Models.Logging;

    /// &lt;summary&gt;
    /// Defines the home controller.
    /// &lt;/summary&gt;
    [ExportController("Home"), PartCreationPolicy(CreationPolicy.NonShared)]
    public class HomeController : Controller
    {
        #region Fields
        private readonly ILogger _logger;
        #endregion

        #region Constructor
        /// &lt;summary&gt;
        /// Initialises a new instance of &lt;see cref="HomeController"/&gt;.
        /// &lt;/summary&gt;
        /// &lt;param name="logger"&gt;The logger.&lt;/param&gt;
        [ImportingConstructor]
        public HomeController(ILogger logger)
        {
            if (logger == null) throw new ArgumentNullException("logger");

            _logger = logger;
        }
        #endregion

        #region Actions
        /// &lt;summary&gt;
        /// Displays the default view.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public ActionResult Index()
        {
            _logger.Log("Entered HomeController.Index() action.");

            ViewBag.Message = "Welcome to ASP.NET MVC!";

            _logger.Log("Returning result from HomeController.Index() action.");
            return View();
        }

        /// &lt;summary&gt;
        /// Displays the about view.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public ActionResult About()
        {
            return View();
        }
        #endregion
    }
}
</pre>
<p>There is nothing really extensive going on here, I&#8217;ve just updated the the default HomeController implementation to support an injection of a dependency (our ILogger), and we then [Export] the controller so it can be picked up by MEF.</p>
<p>How does this get presented to Glimpse? Well, when we make a request to our /Home url, we started saving information about each request to GetExports on our catalogs. So in the above example, we resul in the followin items:</p>
<div><a href="http://www.fidelitydesign.net/wp-content/uploads/2011/11/MEF-Imports.png"><img src="http://www.fidelitydesign.net/wp-content/uploads/2011/11/MEF-Imports-300x133.png" alt="" title="MEF Imports" width="300" height="133" class="aligncenter size-medium wp-image-502" /></a></div>
<ol>
<li>Request to match contract System.Web.Mvc.IController which returns our 1 instance of our exported controller.</li>
<li>Request to match contract GlimpseMEF.Models.Logging.ILogger which returns our 1 instance of our exported logger. This is then injected into our controller.</li>
</ol>
<p>This is an initial version, which could change quite a lot, I need to detemine what sort of information people want to see. With that in mind, grab the source code, or search for Glimpse.MEF on Nuget to start playing around.</p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492&amp;title=Glimpsing+into+MEF" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492&amp;title=Glimpsing+into+MEF" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492&amp;title=Glimpsing+into+MEF" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492&amp;headline=Glimpsing+into+MEF" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Glimpsing+into+MEF&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Glimpsing+into+MEF&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Glimpsing+into+MEF&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Glimpsing+into+MEF&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Glimpsing+into+MEF&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492&amp;title=Glimpsing+into+MEF&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D492" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&#038;p=492</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>An early look at RazorEngine v3</title>
		<link>http://www.fidelitydesign.net/?p=473</link>
		<comments>http://www.fidelitydesign.net/?p=473#comments</comments>
		<pubDate>Thu, 13 Oct 2011 08:37:23 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=473</guid>
		<description><![CDATA[An early look at RazorEngine v3 Finally, I&#8217;ve started making progress on getting RazorEngine v3 out into the wild. Last night I pushed an early version of v3 to RazorEngine&#8217;s new home at GitHub. There is still a lot of stuff I need to get done, but there is at least something you can start [...]]]></description>
			<content:encoded><![CDATA[<h2>An early look at RazorEngine v3</h2>
<p>Finally, I&#8217;ve started making progress on getting RazorEngine v3 out into the wild. Last night I pushed an early version of v3 to RazorEngine&#8217;s new home at <a href="https://github.com/Antaris/RazorEngine" target="_blank">GitHub</a>. There is still a lot of stuff I need to get done, but there is at least something you can start poking around with. There are a lot of changes in v3, so I thought I&#8217;d highlight just a few here.</p>
<h3>Moving to GitHub</h3>
<p>The first thing you&#8217;ll notice is that I&#8217;m no longer pushing the code onto <a href="http://razorengine.codeplex.com" target="_blank">CodePlex</a>, but now moving to GitHub. GitHub will give us the opportunity to better share and collaborate with the development community to start really pushing RazorEngine in the open-source direction. Up until now, development has really been done by Ben (<a href="http://www.twitter.com/buildstarted">@buildstarted</a>) and myself, but I want to allow many more people to get involved and determine the direction we take RazorEngine. GitHub&#8217;s fantastic SCM abilities and community features will help us achieve this.</p>
<p>Currently, I&#8217;ve been using the master branch for all my commits. After the release push of v3, we&#8217;ll start development in secondary branches and use the master branch as a release branch.</p>
<p>An early version of v3 is on GitHub now, so feel free to fork and start your pull requests, ask questions and get involved <img src='http://www.fidelitydesign.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3>Breaking API Changes</h3>
<p>I hate breaking API changes, but unfortunately there is such a significant reason to do so that it becomes unavoidable. Attempting to wrap the older API calls into what we now need may be impossible to do cleanly. Rest assured, I&#8217;ll be doing a complete review of the API before pushing an RC, but unfortunately there have been a few required changes.</p>
<p>The key change that prompted this was the overwhelming need to run RazorEngine in parallel/multi-threaded scenarios. Because of how RazorEngine v2 was laid out under the hood, there were a number of mistakes that were made in its design, and thread-safety was a big one. Currently, attempting to run RazorEngine v2.1 in a multi-threaded way nearly always ends badly, you&#8217;ll get a hideous amount of mangled template output and/or failed compiles. This has prompted me to redesign the API to support multi-threaded scenarios natively.</p>
<p>This key change is breaking, and there a few other changes which have required a redesign. We&#8217;ll be reviewing the whole API and will document some migration guides nearer release date.</p>
<h3>Native Parallel Support</h3>
<p>To assist with parallel scenarios, I&#8217;ve baked in support for parsing multiple templates in parallel. This means you don&#8217;t have to worry about handling the threading model yourself, let RazorEngine&#8217;s TemplateService take care of it. Here is an example test highlighting running some templates in parallel:</p>
<pre class="prettyprint">
/// &lt;summary&gt;
/// Tests that the template service can parse multiple templates in parallel.
/// &lt;/summary&gt;
[Test]
public void TemplateService_CanParseMultipleTemplatesInParallel_WitNoModels()
{
    using (var service = new TemplateService())
    {
        const string template = "&lt;h1&gt;Hello World&lt;/h1&gt;";
        var templates = Enumerable.Repeat(template, 10);

        var results = service.ParseMany(templates, true);

        Assert.That(templates.SequenceEqual(results), "Rendered templates do not match expected."); 
    }
}
</pre>
<p>Obviously this is a trivial example, there are a number of overloads for the ParseMany method which supports scenarios with single templates/many models, many-templates/many models, etc. The parallelism is provided by PLINQ, and the execution of which can be customised by providing your own implementation of the new IParallelQueryPlan interface.</p>
<p>This is not to say you can&#8217;t use your own threading model, or even the threadpool. If you want to pop over to GitHub you can find some example tests of running a TemplateService in parallel scenarios. A future blog post will cover this in more depth.</p>
<h3>Unit Test Support</h3>
<p>At first I found it hard to quantify what would be considered a plausible test case. Originally we were simply providind a wrapper around the Razor parser, so most unit tests would only be testing the parser itself. As RazorEngine has evolved, a need has arrisen to provide a suite of tests that prove the API.</p>
<p>Currently I am using NUnit as the test framework, but I would imagine I will push up some sample tests using alternatives. This is important, as unit testing was a key area of support we were lacking in v2.1. There is a whole host of tests on GitHub currently, as these will expand as we introduce more features and capture more test scenarios.</p>
<h3>Template Isolation</h3>
<p>Razor was built around a neat parsing technology, and a code generation framework. Under the hood, your templates are being parsed, and compiled into executable class instances. Each template we generate is compiled into its own assembly, and subsequently loaded into memory. If you are using RazorEngine in volume  you&#8217;ll notice that the memory footprint of your app will increase, because we do not have the ability to unload assemblies from the primary AppDomain.</p>
<p>In v3, we&#8217;ve introduced a new template service, the IsolatedTemplateService that supports the parsing of templates in a child AppDomain. Now, there are some limitations on what can be parsed, essentially at the moment there is no support for anonymous or dynamic models, and also any models that you do want parsed must be serialisable (for cross-domain communication).</p>
<p>Here is an example test of using the IsolatedTemplateService:</p>
<pre class="prettyprint">
/// &lt;summary&gt;
/// Tests that a simple template with a model can be parsed.
/// &lt;/summary&gt;
[Test]
public void IsolatedTemplateService_CanParseSimpleTemplate_WithComplexSerialisableModel()
{
    using (var service = new IsolatedTemplateService())
    {
        const string template = "&lt;h1&gt;Hello @Model.Forename&lt;/h1&gt;";
        const string expected = "&lt;h1&gt;Hello Matt&lt;/h1&gt;";

        var model = new Person { Forename = "Matt" };
        string result = service.Parse(template, model);

        Assert.That(result == expected, "Result does not match expected: " + result);
    }
}
</pre>
<p>The basic example is virtually identical to how you would instantiate a normal TemplateService, we wanted to make it easy to spin up instances in template services. A future blog post will detail AppDomain isolation more.</p>
<h3>Automatic Text Encoding</h3>
<p>Like ASP.NET MVC&#8217;s Razor implementation, we wanted to include automatic text encoding in the base framework. As the majority of use cases are based around the use of HTML, we&#8217;ve defaulted the default text encoding for values as Html-encoded. We also support raw-encoding (i.e. raw text) also, as well as a native Raw method for rendering out raw text in an Html-encoded template.
<p>There is still a lot more to come, I hope to introduce more extensibility points to allow developers to plug more directly into the pipeline. Let me know your thoughts!</p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473&amp;title=An+early+look+at+RazorEngine+v3" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473&amp;title=An+early+look+at+RazorEngine+v3" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473&amp;title=An+early+look+at+RazorEngine+v3" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473&amp;headline=An+early+look+at+RazorEngine+v3" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=An+early+look+at+RazorEngine+v3&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=An+early+look+at+RazorEngine+v3&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=An+early+look+at+RazorEngine+v3&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=An+early+look+at+RazorEngine+v3&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=An+early+look+at+RazorEngine+v3&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473&amp;title=An+early+look+at+RazorEngine+v3&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D473" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&#038;p=473</wfw:commentRss>
		<slash:comments>52</slash:comments>
		</item>
		<item>
		<title>A Tale of Epic Epicness&#8230;</title>
		<link>http://www.fidelitydesign.net/?p=415</link>
		<comments>http://www.fidelitydesign.net/?p=415#comments</comments>
		<pubDate>Wed, 14 Sep 2011 19:03:02 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[clr]]></category>
		<category><![CDATA[razor]]></category>
		<category><![CDATA[razorengine]]></category>
		<category><![CDATA[razorenginelite]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sqlclr]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=415</guid>
		<description><![CDATA[Using dynamically compiled assemblies generated by Razor using Sql Server CLR stored procedures.]]></description>
			<content:encoded><![CDATA[<h2>A tale of epic epicness&#8230;</h2>
<h5>An adventurous attempt at twisting Razor and abusing Sql Server</h5>
<p>I have many hair-brained ideas, but none as mental as this one. I wanted to introduce the power of Razor to Sql Server, to allow for database-level template parsing! You&#8217;re probably asking what the hell I was thinking, but to understand fully I need to explain a few things about our corporate network migration, and the limitations it now provides.</p>
<p>As part of a large migration from our smaller network to a larger, globally managed network, a lot of new restrictions were put in place as to what applications and services can or can&#8217;t do. The biggest issue was that we can no longer send SMTP emails, only approved services can do <img src='http://www.fidelitydesign.net/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> . Also, the sheer volume of logging/error emails being despatched has slowly been getting out of hand for a while now &#8211; so we were looking to introduce a centralised logging mechanism in a database, which handles throttling and esclation of logging data where required. Updating our existing applications/services to use this new logging tool is easy&#8230; we just take out the email logger, and plug in our shiny new database logger (thanks <a href="http://geekswithblogs.net/cskardon/Default.aspx" target="_blank">Chris</a> and <a href="http://blog.andyrobinson.com/" target="_blank">Andy</a>!). </p>
<p>The database would be controlling how often items are reported, so it would need the ability to create the html emails we despatch. Different applications require and report different information, so it was important to me to provide a flexible templating solution for whatever is reported. And thats when I considered Razor.</p>
<p>Now, there are a number of challenges which will cause this dream to be a complete failure, and these include (but are not limited to)</p>
<ul>
<li>Razor is a .NET 4.0 assembly, and Sql Server 2008 supports .NET 3.5</li>
<li>Compiling dynamic assemblies and loading them on Sql Server using Assembly.Load() fails</li>
</ul>
<p>So here&#8217;s what I did&#8230;</p>
<h3>Backporting System.Web.Razor</h3>
<p>The first challenge that had to be overcome was the initial issue with the System.Web.Razor library. Razor was introduced with ASP.NET MVC 3, which of course is a .NET 4.0 assembly. To enable us to even consider using Razor on Sql Server we have to acknowledge that Sql Server 2008 (which was my target version) supports up to .NET 3.5 (with the .NET 2.0 runtime). This means the standard release System.Web.Razor.dll assembly would not work at all. We need to somehow backport this to .NET 3.5.</p>
<p>Luckily, the source code for the library is available at the <a href="http://aspnet.codeplex.com/releases/view/58781" target="_blank">ASP.NET codeplex site</a> for us to abuse. First thing first, change the project target (to .NET 3.5 Client Profile) and then try to compile. Whoa, as expected a whole host of errors. Missing ISet&lt;T&gt;? No Tuple&lt;T1, T2&gt;?, no Task&lt;T&gt;? Lots to try and fix. Let&#8217;s take them one step at a time&#8230;</p>
<h4>Fixing ISet&lt;T&gt;</h4>
<p>The generic ISet&lt;T&gt; interface was introduced in as part of the .NET 4.0 BCL, and doesn&#8217;t have a counterpart in the .NET 3.5 BCL. But, the standard HashSet&lt;T&gt; does exist. Simple fix, replace all instances of ISet&lt;string&gt; with HashSet&lt;string&gt;.</p>
<h4>Fixing Tuple&lt;T1, T2&gt;</h4>
<p>The ordered set type, Tuple was also first introduced as part of .NET 4.0. This was a quick type to chuck together:</p>
<pre class="prettyprint">
public class Tuple&lt;T1, T2&gt;
{
    private readonly T1 _t1;
    private readonly T2 _t2;

    internal Tuple(T1 t1, T2 t2)
    {
        _t1 = t1;
        _t2 = t2;
    }

    public T1 Item1 { get { return _t1; } }
    public T2 Item2 { get { return _t2; } }
}

public class Tuple
{
    public static Tuple&lt;T1, T2&gt; Create&lt;T1, T2&gt;(T1 t1, T2 t2)
    {
        return new Tuple&lt;T1, T2&gt;(t1, t2);
    }
}
</pre>
<h4>Fixing Task&lt;T&gt;</h4>
<p>Gah, the Task type&#8230; I don&#8217;t know enough about how it works internally to build a new Task type from scratch. After a bit of googling you can uncover the lineage of that particular type (Task Parallel Library), and a version comes bundled with the Reactive Extensions project. When Reactive was being developed, it was still pre .NET 4.0, so they were actively targeting .NET 3.5. This is good, it allows us to install the v1.0.2856.0 (this is important!) version of Rx for .NET 3.5 (you can find it <a href="http://www.microsoft.com/download/en/details.aspx?id=24940" target="_blank">here</a>), and grab the System.Threading.dll assembly from C:\Program Files\Microsoft Cloud Programmability\Reactive Extensions\v1.0.2856.0\Net35. Add that as a reference to the project.</p>
<h4>Other small fixes&#8230;</h4>
<p>There are a few other fixes which you need to tackle, firstly String.IsNullOrWhiteSpace, and the Enum.HasFlag methods which don&#8217;t currently exist.. They are pretty easy to fix&#8230; and also StringBuilder.Clear. I wrapped all these up in a simple extension class:</p>
<pre class="prettyprint">
static class Extensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        return (string.IsNullOrEmpty(value)) || (string.IsNullOrEmpty(value.Trim()));
    }

    public static void Clear(this StringBuilder builder)
    {
        builder.Length = 0;
    }

    public static bool HasFlag(this PartialParseResult result, PartialParseResult flag)
    {
        return ((result &#038; flag) == flag);
    }

    public static bool HasFlag(this RecoveryModes modes, RecoveryModes flag)
    {
        return ((modes &#038; flag) == flag);
    }
}
</pre>
<p>Once we&#8217;ve updated any method calls, we can try compiling again, and hazaah! We have now backported System.Web.Razor to .NET 3.5. There are oppotunities here for future projects, potentially including backporting the MVC RazorViewEngine to .NET 3.5 (any takers?) and also a .NET 3.5 version of the <a href="http://razorengine.codeplex.com" target="_blank">RazorEngine</a> to target those scenarios where you can&#8217;t actually move on to using .NET 4.0 just yet (and believe me, sadly there are many!).</p>
<h3>Shrinking RazorEngine for Sql Server</h3>
<p>The RazorEngine project (current release v2 &#8211; v3 is still in the works, I just tend to get sidetracked with wacky ideas&#8230;) has been a great project to work on, from its inception (thanks Ben <a href="http://www.buildstarted.com">@BuildStarted</a>) to where we are with it now. The only downside to it in this instance is that it is a bit complex to configure. What we need to do, is create a streamlined version of it. Now, Ben (@BuildStarted) had already done something similar (<a href="https://github.com/Buildstarted" target="_blank">Git</a>) when he was assisting with the awesome <a href="https://github.com/martinrue/Tinyweb" target="_blank">TinyWeb</a> Razor View Engine. I took that as a starting point, and put together a severly cut down verison of RazorEngine (hereby called RazorEngineLite) that focused purely on the C# language and Html markup. No template isolation, no anonymous and dynamic types (which we couldn&#8217;t support on .NET 3.5 anyways). It&#8217;s a real barebones RazorEngine release. What I did want to do though, is I wanted to look ahead at how I might introduce a caching mechanism for templates that might take advantage of our database level access.</p>
<h4>Introducing the ITemplateCache</h4>
<p>RazorEngineLite has support for a dual-level caching mechanism. The Runner type that is included uses a RunnerCache type which is an in-memory cache. This is the primary location that RazorEngineLite will look for previously compiled template types. If the template type has not been previously cached, it will search through a possible series of second-level caching mechanims to try and grab an instance. The reason I wanted to support this, is to allow compiled types to be pushed back to the database, so in scenarios where the database is taken offline (or simply the AppDomain unloaded), when it starts again, it doesn&#8217;t have to recompile the template, it can just grab the cache details.</p>
<p>The baseline RazorEngineLite assembly bundles the default ITemplateCache instance which is automatically instantiated by the Runner type. Libraries can pass in their own instances to provide the second-level cache sources.</p>
<p>Also, like its v3 big brother, the caching mechanism supports a hashcode operation. Essentially when a template is cached, the current hashcode is cached alongside it. Should the template content change when we call to parse it again, the cached item will be invalidated (as the new and old hashcodes will be different) &#8211; this prompts a new compilation and a re-caching of the updated type.</p>
<p>We do some other peformance improvements too, and an idea spun from our codeplex project has evolved into us caching constructor delegates, so when we actually want to spin up new instances of our templates, we can just re-use our delegates instead. This is all handled by our TemplateCacheItem type:</p>
<pre class="prettyprint">
public class TemplateCacheItem
{
    public int HashCode { get; private set; }
    public Type Type { get; private set; }
    public Func&lt;ITemplate&gt; Factory { get; private set; }

    public TemplateCacheItem(int hashCode, Type type)
    {
        HashCode = hashCode;
        Type = type;

        CreateFactory();
    }

    private void CreateFactory()
    {
        var ctor = Type.GetConstructor(new Type[0]);

        Factory =  Expression.Lambda&lt;Func&lt;ITemplate&gt;&gt;(
            Expression.New(ctor)).Compile();
    }
}
</pre>
<h3>The Sql Server Mountain</h3>
<p>Right, here is where it gets really interesting. The Sql CLR is a sandboxed runtime that runs within Sql Server. Assemblies can be hosted by Sql Server per database, and the AppDomain in which they run is per owner. There are a number of restrictions to what you can and can&#8217;t do with hosted assemblies, and the SQL CLR sandbox is very good enforcing that.</p>
<p>When you register assemlies, you do so through the CREATE ASSEMBLY command, and you specify the permission set the assembly will conform to. Sql Server will verify the integrity of the assembly and ensure that it conforms the requirements of the requested permission set (SAFE, EXTERNAL ACCESS and UNSAFE). Using SAFE wouldn&#8217;t work for what we want to do, as we&#8217;re going to need to access the file system. Attempting to register our assembly with EXTERNAL ACCESS fails, as it doesn&#8217;t like static fields that are not marked as read-only (I did look to change these, but stumbled at the System.Threading.dll assembly, which would need to be recompiled&#8230;). This leaves us with UNSAFE.</p>
<p>Before we start registering anything, we need to make sure that we&#8217;ve done some additional configuration:</p>
<pre class="prettyprint">
ALTER DATABASE [ErrorLogging] SET TRUSTWORTHY ON;
sp_configure 'clr enabled', 1
RECONFIGURE
</pre>
<p><em>Quick sidebar: Instead of registering all three assemblies (RazorEngineLite, System.Web.Razor and System.Threading, I opted to ILMerge them into a single assembly, RazorEngineLite.Merged.dll)</em></p>
<pre class="prettyprint">
CREATE ASSEMBLY [RazorEngineLite]
AUTHORIZATION [ErrorLoggingClient]
FROM 'C:&#92;CLR&#92;RazorEngineLite.Merged.dll'
WITH PERMISSION_SET = UNSAFE
</pre>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2011/09/AddReference.jpg"><img src="http://www.fidelitydesign.net/wp-content/uploads/2011/09/AddReference-300x252.jpg" alt="" title="AddReference" width="300" height="252" class="alignnone size-medium wp-image-455" /></a></p>
<p>When the assembly is registered it is exposed to any SQL CLR projects that target the database. Our ErrorLogging project is one such project, so I can now add a reference to our hosted assembly.</p>
<p>Now we are in a position to try and start using Razor, but immediately we are thwarted. Firstly, we can&#8217;t add our referenced assembly to the compiler operation as the C# compiler expects an absolute path to the assembly so we can compile our dynamic templates, and after that, we can&#8217;t use Assembly.Load() as its explicitly forbidden (even when using the UNSAFE permission set). Frowning face.</p>
<h4>Referencing our assemblies for compilation</h4>
<p>The C# compiler requires explicit references to non GAC&#8217;d assemblies when it is building the metadata of a new assembly. Our hosted assemblies exist in Sql Server, so we can&#8217;t actually provide a folder path to them in their current state. What I did, was to write out the hosted assemblies back to the file system, and then reference them explicitly via the compiler. The first time our CLR stored procedure is accessed, the static constructor of it&#8217;s parent type enforces that we grab any hosted assemblies (that are user defined) and writes them back out:</p>
<pre class="prettyprint">
CREATE PROCEDURE [re].[GetHostedAssemblies]
AS
BEGIN
	SELECT a.[name] AS [HostedName], a.[clr_name] AS [AssemblyName], f.[name] as [Path], f.[content] as [Content]
	FROM sys.assemblies a INNER JOIN sys.assembly_files f ON a.[assembly_id] = f.assembly_id
	WHERE a.is_user_defined = 1
END
</pre>
<pre class="prettyprint">
private static void EnsureHostedAssemblies()
{
    if (!Directory.Exists(_referenceDirectory))
        Directory.CreateDirectory(_referenceDirectory);

    using (var conn = new SqlConnection("Context Connection = true"))
    {
        conn.Open();

        using (var command = new SqlCommand("re.GetHostedAssemblies", conn))
        {
            command.CommandType = CommandType.StoredProcedure;

            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    string filename = (string)reader["Path"];
                    if (filename.Contains("&#92;&#92;"))
                        filename = filename.Substring(filename.LastIndexOf('&#92;&#92;') + 1);

                    if (!filename.Contains("."))
                        filename += ".dll";

                    byte[] data = (byte[])reader["Content"];
                    using (var writer = new BinaryWriter(new FileStream(Path.Combine(_referenceDirectory, filename), FileMode.Create, FileAccess.ReadWrite)))
                    {
                        writer.Write(data);
                    }
                }
            }
        }
    }
}
</pre>
<p>This will pick up any assemblies that are hosted and defined by us, therefore, our RazorEngineLite.Merged assembly, and also the library we are currently debugging with Visual Studio (<em>which incidentally is registered without a .dll suffix, which is why the code checks for a missing file extension</em>). We build a list of these assemblies and pass them back into the RazorEngineLite&#8217;s Compiler type so we can manually reference our required assemblies.</p>
<h4>Loading dynamic assemblies in Sql Server</h4>
<p>One of the biggest problems with this whole plan of mine is that I didn&#8217;t realise that I couldn&#8217;t use Assembly.Load() anywhere in my code. Sql Server enforces that we can&#8217;t use this, even with our UNSAFE permission set. Thats a spanner in the works! My workaround for this feels dirty, but actually works really well. There are two parts to this workaround. Firstly, after we compile the dynamic assembly, we need to ensure we register that assembly with Sql Server. I call a procedure in my database which does this for me:</p>
<pre class="prettyprint">
CREATE PROCEDURE [re].[CreateAssembly]
	@name VARCHAR(1000),
	@path VARCHAR(MAX)
AS
BEGIN
	DECLARE @sql NVARCHAR(MAX)
	SET @sql = N'CREATE ASSEMBLY [' + @name + '] AUTHORIZATION [ErrorLoggingClient] FROM ''' + @path + ''' WITH PERMISSION_SET = SAFE';

	EXECUTE sp_executesql @sql;
END
</pre>
<p>By setting the generated assembly to be finalised on disk instead of memory, we now have a dynamically compiled assembly, which we can register with Sql Server before we attempt to load it.</p>
<p>Next, instead of explicity using Assembly.Load() (which we are indirectly calling when we access the CompiledAssembly property of the CompilerResults type [ref: RazorEngineLite's Compiler type]), we can make use of Type.GetType(&#8230;) but pass in the fully qualified assembly name of the type.</p>
<pre class="prettyprint">
string typeName = "RazorEngineLite.Dynamic." + name + ", " + name + ", version=0.0.0.0, culture=neutral, publickeytoken=null, processorarchitecture=msil";
Type type = Type.GetType(typeName);
</pre>
<p>When the AppDomain tries to resolve that type, it will find it, because the owning assembly has already been registered. No Assembly.Load(), just pure awesomenous!</p>
<p>Let&#8217;s look at an example:</p>
<pre class="prettyprint">
[SqlProcedure]
public static int TestCompile(string name, string template, ref string result)
{
    try
    {
        var person = new Person { Name = "Matt", Age = 27 };
        var runner = new Runner(GetReferenceAssemblies(), CreateAssembly, new SqlTemplateCache());

        result = runner.Parse(name, template, person);

        return 0;
    }
    catch (Exception ex)
    {
        SqlContext.Pipe.Send(ex.Message);
        SqlContext.Pipe.Send(ex.StackTrace);

        result = null;
        return -1;
    }

}
</pre>
<p>In the above sample CLR procedure, we&#8217;re creating an instance of our model, Person, and creating a new Runner instance. The Runner instance will call to the Compiler to create the associated template, passing in our referenced assemblies, and a callback delegate which is actioned when we have created the dynamic assembly (this is the point we register it with Sql Server). We get our parsed template result back, merged with our model information (ala Razor), and return:</p>
<pre class="prettyprint">
DECLARE @result VARCHAR(MAX)

EXEC dbo.TestCompile 'test', 'Hello @Model.Name', @result OUTPUT

PRINT @result
</pre>
<p>Which results in:</p>
<pre class="prettyprint">
Hello Matt
</pre>
<h4>Adding a second-level cache</h4>
<p>I mentioned previously that the RazorEngineLite project supports a dual-level cache mechanism. Well, in this use case, I wanted to take advantage of Sql Server to provide an additional caching mechanism. The reason being, is that if the AppDomain is unloaded and restarted, there is no real point in recompiling a template that has already been registered with Sql Server. To support this second-level cache, I created a SqlTemplateCache type:</p>
<pre class="prettyprint">
public class SqlTemplateCache : ITemplateCache
{
    public void Add(string name, TemplateCacheItem item)
    {
        if (string.IsNullOrEmpty(name) || item == null)
            return;
            
        using (var conn = new SqlConnection("Context Connection = true"))
        {
            conn.Open();

            using (var command = new SqlCommand("re.Add", conn))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@name", name);
                command.Parameters.AddWithValue("@hashCode", item.HashCode);
                command.Parameters.AddWithValue("@typeName", item.Type.AssemblyQualifiedName);
                command.Parameters.AddWithValue("@assembly", item.Type.Assembly.GetName().Name);

                command.ExecuteNonQuery();
            }
        }
    }
    
    public TemplateCacheItem Find(string name)
    {
        if (string.IsNullOrEmpty(name))
            return null;

        using (var conn = new SqlConnection("Context Connection = true"))
        {
            conn.Open();

            using (var command = new SqlCommand("re.Find", conn))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@name", name);

                using (var reader = command.ExecuteReader())
                {
                    if (!reader.Read())
                        return null;

                    int hashCode = (int)reader["HashCode"];
                    string typeName = (string)reader["TypeName"];

                    Type type = Type.GetType(typeName);

                    if (type == null)
                        return null;

                    return new TemplateCacheItem(hashCode, type);
                }
            }
        }
    }
}
</pre>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2011/09/TemplateCache.jpg"><img src="http://www.fidelitydesign.net/wp-content/uploads/2011/09/TemplateCache-300x42.jpg" alt="" title="TemplateCache" width="300" height="42" class="alignnone size-medium wp-image-457" /></a></p>
<p>We store the type information for the registered template, so when an initial check for a compiled assembly that won&#8217;t be in memory, it can check this table for the secondary cache information, get the Type, and then promote it to the primary cache (in memory).</p>
<h3>Wrapping it Up</h3>
<p>This was probably my biggest challenge yet, and I&#8217;m glad I&#8217;ve got it done. But before you even consider it&#8217;s actual application in production use, a lot of time needs to be spent ensuring the code is performant and most importantly.. safe. Ensuring the stability of Sql Server should always be a priority when you start integrating CLR procedures into your database platform.</p>
<p>If you like what you see, heck if you don&#8217;t like what you see, I welcome any and all feedback!</p>
<p>For those interested in seeing it in action, the project(s) are attached, but you&#8217;ll need to do some work to prepare your database to support it.</p>
<p><a href='http://www.fidelitydesign.net/wp-content/uploads/2011/09/RazorEngineLite.zip'>RazorEngineLite/System.Web.Razor</a> &#8211; after build, using \Build\Merge.bat to ILMerge assemblies into RazorEngineLite.Merged.dll<br />
<a href='http://www.fidelitydesign.net/wp-content/uploads/2011/09/ErrorLogging.zip'>ErrorLogging</a><br />
<a href='http://www.fidelitydesign.net/wp-content/uploads/2011/09/ErrorLoggingSql.txt'>ErrorLoggingSql</a> &#8211; baseline structure &#8211; make sure you create database, user and schema ([re]) first.</p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415&amp;title=A+Tale+of+Epic+Epicness..." ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415&amp;title=A+Tale+of+Epic+Epicness..." ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415&amp;title=A+Tale+of+Epic+Epicness..." ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415&amp;headline=A+Tale+of+Epic+Epicness..." ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=A+Tale+of+Epic+Epicness...&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=A+Tale+of+Epic+Epicness...&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=A+Tale+of+Epic+Epicness...&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=A+Tale+of+Epic+Epicness...&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=A+Tale+of+Epic+Epicness...&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415&amp;title=A+Tale+of+Epic+Epicness...&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D415" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&#038;p=415</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Plug and Play Services with MEF and WCF</title>
		<link>http://www.fidelitydesign.net/?p=390</link>
		<comments>http://www.fidelitydesign.net/?p=390#comments</comments>
		<pubDate>Sat, 13 Aug 2011 21:21:30 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[IIS]]></category>
		<category><![CDATA[MEF]]></category>
		<category><![CDATA[wcf]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=390</guid>
		<description><![CDATA[It&#8217;s been a while since I&#8217;ve blogged any MEF stuff, and having never blogged anything to do with WCF, I thought it could be good to share something I&#8217;ve been playing with these last few days. The Premise I&#8217;m already using MEF now in quite a few production projects, but also a lot of work [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a while since I&#8217;ve blogged any MEF stuff, and having never blogged anything to do with WCF, I thought it could be good to share something I&#8217;ve been playing with these last few days.</p>
<h3>The Premise</h3>
<p>I&#8217;m already using MEF now in quite a few production projects, but also a lot of work lately has been going in to evolve the architecture of a service bus. Consider a set of individual services hosted as seperate WCF services. The hosting architecture is all essentially the same.</p>
<p>Where does MEF fit in? What I wanted to do was build an architecture that will allow me to drop in libraries that contain WCF services, and we&#8217;ll discover them with MEF and instantiate them.</p>
<h3>The Basics</h3>
<p>To aid discovery of services via MEF, we need someway of expressing that the service is actually a service, instead of just another part. Now, typically when we are exporting a part, we would label up a part, either using a common base type, or just with an empty export:</p>
<pre class="prettyprint">
[Export]
[Export(typeof(ISomething))]
</pre>
<p>What I decided on doing, was provide a marker interface. This will allow us to select the all service parts from the container. Let&#8217;s look at the contract, and a sample service that might implement it:</p>
<pre class="prettyprint">
public interface IHostedService { }

[ServiceContract]
public interface ICalculatorService : IHostedService
{
  [OperationContract]
  int Add(int operandA, int operandB);
}
</pre>
<p>Now when we export our service, we also need a way of describing that service to our consuming types. So, that means some metadata, here&#8217;s what I&#8217;ve got:</p>
<pre class="prettyprint">
public interface IHostedServiceMetadata
{
  string Name { get; }
  Type ServiceType { get; }
}
</pre>
<p>The metadata interface is quite simplistic, giving us a way of selecting the service via a name. The ServiceType property I&#8217;ll come to a bit later. Now we can wrap up the export and the metadata, by combining them into a single export attribute:</p>
<pre class="prettyprint">
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true),
 MetadataAttribute]
public class ExportServiceAttribute : ExportAttribute, IHostedServiceMetadata
{
  public ExportServiceAttribute(string name, Type serviceType)
    : base(typeof(IHostedService))
  {
    Name = name;
    ServiceType = ServiceType;
  }
  
  public string Name { get; private set; }
  public Type ServiceType { get; private set; }
}
</pre>
<h3>The Imports</h3>
<p>Now, on the other side of the fence, we need a way of importing our types, but rather than require us to manually create instances of types, it could be good to have MEF automatically create instances of the ServiceHost that actually hosts the service.</p>
<p>MEF is extensible by design, and a core part of that is the ExportProvider model. ExportProvider instances are used to match ImportDefinitions with appropriate parts. So in this sense, we can create an ExportProvider that will automatically create ServiceHost instances.</p>
<pre class="prettyprint">
public class ServiceHostExportProvider : ExportProvider
{
  private static readonly string MatchContractName = AttributedModelServices
    .GetContractName(typeof(ExportServiceHost));
    
  public CompositionContainer SourceContainer { get; set; }
  
  protected override IEnumerable&lt;Export&gt; GetExportsCore(
    ImportDefinition importDefinition,
    AtomicComposition atomicComposition)
  {
    if (importDefinition.ContractName.Equals(MatchContractName))
    {
      var exports = SourceContainer
        .GetExports&lt;IHostedService, IHostedServiceMetadata&gt;();
        
      Func&lt;IHostedServiceMetadata, Export&gt; factory = 
        m =&gt; new Export(MatchContractName,
          () =&gt; ExportServiceHostFactory.CreateExportServiceHost(SourceContainer, m));
          
      switch (importDefinition.Cardinality)
      {
        case ImportCardinality.ExactlyOne:
          {
            var export = exports.Single();
            return new[] { factory(export.Metadata) };
          }
        case ImportCardinality.ZeroOrOne:
          {
            var export = exports.SingleOrDefault();
            return (export == null)
              ? Enumerable.Empty&lt;Export&gt;()
              : new[] { factory(export.Metadata) };
          }
        case ImportCardinality.ZeroOrMore:
          {
            return exports.Select(e =&gt; factory(e.Metadata));
          }
      }
    }
    
    return Enumerable.Empty&lt;Export&gt;();
  }
}
</pre>
<p>Now, remember I added that ServiceType property to our metadata export, the reason being is we need that to create or service, and its not easy to grab Type information from MEF, because MEF is designed for the discovery of unknown parts (in the default programming model). So our ServiceType property allows us to express the actual type before we&#8217;ve created the instance.</p>
<p>The other issue we have, is the design of the ServiceHost type that System.ServiceModel provides. ServiceHost allows us to pass a Singleton object, or a Type instance. MEF supports the creation of types with complex constructors with dependency injection, but the ServiceHost(Type) constructor enforces a public default constructor. What I decided to do, is create a custom service host type, the ExportServiceHost which will support custom creation of objects via MEF.</p>
<p>The ExportServiceHost type extends ServiceHostBase, with the main requirement being to initialise the ServiceDescription which actually describes our service:</p>
<pre class="prettyprint">
  protected override ServiceDescription CreateDescription(
    out IDictionary&lt;string, ContractDescription&gt; implementedContracts)
  {
    var sd = new ServiceDescription { ServiceType = Meta.ServiceType };
    
    implementedContracts = GetContracts(Meta.ServiceType)
      .ToDictionary(cd =&gt; cd.ConfigurationName, cd =&gt; cd);
      
    var endpointAttributes = GetEndpoints(Meta.ServiceType);
    
    foreach (var cd in implementedContracts.Values)
    {
      foreach (var endpoint in GetServiceEndpoints(endpointAttributes, meta, cd))
        sd.Endpoints.Add(endpoint);
    }
    
    var serviceBehaviour = EnsureServiceBehavior(sd);
    serviceBehaviour.InstanceContextMode = InstanceContextMode.PerSession;
    
    foreach (var endpointAttribute in endpointAttributes)
      endpointAttribute.UpdateServiceDescription(sd);
      
    AddBaseAddresses(sd.Endpoints);
    return sd;
  }
</pre>
<p>There is no wiring up at this point, we need to extend WCF with an IInstanceProvider and a behaviour to link it through. We add this through our factory class:</p>
<pre class="prettyprint">
internal static class ExportServiceHostFactory
{
  public static ExportServiceHost CreateExportServiceHost(
    CompositionContainer container,
    IHostedServiceMetadata meta)
  {
    var host = new ExportServiceHost(meta);
    host.Description.Behaviors.Add(
      new ExportServiceBehavior(container, meta.Name));
      
    return host;
  }
}
</pre>
<p>One of the key parts of this implementation is how we describe our endpoints.</p>
<h3>The Endpoints</h3>
<p>One of the early pain points when learning WCF is getting used to configuration of endpoints and bindings. With the idea of dynamic services, we should try and rely on configuration less. While this could be objectional, it isn&#8217;t too different from say, a fluent configuration API.</p>
<p>What we can take advantage of is the ability to decorate our service implementation with attributes which define both endpoints/bindings. Now, I imaging we can leverage a base attribute with common endpoint properties, and then specialise for our different communication schemes, http, tcp, etc.</p>
<pre class="prettyprint">
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public abstract class EndpointAttribute : Attribute
{
  protected EndpointAttribute(int defaultPort)
  {
    Port = defaultPort;
  }
  
  public string BindingConfiguration { get; set; }
  public string Path { get; set; }
  public int Port { get; set; }
  
  internal abstract ServiceEndpoint CreateEndpoint(
    ContractDescription description,
    IHostedServiceMetadata meta);
    
  protected virtual Uri CreateUri(string scheme, IHostedServiceMetadata)
  {
    var builder = new UriBuilder(scheme, "localhost", Port, Path ?? meta.Name);
    return builder.Uri;
  }
}
</pre>
<p>So, let&#8217;s have a look at a specialised endpoint attribute:</p>
<pre class="prettyprint">
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class HttpEndpointAttribute : EndpointAttribute
{
  private const int DefaultPort = 50001;
  
  public HttpEndpointAttribute() : base(DefaultPort) 
  {
    EnableGet = true;
  }
  
  public HttpBindingType BindingType { get; set; }
  public bool UseHttps { get; set; }
  public bool EnableGet { get; set; }
  
  internal override ServiceEndpoint CreateEndpoint(
    ContractDescription description,
    IHostedServiceMetadata meta)
  {
    var uri = CreateUri((UseHttps) ? "https" : "http", meta);
    var address = new EndpointAddress(uri);
    
    var binding = CreateBinding(BindingType);
    return new ServiceEndpoint(description, binding, address);
  }
  
  protected virtual Binding CreateBinding(HttpBindingType bindingType)
  {
      switch (bindingType)
      {
          case HttpBindingType.BasicHttp:
              return (BindingConfiguration == null)
                         ? new BasicHttpBinding()
                         : new BasicHttpBinding(BindingConfiguration);
          case HttpBindingType.WSHttp:
              return (BindingConfiguration == null)
                         ? new WSHttpBinding()
                         : new WSHttpBinding(BindingConfiguration);
          default:
              throw new ArgumentNullException("Unsupported binding type: " + bindingType);
      }
  }
}
</pre>
<h3>The Examples</h3>
<p>Right, so let&#8217;s put this all together, using our sample contract we defined earlier:</p>
<pre class="prettyprint">
[ExportService("SimpleCalculator", typeof(SimpleCalculatorService)), HttpEndpoint]
public class SimpleCalculatorService : ICalculatorService
{
  public int Add(int operandA, int operandB)
  {
    return (operandA + operandB);
  }
}
</pre>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2011/08/SimpleCalculatorService.png"><img src="http://www.fidelitydesign.net/wp-content/uploads/2011/08/SimpleCalculatorService-300x185.png" alt="" title="SimpleCalculatorService" width="300" height="185" class="alignnone size-medium wp-image-403" /></a></p>
<p>As you can see, the idea is simple, you can focus on your service implementation, and the MEF architecture just gets out of the way. To simply it further, we can change our architecture to automatically create a HttpEndpointAttribute where no EndpointAttribute instances are defined.</p>
<p>A more advanced example, let&#8217;s add in support for a complex constructor:</p>
<pre class="prettyprint">
[ExportService("AdvancedCalculator", typeof(AdvancedCalculatorService)),
 HttpEndpoint, TcpEndpoint]
public class AdvancedCalculatorService : ICalculatorService
{
  private readonly ILogger _logger;
  
  [ImportingConstructor]
  public AdvancedCalculatorService(ILogger logger)
  {
    _logger = logger;
    _logger.Log("Created instance of AdvancedCalculatorService");
  }
  
  public int Add(int operandA, int operandB)
  {
    int result = (operandA + operandB);
    
    _logger.Log("Computing result: " + operandA + " + " + operandB + ": " + result);
    return result;
  }
}
</pre>
<p>We get the benefits of clean, testable code, and dynamic instantiation with dependency injection for our services.</p>
<h3>The Web</h3>
<p>When hosting services through IIS, the server handles requests to .svc files. To support our dynamic instantiation, we can use a derivative of <a href="http://blog.micic.ch/net/dynamic-iis-hosted-wcf-service" target="_blank">Darko&#8217;s Dynamic IIS hosted WCF Service</a> work. In which we create a custom ServiceHostFactory, and then power it through a VirtualPathProvider. Our WebServiceHostFactory is shaped like:</p>
<pre class="prettyprint">
public class WebServiceHostFactory : ServiceHostFactory
{
  private static CompositionContainer _container;
  private static readonly sync = new object();
  
  public CompositionContainer Container
  {
    get
    {
      lock (object)
      {
        return _container;
      }
    }
  }
  
  public override ServiceHostBase CreateServiceHost(
    string constructorString,
    Uri[] baseAddresses)
  {
    var meta = Container
      .GetExports&lt;IHostedService, IHostedServiceMetadata&gt;()
      .Where(e =&gt; e.Metadata.Name.Equals(constructorString, StringComparison.OrdinalIgnoreCase))
      .Select(e =&gt; e.Metadata)
      .SingleOrDefault();
      
    if (meta == null) return null;
    
    var host = new ExportServiceHost(meta, baseAddresses);
    host.Description.Behaviors.Add(
      new ExportServiceBehavior(Container, meta.Name));
      
    var contracts = meta.ServiceType
      .GetInterfaces()
      .Where(t =&gt; t.IsDefined(ServiceContractAttribute), true));
      
    EnsureHttpBinding(host, contracts);
    return host;
  }
  
  private static void EnsureHttpBinding(
    ExportServiceHost host,
    IEnumerable&lt;Type&gt; contracts)
  {
    var binding = new BasicHttpBinding();
    
    host.Description.Endpoints.Clear();
    foreach (var contract in contracts)
      host.AddServiceEndpoint(contract.FullName, binding, "");
  }
}
</pre>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2011/08/SimpleCalculatorService-IIS.png"><img src="http://www.fidelitydesign.net/wp-content/uploads/2011/08/SimpleCalculatorService-IIS-300x161.png" alt="" title="SimpleCalculatorService-IIS" width="300" height="161" class="alignnone size-medium wp-image-406" /></a></p>
<p>Now we are in a position to dynamically support WCF services through both standalone code (e.g. windows services, console apps, etc.), and also hosted code (ASP.NET). Please find the sample code attached, which includes the base code, some example services, some example hosts, and also an example client.</p>
<p>I welcome any and all feedback <img src='http://www.fidelitydesign.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><a href='http://www.fidelitydesign.net/wp-content/uploads/2011/08/FD.ServiceHost.zip'>MEF + WCF ServiceHost</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390&amp;title=Plug+and+Play+Services+with+MEF+and+WCF" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390&amp;title=Plug+and+Play+Services+with+MEF+and+WCF" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390&amp;title=Plug+and+Play+Services+with+MEF+and+WCF" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390&amp;headline=Plug+and+Play+Services+with+MEF+and+WCF" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Plug+and+Play+Services+with+MEF+and+WCF&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Plug+and+Play+Services+with+MEF+and+WCF&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Plug+and+Play+Services+with+MEF+and+WCF&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Plug+and+Play+Services+with+MEF+and+WCF&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Plug+and+Play+Services+with+MEF+and+WCF&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390&amp;title=Plug+and+Play+Services+with+MEF+and+WCF&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D390" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&#038;p=390</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Javascript + Razor == Jazor?</title>
		<link>http://www.fidelitydesign.net/?p=375</link>
		<comments>http://www.fidelitydesign.net/?p=375#comments</comments>
		<pubDate>Tue, 05 Jul 2011 22:36:15 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=375</guid>
		<description><![CDATA[I&#8217;ve been doing quite a lot with Razor lately, namely still working on RazorEngine vNext, but also reading a lot of Andrew Nurse&#8217;s blog to understand what the Razor parser is doing under the hood. Turns out, its an elegant synergy of two separate parsers, one which handles code, one which handles markup. The two [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing quite a lot with Razor lately, namely still working on <a href="http://razorengine.codeplex.com">RazorEngine</a> vNext, but also reading a lot of <a href="http://vibrantcode.com/">Andrew Nurse&#8217;s blog</a> to understand what the Razor parser is doing under the hood. </p>
<p>Turns out, its an elegant synergy of two separate parsers, one which handles code, one which handles markup. The two parsers do a little dance, and the end result, is a series of code statements that write the content of your template/page/document to an output. This in turn is compiled into a class which is executed to obtain the end result.</p>
<p>Jazor (ahem), attempts to be a faithful implementation of the Razor syntax, but built purely in javascript. The general idea would be that you could declaratively use Razor syntax in your client side templates. Let&#8217;s have a quick look:</p>
<pre class="prettyprint">
&lt;script type="text/html" id="template01"&gt;
  &lt;div&gt;Hello @model.name, you are @model.getAge() year(s) old!&lt;/div&gt;
&lt;/script&gt;
</pre>
<p>Now, let&#8217;s breakdown how it works:</p>
<h3>Synergistic ballet</h3>
<p>Andrew aptly calls this &#8220;recursive ping-pong&#8221; (read his blog post <a href="http://vibrantcode.com/blog/2010/7/5/inside-razor-part-1-recursive-ping-pong.html">here</a>), its an elegant way of breaking down a text stream into a recursive set of calls to each parser. We start off at the very top level, and make an initial call to a markup parser; when the markup parser starts reading the content, it will do so until it reaches a valid transtion point, the &#8220;@&#8221; symbol (well, there is a little more to it than that, we have to take email address, and @@ escaping into consideration). Once a valid transition point is reached, the markup parser calls the code parser, which in turn attempts to read a code block (an expression, statement, etc.).</p>
<p>The way we do this with Jazor is we have our core object, the <strong>parser</strong> which wraps a <strong>codeParser</strong> and a <strong>markupParser</strong>. The parser makes a call to the markupParser to start reading the content. and the recursive little dance begins. </p>
<h3>Generating code</h3>
<p>Much like Razor, we start generating blocks of code which we will reassemble as part of our template execution.  If we take our above example, Jazor will generate a literal block, followed by an expression, then a literal, another expression, and then a final literal, so:</p>
<pre class="prettyprint">
"n &lt;div&gt;Hello "
model.name
", you are "
model.getAge()
" year(s) old!&lt;/div&gt;n "
</pre>
<p>We need to transform this series of blocks into something runnable, thankfully, there is eval.</p>
<h3>Return of eval</h3>
<p>After we&#8217;ve done generating our template blocks, we assembly them back together as a function, which we can then eval, and run. We do this by writing the code that wraps the blocks. For the above example, the code we generate would look something like:</p>
<pre class="prettyprint">
(function(model) {
    var r = []; 
    r.push("n &lt;div&gt;Hello "); 
    r.push(model.name); 
    r.push(", you are "); 
    r.push(model.getAge()); 
    r.push(" year(s) old!&lt;/div&gt;n "); 
    return r.join(""); 
});
</pre>
<p>I&#8217;ve prettified the code for readability, but essentially we are writing a custom method, and then we evaluate that as a function object, which can be executed directly:</p>
<pre class="prettyprint">
    var func = eval(tmp); // Where tmp is our generated function code.
</pre>
<h3>Executing templates</h3>
<p>You can start running templates using the global <strong>jazor</strong> object:</p>
<pre class="prettyprint">
    var model = {
        name: "Matt",
        getAge: function() { return 27; }
    };
    var result = jazor.parse("Hello @model.name", model);
</pre>
<p>Alternatively, if you are using jQuery, you can use the $.fn.jazor method on your query object:</p>
<pre class="prettyprint">
    var result = $("#template01").jazor(model);
</pre>
<h3>What does Jazor support</h3>
<p>In this initial 0.1.0, it is really just a preview, very much unfinished. Currently we have support for most Razor syntaxes, so we have:</p>
<p>Expressions</p>
<pre class="prettyprint">
    @model.name
</pre>
<p>Code Blocks</p>
<pre class="prettyprint">
    @{
        var name = "Matt";
    }
</pre>
<p>Explicit Expressions</p>
<pre class="prettyprint">
    @(model.name)
</pre>
<p>Line parsing</p>
<pre class="prettyprint">
    @: Hello World
</pre>
<p>if, for, with, while</p>
<pre class="prettyprint">
    @for (var i in model) {
        Current: @i
    }
</pre>
<p>And we also have support for helper methods, e.g.:</p>
<pre class="prettyprint">
    @helper writeAge(age) {
        &lt;span&gt;@age&lt;/span&gt;
    }
    Hello @model.name, you are @writeAge(model.getAge()) year(s) old!
</pre>
<p>Helper methods are transformed into internal functions of our template function. E.g, the above would be transformed into:</p>
<pre class="prettyprint">
(function(model) {
  function writeAge(age) {
    var hr = [];
    hr.push("n    &lt;span&gt;");
    hr.push(age);
    hr.push("&lt;/span&gt;n");
    return hr.join("");
  }
  // etc....
});
</pre>
<p>This allows us to declaratively define template functions, just as Razor allows.</p>
<h3>What&#8217;s missing</h3>
<p>There is still quite a bit of work to do, bugs to iron out, one big glaring omission currently is support for else/else if statements, and the parser doesn&#8217;t really obey xml markup just yet, but for an initial release, I&#8217;m hoping its enough to get people interested. I&#8217;ll push it to github soon so you can start forking and hopefully get involved!</p>
<p>The script file is attached, remember, its an early work in progress! Let me know what you think <img src='http://www.fidelitydesign.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><a href='http://www.fidelitydesign.net/wp-content/uploads/2011/07/jazor-dev.0.1.0.js'>jazor-dev.0.1.0.js</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375&amp;title=Javascript+%2B+Razor+%3D%3D+Jazor%3F" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375&amp;title=Javascript+%2B+Razor+%3D%3D+Jazor%3F" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375&amp;title=Javascript+%2B+Razor+%3D%3D+Jazor%3F" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375&amp;headline=Javascript+%2B+Razor+%3D%3D+Jazor%3F" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Javascript+%2B+Razor+%3D%3D+Jazor%3F&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Javascript+%2B+Razor+%3D%3D+Jazor%3F&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Javascript+%2B+Razor+%3D%3D+Jazor%3F&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Javascript+%2B+Razor+%3D%3D+Jazor%3F&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Javascript+%2B+Razor+%3D%3D+Jazor%3F&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375&amp;title=Javascript+%2B+Razor+%3D%3D+Jazor%3F&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D375" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&#038;p=375</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Facebook-style Search using Knockoutjs and jQuery</title>
		<link>http://www.fidelitydesign.net/?p=348</link>
		<comments>http://www.fidelitydesign.net/?p=348#comments</comments>
		<pubDate>Tue, 10 May 2011 23:41:49 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[knockout]]></category>
		<category><![CDATA[mvvm]]></category>
		<category><![CDATA[tmpl]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=348</guid>
		<description><![CDATA[Facebook-style Search with Knockoutjs and JQuery I recently stumbled across Knockoutjs, a MVVM framework for Javascript that allows us to declaratively add two-way data binding to html elements with minimal markup and no tedious event registration. Now there are plenty of examples of using Knockoutjs on the project website, but what I want to see [...]]]></description>
			<content:encoded><![CDATA[<h1>Facebook-style Search with Knockoutjs and JQuery</h1>
<p>I recently stumbled across <a href="http://www.knockoutjs.com">Knockoutjs</a>, a MVVM framework for Javascript that allows us to declaratively add two-way data binding to html elements with minimal markup and no tedious event registration. Now there are plenty of examples of using Knockoutjs on the project website, but what I want to see is if I could create a Facebook style search box and results using some nifty and clean Knockoutjs code.</p>
<p>Now, Knockoutjs isn&#8217;t really concerned with the DOM manipulation and event registration of the current generation of javascript frameworks, but that is not to say that it doesn&#8217;t play nice. In fact, using Knockoutjs and jQuery together is just a dream.</p>
<h2>View Models and Bindings</h2>
<p>Our first port of call is to look at how we plan our view model. I can initially see we&#8217;re going to need something like:
<pre class="prettyprint">
var viewModel = {
  query: ko.observable(),
  results: ko.observableArray()
};
</pre>
<p>This allows us to data bind to the query property and automatically update that as our search box is changed. But the problem we currently have, is when we want to start fetching data from our server, we would have to manually update this observable with our results. To get round this, we can use a nifty extension called ko.mapping. The mapping extension allows us to define a base model and generate a view model from that, e.g.:</p>
<pre class="prettyprint">
var baseModel = {
  query: "",
  results: []
}

var viewModel = ko.mapping.fromJS(baseModel);
</pre>
<p>The mapping extension will take our base model and generate a view model with observable members within it, essentially our mapped view model works like our original view model.  What we can do now though, is when we grab results from our server, we can simple use the mapping extension to update the view model, which in turn updates our UI.</p>
<pre class="prettyprint">
var resultModel = // get from server?
ko.mapping.updateFromJS(viewModel, resultModel);
</pre>
<p>So how does this fit in with our UI?</p>
<h2>A simple html markup</h2>
<p>Our markup is pretty simple, we have a textbox, a button and a list. Chuck in a few more elements and some styling, we get a nice Facebook-style search box:</p>
<div><a href="http://www.fidelitydesign.net/wp-content/uploads/2011/05/Facebook-Search.png"><img src="http://www.fidelitydesign.net/wp-content/uploads/2011/05/Facebook-Search.png" alt="" title="Facebook-Search" width="362" height="34" class="alignnone size-full wp-image-356" /></a></div>
<pre class="prettyprint">
&lt;div class="searchBox"&gt;
  &lt;span class="searchContainer"&gt;&lt;input /&gt;&lt;button&gt;&lt;/button&gt;&lt;/span&gt;
  &lt;ul class="results"&gt;&lt;/ul&gt;
&lt;/div&gt;
</pre>
<h2>Data-binding the view model</h2>
<p>What we need to do first, is add a two-way data-binding to our input textbox, but the default binding updates our value when the change event is fired. To allow a search-as-you-type experience, we need to change this to a keyup event. We can do that with the following binding:</p>
<pre class="prettyprint">
&lt;input data-bind="value: query, valueUpdate: 'afterkeyup'" /&gt;
</pre>
<p>Now, let&#8217;s jump ahead a bit, and start looking at how our UI will get updated by our view model:</p>
<pre class="prettyprint">
(function($)
{      
  var baseModel = 
  {
    query: "",
    results: []
  };
  
  var viewModel = ko.mapping.fromJS(baseModel);
  viewModel.doSearch = function()
  {
    var $this = this;
    setTimeout(function()
    {
      var resultModel = null;
      var q = $this.query();
      if (q == "") 
      {
        resultModel = { results: [] };
        ko.mapping.updateFromJS(viewModel, resultModel);
      } 
      else
      {
        $.ajax({
          url: "json.asp",
          data: { "query": q },
          type: "GET",
          dataType: "json",
          success: function(r)
          {
            resultModel = r;
            ko.mapping.updateFromJS(viewModel, resultModel);
          }
        });
      }
    }, 1);
    
    return true;
  };

  ko.applyBindings(viewModel, $("#search").get(0));
})(jQuery);
</pre>
<p>I&#8217;ve added a function to the view model, doSearch and that is responsible for updating our results. We use jQuery&#8217;s ajax function to grab our server data (in JSON format), and then map that result straight into our view model. You&#8217;ll notice the setTimeout call, unfortunately the keypress event the doSearch function will be bound to fires before the value is updated, so we need to delay it and allow our value to update before the we try and do our search.</p>
<p>We&#8217;ve also only applied this view model in the scope of the search element, this allows us to use multiple view models in a single page, targeting different widgets.</p>
<h2>Binding events and templating the results</h2>
<p>To get it all working, we need to do a couple of things. Firstly, let&#8217;s bind our events, we do this in two places, our textbox and our button. The button will respond to the default click event, but the textbox needs to respond to keyup, so&#8230;</p>
<pre class="prettyprint">
&lt;input data-bind="value: query, valueUpdate: 'afterkeyup', event: { keyup: doSearch }" /&gt;
&lt;button data-bind="click: doSearch"&gt;&lt;/button&gt;
</pre>
<p>Using jQuery&#8217;s tmpl plugin, we can easily create client side templates, which we need for our result objects. Now, our results may look like this:</p>
<pre class="prettyprint">
results: [
  { type: "header", text: "People" },
  { type: "person", name: "Matthew Abbott", imageUrl: "..." }
]
</pre>
<p>So, in our template, we need to handle both header elements, and people elements. Let&#8217;s have a look:</p>
<pre class="prettyprint">
&lt;script type="text/html" id="resultItem"&gt;
  &lt;li class="${ type() }"&gt;
    {{if type() == "header"}}
      &lt;span data-bind="text: text"&gt;&lt;/span&gt;
    {{else}}
      &lt;a href="#"&gt;
        &lt;img src="${ imageUrl() }" /&gt;
        &lt;span class="text" data-bind="text: name"&gt;&lt;/span&gt;
      &lt;/a&gt;
    {{/if}}
  &lt;/li&gt;
&lt;/script&gt;
</pre>
<p>With that template, we add a specific class for styling purposes, based on the result type, and then fill the content using data-bound html elements. Once again, we leave the majority of our data-binding to Knockoutjs, but we let jQuery&#8217;s tmpl plugin handle our conditionals.</p>
<p>And this is how we wire it up:</p>
<pre class="prettyprint">
&lt;ul class="results" data-bind='template: { name: "resultItem", foreach: results }, visible: results().length &gt; 0'&gt;&lt;/ul&gt;
</pre>
<p>We add our data binding to the list element, specify our template name, and then we toggle the visible binding based on the number of results. Without any results present, the list will automatically be hidden, when we have results, it shows. Here is an example:</p>
<div><a href="http://www.fidelitydesign.net/wp-content/uploads/2011/05/Facebook-Result.png"><img src="http://www.fidelitydesign.net/wp-content/uploads/2011/05/Facebook-Result.png" alt="" title="Facebook-Result" width="364" height="170" class="alignnone size-full wp-image-363" /></a></div>
<p>Let me know what you think, you can have a look at the demo here: <a href="http://fidelitydesign.net/pub/index.html">http://fidelitydesign.net/pub/index.html</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348&amp;title=Facebook-style+Search+using+Knockoutjs+and+jQuery" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348&amp;title=Facebook-style+Search+using+Knockoutjs+and+jQuery" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348&amp;title=Facebook-style+Search+using+Knockoutjs+and+jQuery" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348&amp;headline=Facebook-style+Search+using+Knockoutjs+and+jQuery" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Facebook-style+Search+using+Knockoutjs+and+jQuery&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Facebook-style+Search+using+Knockoutjs+and+jQuery&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Facebook-style+Search+using+Knockoutjs+and+jQuery&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Facebook-style+Search+using+Knockoutjs+and+jQuery&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Facebook-style+Search+using+Knockoutjs+and+jQuery&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348&amp;title=Facebook-style+Search+using+Knockoutjs+and+jQuery&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D348" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&#038;p=348</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Converting String expressions to Funcs with FunctionFactory</title>
		<link>http://www.fidelitydesign.net/?p=333</link>
		<comments>http://www.fidelitydesign.net/?p=333#comments</comments>
		<pubDate>Tue, 12 Apr 2011 20:56:42 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Delegate]]></category>
		<category><![CDATA[expressions]]></category>
		<category><![CDATA[Func]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=333</guid>
		<description><![CDATA[I remember looking through some of the included VS2008 samples (here), and there is quite a nice little DynamicQuery project demonstrating the ExpressionParser demo type. It wasn&#8217;t long until I started having a play with how we could take advantage of this in code. The first step was to make a few modifications to the [...]]]></description>
			<content:encoded><![CDATA[<p>I remember looking through some of the included VS2008 samples (<a href="http://archive.msdn.microsoft.com/cs2008samples">here</a>), and there is quite a nice little DynamicQuery project demonstrating the ExpressionParser demo type. It wasn&#8217;t long until I started having a play with how we could take advantage of this in code.</p>
<p>The first step was to make a few modifications to the ExpressionParser type, namely changing access modifiers and removing the limitation on using a fixed list of types. Where do we make these changes? Well, first step, let&#8217;s make it public.</p>
<pre class="prettyprint">
public class ExpressionParser
{
  // ...
}
</pre>
<p>Next, let&#8217;s remove the constraint on predefined types, within the ParseMemberAccess method:</p>
<pre class="prettyprint">
Expression ParseMemberAccess(Type type, Expression instance)
{
  // ...
        switch (FindMethod(type, id, instance == null, args, out mb))
        {
            case 0:
                throw ParseError(errorPos, Res.NoApplicableMethod,
                    id, GetTypeName(type));
            case 1:
                MethodInfo method = (MethodInfo)mb;
                //if (!IsPredefinedType(method.DeclaringType)) // Comment out this line, and the next.
                    //throw ParseError(errorPos, Res.MethodsAreInaccessible, GetTypeName(method.DeclaringType));
                if (method.ReturnType == typeof(void))
                    throw ParseError(errorPos, Res.MethodIsVoid,
                        id, GetTypeName(method.DeclaringType));
                return Expression.Call(instance, (MethodInfo)method, args);
            default:
                throw ParseError(errorPos, Res.AmbiguousMethodInvocation,
                    id, GetTypeName(type));
        }
  // ...
}
</pre>
<p>Now we are in a position to start flexing our function musicles. But first, we need to understand how it all works.</p>
<p>ExpressionParser can take a string expression and convert it to an Expression, which we can in turn create a Delegate for, so given the expression &#8220;(a + b)&#8221;, if we know the operand types, and the return type, we can create a Delegate. Let&#8217;s see how:</p>
<pre class="prettyprint">
var @params = new[] 
              { 
                Expression.Parameter(typeof(int), "a"),
                Expression.Parameter(typeof(int), "b")
              };
              
var parser = new ExpressionParser(@params, "(a + b)", null);
var @delegate = Expression.Lambda(parser.Parse(typeof(int)), @params).Compile();
</pre>
<p>With that small bit of code, we&#8217;ve created some parameter expressions, named to match the operands in our expression, and then we use the ExpressionParser to create an Expression instance that represents our string expression. The next step was to compile the Lamda of that expression into an executable Delegate.</p>
<p>The nice thing about the Delegate type, is that it is castable to Func<> instances and makes using the code easy to use.  Our example above could be used as such:</p>
<pre class="prettyprint">
Func&lt;int, int, int&gt; func = (Func&lt;int, int, int&gt;)@delegate;
int result = func(1, 2); // Result should be three.
</pre>
<p>The important thing which I hope you get, is that we&#8217;ve taken a simple string expression and converted it into a much more powerful Func<> delegate, which is strongly-typed.</p>
<p>To this end, I&#8217;ve started building a FunctionFactory type used to easily generate these Func<> instances, e.g.</p>
<pre class="prettyprint">
public static class FunctionFactory
{
    private static Delegate CreateInternal(Type[] argumentTypes, Type returnType, string expression, string[] argumentNames = null)
    {
        if (argumentNames != null)
        {
            if (argumentTypes.Length != argumentNames.Length)
                throw new ArgumentException("The number of argument names does not equal the number of argument types.");
        }

        var @params = argumentTypes
            .Select((t, i) =&gt; (argumentNames == null)
                                  ? Expression.Parameter(t)
                                  : Expression.Parameter(t, argumentNames[i]))
            .ToArray();

        ExpressionParser parser = new ExpressionParser(@params, expression, null);

        var @delegate = Expression.Lambda(parser.Parse(returnType), @params).Compile();
        return @delegate;
    }

    public static Func&lt;TReturn&gt; Create&lt;TReturn&gt;(string expression, string[] argumentNames = null)
    {
        return (Func&lt;TReturn&gt;)CreateInternal(new Type[0], typeof(TReturn), expression, argumentNames);
    }

    public static Func&lt;A, TReturn&gt; Create&lt;A, TReturn&gt;(string expression, string[] argumentNames = null)
    {
        return (Func&lt;A, TReturn&gt;)CreateInternal(new[] { typeof(A) }, typeof(TReturn), expression, argumentNames);
    }

    public static Func&lt;A, B, TReturn&gt; Create&lt;A, B, TReturn&gt;(string expression, string[] argumentNames = null)
    {
        return (Func&lt;A, B, TReturn&gt;)CreateInternal(new[] { typeof(A), typeof(B) }, typeof(TReturn), expression, argumentNames);
    }
}
</pre>
<p>Now we can do some really cool stuff:</p>
<pre class="prettyprint">
string expression = "(1 + 2)";
var func = FunctionFactory.Create&lt;int&gt;(expression);

int result = func(); // Result should be 3.

expression = "(a * b)";
var func2 = FunctionFactory.Create&lt;int, int, int&gt;(expression, new[] { "a", "b" });

int result = func2(10, 50); // Result should be 500.
</pre>
<p>We can even go a bit further and handle more complex objects, so if I have an example type, Person with an Age property, we can test against it:</p>
<pre class="prettyprint">
expression = "(Age == 5)";
var func3 = FunctionFactory.Create&lt;Person, bool&gt;(expression);
bool isFive = func3(new Person { Age = 5 });
</pre>
<p>As you can see, the application of these types of expressions is quite endless. Personally I&#8217;ve now been able to introduce dynamic expressions into quite complex rule systems to allow for an additional dimension of flexibility.</p>
<p>Please find the demo project attached, it&#8217;s not as tidy as usual, but still fun to play with and extend.</p>
<p><a href='http://www.fidelitydesign.net/wp-content/uploads/2011/04/FunctionFactory.zip'>FunctionFactory VS2010 Project</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333&amp;title=Converting+String+expressions+to+Funcs+with+FunctionFactory" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333&amp;title=Converting+String+expressions+to+Funcs+with+FunctionFactory" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333&amp;title=Converting+String+expressions+to+Funcs+with+FunctionFactory" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333&amp;headline=Converting+String+expressions+to+Funcs+with+FunctionFactory" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Converting+String+expressions+to+Funcs+with+FunctionFactory&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Converting+String+expressions+to+Funcs+with+FunctionFactory&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Converting+String+expressions+to+Funcs+with+FunctionFactory&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Converting+String+expressions+to+Funcs+with+FunctionFactory&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Converting+String+expressions+to+Funcs+with+FunctionFactory&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333&amp;title=Converting+String+expressions+to+Funcs+with+FunctionFactory&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D333" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&#038;p=333</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RazorEngine v2: Subtemplating</title>
		<link>http://www.fidelitydesign.net/?p=284</link>
		<comments>http://www.fidelitydesign.net/?p=284#comments</comments>
		<pubDate>Tue, 25 Jan 2011 19:00:47 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[include]]></category>
		<category><![CDATA[razor]]></category>
		<category><![CDATA[razorengine]]></category>
		<category><![CDATA[templating]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=284</guid>
		<description><![CDATA[Subtemplating with @Include ASP.NET MVC3 includes the Razor view engine, which was the starting point for the RazorEngine project. Razor views (like their WebForm counterparts) support the ability to include partial views in the parent view. In doing so, it allows you to modularise your views into logical sections. Much like the Razor view engine, [...]]]></description>
			<content:encoded><![CDATA[<h3>Subtemplating with @Include</h3>
<p>ASP.NET MVC3 includes the Razor view engine, which was the starting point for the RazorEngine project.  Razor views (like their WebForm counterparts) support the ability to include partial views in the parent view.  In doing so, it allows you to modularise your views into logical sections.</p>
<p>Much like the Razor view engine, we also support this concept in RazorEngine. We&#8217;ve implemented partial view support using the @Include methods built into TemplateBase. We specifically haven&#8217;t named them RenderPartial (ala the Razor ViewEngine) as we want to differentiate RazorEngine from it&#8217;s MVC counterpart. So how do we start subtemplating?</p>
<p>Here is an example template:</p>
<pre>
Here is a sample template. @Include("helloWorld")
</pre>
<p>When parsing this template, the Razor code generated creates the method calls to the TemplateBase methods. During execution, these methods will first determine if the template named &#8220;helloWorld&#8221; has been pre-compiled (and as such exists in the current TemplateService&#8217;s template cache.</p>
<p>We can handle the resolution of this named template two ways:</p>
<pre class="prettyprint">
string helloWorldTemplate = "Hello World";
Razor.Compile(helloWorldTemplate, "helloWorld");

string fullTemplate = "Here is a sample template. @Include(\"helloWorld\")";
string result = Razor.Parse(fullTemplate);
</pre>
<p>In the above example, we are precompiling the template ahead of time.  This enforces the template is cached (all compiled templates are named). If we don&#8217;t want to precompile the template, we need a ITemplateResolver.</p>
<pre class="prettyprint">
Razor.AddResolver(s =&gt; GetTemplateContent(s));

string fullTemplate = "Here is a sample template. @Include(\"helloWorld\")";
string result = Razor.Parse(fullTemplate);
</pre>
<p>By adding a resolver, it allows us to dynamically locate the template which hasn&#8217;t been precompiled.  This template is then compiled, executed and the result is injected into the result of the parent template.  An ITemplateResolver is defined as:</p>
<pre class="prettyprint">
public interface ITemplateResolver
{
  string GetTemplate(string name);
}
</pre>
<p>The result of the template resolver must be the unparsed template content. RazorEngine supports adding multiple template resolvers to a TemplateService, as well as declaring a template resolver though a Func&lt;string, string&gt; instance.</p>
<h3>Passing Models from Parent to Child</h3>
<p>RazorEngine also supports passing model data from a parent model to a child model using @Include&lt;T&gt;(templateName, model). Child models are treated in compilation the same way as parent models.</p>
<pre class="prettyprint">
string helloWorldTemplate = "Hello @Model";
Razor.CompileWithAnonymous(helloWorldTemplate, "helloWorld");

string fullTemplate = "@Include(\"helloWorld\", @Model.Name)! Welcome to Razor!";
string result = Razor.Parse(fullTemplate, new { Name = "World" });
</pre>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284&amp;title=RazorEngine+v2%3A+Subtemplating" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284&amp;title=RazorEngine+v2%3A+Subtemplating" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284&amp;title=RazorEngine+v2%3A+Subtemplating" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284&amp;headline=RazorEngine+v2%3A+Subtemplating" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=RazorEngine+v2%3A+Subtemplating&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=RazorEngine+v2%3A+Subtemplating&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=RazorEngine+v2%3A+Subtemplating&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=RazorEngine+v2%3A+Subtemplating&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=RazorEngine+v2%3A+Subtemplating&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284&amp;title=RazorEngine+v2%3A+Subtemplating&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D284" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&#038;p=284</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
