<?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>Legomaster Building and Coding</title>
	<atom:link href="http://legomaster.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://legomaster.net</link>
	<description>Building Better Code</description>
	<lastBuildDate>Wed, 25 Aug 2010 14:22:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>MassTransit Distributor (Load Balancing)</title>
		<link>http://legomaster.net/2010/08/masstransit-distributor-load-balancing/</link>
		<comments>http://legomaster.net/2010/08/masstransit-distributor-load-balancing/#comments</comments>
		<pubDate>Wed, 25 Aug 2010 14:20:06 +0000</pubDate>
		<dc:creator>travis</dc:creator>
				<category><![CDATA[Services]]></category>

		<guid isPermaLink="false">http://legomaster.net/?p=82</guid>
		<description><![CDATA[<a href="http://masstransit-project.com/">MassTransit</a> has a distributor built in now (actually for some time...). I'll try to explain what it does and how to use it. 

What is the distributor? It provides the ability to load balancing across multiple endpoints for a given message.
]]></description>
			<content:encoded><![CDATA[<p><a href="http://masstransit-project.com/">MassTransit</a> has a distributor built in now (actually for some time&#8230;). I&#8217;ll try to explain what it does and how to use it. </p>
<p>What is the distributor? It provides the ability to load balancing across multiple endpoints for a given message.</p>
<h2>Distributor Setup</h2>
<p>For setting up the distributor, when doing the service bus configuration, call <code>UseDisttributorFor<T>(IEndpointFactory endpointFactory)</code> on <code>IServiceBusConfigurator</code>. An instance of the endpoint factory is required. </p>
<p>For setting up the worker(s), when doing the service bus configuration, call <code>ImplementDistributorWorker<T>(Action<T> consumeAction) </code>on <code>IServiceBusConfigurator</code>. </p>
<h2>Default <code>IWorkerSelectionStrategy</code> Implementation</h2>
<p>The default worker selection strategy simple looks at the current message count in queue vs. the message count limits. It selects the worker with the smallest number of messages pending or in progress. </p>
<p>The data used to identify which worker is busy might be out of date. There is additional message traffic to keep this data in sync and it can fall behind when the system is under load. </p>
<h2>Custom <code>IWorkerSelectionStrategy</code></h2>
<p>For setting up the distributor, when doing the service bus configuration, call <code>UseDisttributorFor<T>(IEndpointFactory endpointFactory, IWorkerSelectionStrategy<T> workerSelectionStrategy)</code> on <code>IServiceBusConfigurator</code>. </p>
<p>This requires a custom implementation of the <code>IWorkerSelectionStrategy<T></code> interface. There are two methods to implement.</p>
<ul>
<li><code>HasAvaiableWorker </code>- Using the list of candidate workers, indicates if one is available</li>
<li><code>SelectWorker </code>- Using the list of candidate workers, find the best candidate available</li>
</ul>
<h2>Sample</h2>
<p>Okay, so I know you&#8217;re now asking if I&#8217;ll get to any real code. There&#8217;s a sample in the MT solution <a href="http://github.com/MassTransit/MassTransit/tree/master/src/Samples/Grid.Distributor/">Grid.Distributor</a> that shows the basics of using the Distributor. </p>
<p>There are two parts, the activator (who sends commands) and the workers (who completes the commands). You can spin up multiple workers to work on the commands. </p>
]]></content:encoded>
			<wfw:commentRss>http://legomaster.net/2010/08/masstransit-distributor-load-balancing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Topshelf 2.0 Released!</title>
		<link>http://legomaster.net/2010/08/topshelf-2-0-released/</link>
		<comments>http://legomaster.net/2010/08/topshelf-2-0-released/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 23:13:00 +0000</pubDate>
		<dc:creator>travis</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://legomaster.net/?p=78</guid>
		<description><![CDATA[Topshelf 2.0 was released today! You can get it at Topshelf&#8217;s github. 2.0.1 was also released today! A bugfix release&#8230; Shelving: renamed events no longer cause exceptions Shelving: less likely for a service to start up then re-start again right away There are a couple known issues though&#8230; Some log4net log events seem to be [...]]]></description>
			<content:encoded><![CDATA[<p>Topshelf 2.0 was released today! You can get it at <a href="http://github.com/Topshelf/Topshelf/downloads">Topshelf&#8217;s github</a>. </p>
<p>2.0.1 was also released today! A bugfix release&#8230;</p>
<ul>
<li>Shelving: renamed events no longer cause exceptions</li>
<li>Shelving: less likely for a service to start up then re-start again right away</li>
</ul>
<p>There are a couple known issues though&#8230;</p>
<ul>
<li>Some log4net log events seem to be squelched. This might be related to ilmerging we started doing for releases. When it&#8217;s run from source I don&#8217;t see this behavior but I am looking into it.</li>
<li>When shutting down you might see an exception about a pipe not being open. There are a lot of threads &#8216;doing&#8217; stuff to keep everything going right. When shutting down it seems possible for them to not shut down in the right order. I have spent some time trying to pin it down exactly and I haven&#8217;t gotten it yet. I haven&#8217;t seen any negative side effects from it yet though.</li>
</ul>
<p>Thanks to everyone who&#8217;s tried it out so far!</p>
]]></content:encoded>
			<wfw:commentRss>http://legomaster.net/2010/08/topshelf-2-0-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>TopShelf 2.0</title>
		<link>http://legomaster.net/2010/08/topshelf-2-0/</link>
		<comments>http://legomaster.net/2010/08/topshelf-2-0/#comments</comments>
		<pubDate>Mon, 09 Aug 2010 15:50:10 +0000</pubDate>
		<dc:creator>travis</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Services]]></category>

		<guid isPermaLink="false">http://legomaster.net/?p=57</guid>
		<description><![CDATA[What is up and coming in Topshelf 2.0?]]></description>
			<content:encoded><![CDATA[<p>Working on making <a href="http://topshelf-project.com/">Topshelf</a> 2.0 ready for release. I think we&#8217;re mostly feature complete for our 2.0 release, just working on fixing any left over bugs. </p>
<p>So what is changing in Topshelf 2.0? </p>
<ul>
<li><code>InIsolation</code> is no longer an option when creating new services. Support for hosting multiple AppDomains has been moved into shelving. More on shelving to follow.</li>
<li>Command line arguments have changed a bit. See the website&#8217;s documentation on <a href="http://topshelf-project.com/documentation/command-line-syntax/">command line syntax</a> for updates there. </li>
<li>The communication between all subsystems, such as &#8220;start up services&#8221;, is now all down via messages sent across channels. This allows us to easily move to sending messages across AppDomains.</li>
<li>Shelving! More on this below.</li>
</ul>
<h2>Shelving</h2>
<p>So what is this new shelving? It is building Topshelf to be a service host, where when you drop files in a directory, it can look for an interface implementation and spin up a new AppDomain with that logical service isolated in that AppDomain. If you update the files in that folder, the service will attempt to cleanly shutdown then restart with the new files. It&#8217;s pretty awesome, if I do say so myself. </p>
<p>Why is it awesome? </p>
<ol>
<li>Deploying services is dead simple <code>xcopy</code> now, instead of stop service, uninstall, copy, install, start</li>
<li>Configuration changes automagically restart the service when saved &#8211; similar to IIS</li>
<li>Need to scale out a new service? Just drop a new directory in the Service folder and you can scale easily!</li>
</ol>
<p>Here&#8217;s a simple example. </p>
<p><script src="http://gist.github.com/510668.js"> </script></p>
<p>Now compare that to the sample service in the old style. </p>
<p><script src="http://gist.github.com/510671.js"> </script></p>
<p>Shelved services are just DLL assemblies, Topshelf has a Host program that is the windows service that logical services will run under. The second example is a full program that would be installed as a service. </p>
]]></content:encoded>
			<wfw:commentRss>http://legomaster.net/2010/08/topshelf-2-0/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Data Bound Collections in WPF</title>
		<link>http://legomaster.net/2010/01/data-bound-collections-in-wpf/</link>
		<comments>http://legomaster.net/2010/01/data-bound-collections-in-wpf/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 17:40:16 +0000</pubDate>
		<dc:creator>travis</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://legomaster.net/?p=53</guid>
		<description><![CDATA[One of the joys of working with WPF is that data binding that can exist. At a couple points I&#8217;ve wanted to bind a Dictionary as a list. Each item in the list would have a key and only one of those items could exist based upon the the key. Thus I put together two [...]]]></description>
			<content:encoded><![CDATA[<p>One of the joys of working with WPF is that data binding that can exist. At a couple points I&#8217;ve wanted to bind a Dictionary as a list. Each item in the list would have a key and only one of those items could exist based upon the the key. Thus I put together two parts that allowed me to do this. It also allows the bound data to be updated from a thread other than the UI one. </p>
<p>NotifyCollectionChangedBase implemented the INotifyCollectionChanged interface to allow the data bound elements in the WPF to identify the item has been updated.<br />
<script src="http://gist.github.com/282024.js?file=NotifyCollectionChangedBase.cs"></script></p>
<p>The IKeyedObject just allows the KeyedCollectionBase to identify the key used in the internal dictionary.<br />
<script src="http://gist.github.com/282024.js?file=IKeyedObject.cs"></script></p>
<p>KeyedCollectionBase implemented IList to make the collection appear as a list to the rendering elements but internally stores everything as a dictionary so only a single object with the given key exists.<br />
<script src="http://gist.github.com/282024.js?file=KeyedCollectionBase.cs"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://legomaster.net/2010/01/data-bound-collections-in-wpf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XAttribute and null values</title>
		<link>http://legomaster.net/2009/05/xattribute-and-null-values/</link>
		<comments>http://legomaster.net/2009/05/xattribute-and-null-values/#comments</comments>
		<pubDate>Sun, 10 May 2009 02:37:54 +0000</pubDate>
		<dc:creator>travis</dc:creator>
				<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://legomaster.net/?p=30</guid>
		<description><![CDATA[It turns out that for whatever the reason to the <a href="http://msdn.microsoft.com/en-us/library/bb336630.aspx">constructor</a> for <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xattribute.aspx">XAttribute</a> does not accept null values for the value parameter. I think this makes sense even though the XElement constructor will accept null values for the value parameter - mostly because it can still function; a null value for an attribute would be nothing not 'attributeName=""'. 

The quick and dirty: there's an easy solution, use an extension method. 
[code lang="csharp"]    public static class AddXAttribute
    {
        public static XElement NewXAttribute(this XElement xa, XName name, Object value)
        {
            if (xa != null &#038;& value != null)
            {
                xa.Add(new XAttribute(name, value));
            }
            return xa;
        }
    }[/code]]]></description>
			<content:encoded><![CDATA[<p>It turns out that for whatever the reason to the <a href="http://msdn.microsoft.com/en-us/library/bb336630.aspx">constructor</a> for <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xattribute.aspx">XAttribute</a> does not accept null values for the value parameter. I think this makes sense even though the XElement constructor will accept null values for the value parameter &#8211; mostly because it can still function; a null value for an attribute would be nothing not &#8216;attributeName=&#8221;"&#8216;. </p>
<p>The quick and dirty: there&#8217;s an easy solution, use an extension method. </p>
<pre class="brush: csharp;">    public static class AddXAttribute
    {
        public static XElement NewXAttribute(this XElement xa, XName name, Object value)
        {
            if (xa != null &amp;&amp; value != null)
            {
                xa.Add(new XAttribute(name, value));
            }
            return xa;
        }
    }</pre>
<p>Now to explain. Say we have a pretty generic <acronym title="Business Object">BO</acronym> for which we want to be able to generate some XML. </p>
<pre class="brush: csharp;">    public class BusinessObject
    {
        public int Id { get; set; }
        public String Name { get; set; }
        public String Description { get; set; }
    }</pre>
<pre class="brush: csharp;">        private static String BuildXML(List&lt;BusinessObject&gt; data)
        {
            XDocument xDoc = null;
            try
            {
                xDoc = new XDocument(
                    new XElement(&quot;Root&quot;,
                        from d in data
                        select new XElement(&quot;BO&quot;,
                            new XAttribute(&quot;Id&quot;, d.Id),
                            new XAttribute(&quot;Name&quot;, d.Name),
                            new XAttribute(&quot;Desc&quot;, d.Description)
                        )
                    )
                );
            }
            catch (Exception ex)
            {
                Console.WriteLine(&quot;Exception caught: &quot; + ex.Message);
                return String.Empty;
            }

            return xDoc.ToString();
        }</pre>
<p>If we were try and run the BuildXML method with a set of data that included a null in the Name or Description properties then an exception would occur, &#8220;Value cannot be null.&#8221; This seems like it would be a pretty standard why of using LINQ expressions to build an XML document as simple as possible. We don&#8217;t really care about the nulls &#8211; we just want them handled. The answer is to use the NewXAttribute method from above as an extension method. The new BuildXML (call it BuildXML2 for now) would be very similar.</p>
<pre class="brush: csharp;">        private static String BuildXML2(List&lt;BusinessObject&gt; data)
        {
            XDocument xDoc = null;
            try
            {
                xDoc = new XDocument(
                    new XElement(&quot;Root&quot;,
                        from d in data
                        select (new XElement(&quot;BO&quot;))
                            .NewXAttribute(&quot;Id&quot;, d.Id)
                            .NewXAttribute(&quot;Name&quot;, d.Name)
                            .NewXAttribute(&quot;Desc&quot;, d.Description)
                    )
                );
            }
            catch (Exception ex)
            {
                Console.WriteLine(&quot;Exception caught: &quot; + ex.Message);
                return String.Empty;
            }

            return xDoc.ToString();
        }</pre>
<p>You can still chain together expressions, so the code result is not terribly different than what you would expect. The one difference being that any child data would have to be declared before you would add the attributes. At least the way I think of the data when I&#8217;m building it that&#8217;s backwards. </p>
<p>I&#8217;ve included the entire sample below for completeness. </p>
<pre class="brush: csharp;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var data = new List&lt;BusinessObject&gt;();

            // get some data
            data.Add(new BusinessObject()
            {
                Id = 1,
                Name = &quot;One&quot;,
                Description = &quot;First One&quot;
            });

            data.Add(new BusinessObject()
            {
                Id = 2,
                Name = &quot;Two&quot;,
                Description = &quot;Second One&quot;
            });

            data.Add(new BusinessObject()
            {
                Id = 3,
                Name = &quot;Three&quot;,
                Description = &quot;And the third.&quot;
            });

            String xml;

            Console.WriteLine(&quot;==== Standard =============&quot;);
            xml = BuildXML(data);
            Console.WriteLine(xml);
            Console.WriteLine(&quot;===========================&quot;);

            // we need some null data
            data[2].Description = null;

            Console.WriteLine(&quot;==== Standard w/ null data=&quot;);
            xml = BuildXML(data);
            Console.WriteLine(xml);
            Console.WriteLine(&quot;===========================&quot;);

            Console.WriteLine(&quot;==== New Extention ========&quot;);
            xml = BuildXML2(data);
            Console.WriteLine(xml);
            Console.WriteLine(&quot;===========================&quot;);

            Console.ReadLine();

        }

        private static String BuildXML(List&lt;BusinessObject&gt; data)
        {
            XDocument xDoc = null;
            try
            {
                xDoc = new XDocument(
                    new XElement(&quot;Root&quot;,
                        from d in data
                        select new XElement(&quot;BO&quot;,
                            new XAttribute(&quot;Id&quot;, d.Id),
                            new XAttribute(&quot;Name&quot;, d.Name),
                            new XAttribute(&quot;Desc&quot;, d.Description)
                        )
                    )
                );
            }
            catch (Exception ex)
            {
                Console.WriteLine(&quot;Exception caught: &quot; + ex.Message);
                return String.Empty;
            }

            return xDoc.ToString();
        }

        private static String BuildXML2(List&lt;BusinessObject&gt; data)
        {
            XDocument xDoc = null;
            try
            {
                xDoc = new XDocument(
                    new XElement(&quot;Root&quot;,
                        from d in data
                        select (new XElement(&quot;BO&quot;))
                            .NewXAttribute(&quot;Id&quot;, d.Id)
                            .NewXAttribute(&quot;Name&quot;, d.Name)
                            .NewXAttribute(&quot;Desc&quot;, d.Description)
                    )
                );
            }
            catch (Exception ex)
            {
                Console.WriteLine(&quot;Exception caught: &quot; + ex.Message);
                return String.Empty;
            }

            return xDoc.ToString();
        }
    }

    public class BusinessObject
    {
        public int Id { get; set; }
        public String Name { get; set; }
        public String Description { get; set; }
    }

    public static class AddXAttribute
    {
        public static XElement NewXAttribute(this XElement xa, XName name, Object value)
        {
            if (xa != null &amp;&amp; value != null)
            {
                xa.Add(new XAttribute(name, value));
            }
            return xa;
        }
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://legomaster.net/2009/05/xattribute-and-null-values/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>VirtualPathProvider for Assemblies</title>
		<link>http://legomaster.net/2009/05/virtualpathprovider-for-assemblies/</link>
		<comments>http://legomaster.net/2009/05/virtualpathprovider-for-assemblies/#comments</comments>
		<pubDate>Sat, 02 May 2009 11:53:15 +0000</pubDate>
		<dc:creator>travis</dc:creator>
				<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://legomaster.net/?p=24</guid>
		<description><![CDATA[The VirtualPathProvider class provides some options when building websites. One of the most common is to be able to server ASPX/ASCX requests from embedded resources in an assembly. A good place to start is from a CodeProject article that address this issue. First, instead of using hardcode assemblies/paths/etc, a few properties were attached. #region Properties [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://msdn.microsoft.com/en-us/library/system.web.hosting.virtualpathprovider.aspx">VirtualPathProvider</a> class provides some options when building websites. One of the most common is to be able to server ASPX/ASCX requests from embedded resources in an assembly.</p>
<p>A good place to start is from a <a title="Load WebForms and UserControls from Embedded Resources" href="http://www.codeproject.com/KB/aspnet/ASP2UserControlLibrary.aspx">CodeProject article</a> that address this issue.</p>
<p>First, instead of using hardcode assemblies/paths/etc, a few properties were attached.</p>
<pre class="brush: csharp;">        #region Properties
        public String VirtualPath { get; set; }
        public String VirtualFileSystemAssembly { get; set; }
        public String VirtualFileSystemBaseNamespace { get; set; }
        #endregion</pre>
<p>Also, instead of just assuming that a file might exist in the assembly if the virtual paths match &#8211; because we might want to serve file from multiple assemblies on the same virtual path &#8211; the code will check if the resource exists in the assembly. </p>
<pre class="brush: csharp;">        private bool DoesExistInVirtualPath(string virtualPath)
        {
            if (!IsInVirtualPath(virtualPath))
                return false;

            Assembly assembly = GetAssemblyReference();

            if (assembly != null)
            {
                String[] resources = assembly.GetManifestResourceNames();
                String resourceName = ConstructAssemblyResourceName(virtualPath);

                if (resources != null &amp;&amp; resources.Contains(resourceName, StringComparer.InvariantCultureIgnoreCase))
                    return true;
            }
            return false;
        }</pre>
<p>First we check to see if the path even matches, failing that it&#8217;s obvious that there isn&#8217;t a match. They we attempt to get a reference to the desired assembly. Of course if that fails then there&#8217;s no way to be able to serve files from it. Lastly we check the manifest for resources and if there are any does it contain the file we&#8217;re looking for. A file name mangling needs to occur (in ConstructAssemblyResourceName) because of the way the files are named as resources. </p>
<p>There are a couple of helper methods used in the above block, they are just there to keep things neat. </p>
<pre class="brush: csharp;">        private String ConstructAssemblyResourceName(string resourcePath)
        {
            // nix the base path
            String resourceName = resourcePath.Remove(0, VirtualPath.Length);
            // tack on the base namespace
            if (VirtualFileSystemBaseNamespace.Length &gt; 0)
            {
                resourceName = VirtualFileSystemBaseNamespace + '/' + resourceName;
            }
            // replace directory seperators with .'s
            resourceName = resourceName.Replace('/', '.');
            return resourceName;
        }

        private Assembly GetAssemblyReference()
        {
            if (assemblyReference != null)
                return assemblyReference;

            String binDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            String assemblyName = Path.Combine(binDir, VirtualFileSystemAssembly);

            Assembly assembly;
            try
            {
                assembly = Assembly.LoadFile(assemblyName);
            }
            catch
            {
                return null;
            }

            // if it is a real assembly - keep it
            if (assembly != null)
                assemblyReference = assembly;

            return assembly;
        }</pre>
<p>Download the source code: <a href="http://legomaster.net/wp-content/uploads/2009/05/legomasterassemblypathprovider-20090502.zip">Legomaster.AssemblyPathProvider</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://legomaster.net/2009/05/virtualpathprovider-for-assemblies/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
