<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Mebyon Kernow</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/morgan/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/morgan/feed.xml</link>
    <description>A blog by Morgan</description>
    <lastBuildDate>Wed, 17 Apr 2019 03:24:29 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Using standard icons in a rehosted Workflow Designer</title>
      <link>https://docs.microsoft.com/archive/blogs/morgan/using-standard-icons-in-a-rehosted-workflow-designer</link>
      <pubDate>Tue, 15 Mar 2011 06:17:00 GMT</pubDate>
      <dc:creator><![CDATA[Clibbolasbolei]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/morgan/2011/03/15/using-standard-icons-in-a-rehosted-workflow-designer/</guid>
      <description><![CDATA[In this post I&rsquo;ll show how you can easily use appropriate icons within the Workflow Designer...]]></description>
      <content:encoded><![CDATA[<p>In this post I&rsquo;ll show how you can easily use appropriate icons within the Workflow Designer toolbox. There are a number of posts out on the web that show varying ways to do this, however the method I&rsquo;m proposing is most probably the easiest and most flexible.</p>
<p>In days of yore you would simply use the [ToolboxBitmap] attribute and define a bitmap for your custom tools (an activity is just another tool in this instance), and when adding a tool to the toolbox you can optionally specify an icon &ndash; however if you don&rsquo;t then you get the standard &lsquo;cog&rsquo; on screen&hellip;</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/5141.image_37A9DFB6.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/5141.image_5F00_37A9DFB6.png"><img height="116" width="173" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/1447.image_thumb_298AF0B9.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/1447.image_5F00_thumb_5F00_298AF0B9.png" alt="image" border="0" title="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" /></a></p>
<p>If you want however to display the correct icon for a given activity you&rsquo;ll need to do a bit more work and that&rsquo;s where the fun starts. The images for the inbuilt activities are held in a couple of places &ndash; one is inside the Microsoft.VisualStudio.Activities.dll (which you&rsquo;ll typically find in C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE) however that&rsquo;s not redistributable &ndash; but it does include bitmap images of each activity and these are what&rsquo;s used within Visual Studio.</p>
<p>The other is within the System.Activities.Presentation.dll which is redistributable, however this contains XAML resources and not standard bitmaps &ndash; and [ToolboxBitmap] expects an image resource not a slab of XAML.</p>
<p>Now, we&rsquo;re in the world of XAML so using a bitmap resource seems a bit old hat &ndash; I&rsquo;d much rather use a scalable vector icon representation so this post will show how to do this. The following steps will guide you through the process.</p>
<h5>Step One: Add the workflow resources to your application</h5>
<p>Edit your App.xaml.cs (or anywhere else you wish for that matter) and insert the following code &ndash; this will add the standard icon resources from System.Activities.Presentation.dll into your applications resource directory&hellip;</p>
<pre class="code"><span style="color: #2b91af">ResourceDictionary </span>dict = <span style="color: blue">new </span><span style="color: #2b91af">ResourceDictionary </span>{ Source = <br />  <span style="color: blue">new </span><span style="color: #2b91af">Uri</span>(<span style="color: #a31515">"pack://application:,,,/System.Activities.Presentation;V4.0.0.0;31bf3856ad364e35;component/themes/icons.xaml"</span>) };
<span style="color: blue">this</span>.Resources.MergedDictionaries.Add(dict);</pre>
<p>Note here that I have included the full pack: specification for the assembly, including the version number and public key token. In my application it would work fine without these whilst debugging, however if the debugger wasn&rsquo;t attached this would fail without the fully qualified assembly information.</p>
<h5>Step Two: Create a converter</h5>
<p>We&rsquo;ll use this converter to lookup the appropriate icon resource from the above resource dictionary at runtime, in order to present this on screen. If you disassemble System.Activities.Presentation.dll in Reflector and look at the resources (using the BamlViewer add-in) then you&rsquo;ll see the naming scheme is just the activity name + &lsquo;Icon&rsquo;&hellip;</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/3823.image_20BAE86D.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/3823.image_5F00_20BAE86D.png"><img height="195" width="827" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/4118.image_thumb_4C8B3C5C.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/4118.image_5F00_thumb_5F00_4C8B3C5C.png" alt="image" border="0" title="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" /></a></p>
<p>This is just a snippet of the themes/icons.baml resource, and you can see from the above there are some other things in there that aren&rsquo;t necessarily activities (and interestingly enough there are some resources for activities no longer in WF4).</p>
<p>So, all our converter needs to do is lookup the typename of the activity, then append &lsquo;Icon&rsquo;, then go hunting in the resource dictionary and finally return the content of the DrawingBrush&hellip;</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">ToolboxItemWrapperIconConverter </span>: <span style="color: #2b91af">IValueConverter
</span>{
    <span style="color: blue">public object </span>Convert(<span style="color: blue">object </span>value, <span style="color: #2b91af">Type </span>targetType, <span style="color: blue">object </span>parameter, <span style="color: #2b91af">CultureInfo </span>culture)
    {
        <span style="color: #2b91af">ToolboxItemWrapper </span>wrapper = value <span style="color: blue">as </span><span style="color: #2b91af">ToolboxItemWrapper</span>;

        <span style="color: blue">if </span>(<span style="color: blue">null </span>== wrapper)
            <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentException</span>(<span style="color: #a31515">"Expecting a ToolboxItemWrapper as the converter parameter"</span>, <span style="color: #a31515">"value"</span>);

        <span style="color: green">// Generate the resource name
        </span><span style="color: blue">string </span>resourceName = <span style="color: blue">string</span>.Concat(wrapper.Type.Name, <span style="color: #a31515">"Icon"</span>);

        <span style="color: green">// And lookup in app resources
        </span><span style="color: #2b91af">DrawingBrush </span>icon = <span style="color: #2b91af">App</span>.Current.Resources[resourceName] <span style="color: blue">as </span><span style="color: #2b91af">DrawingBrush</span>;

        <span style="color: blue">if </span>(<span style="color: blue">null </span>!= icon)
            <span style="color: blue">return </span>icon.Drawing;
        <span style="color: blue">else
            return null</span>;
    }

    <span style="color: blue">public object </span>ConvertBack(<span style="color: blue">object </span>value, <span style="color: #2b91af">Type </span>targetType, <span style="color: blue">object </span>parameter, <span style="color: #2b91af">CultureInfo </span>culture)
    {
        <span style="color: blue">throw new </span><span style="color: #2b91af">NotImplementedException</span>();
    }
}</pre>
<p>This converter isn&rsquo;t quite finished yet &ndash; if you happen to add on an activity to the toolbox such as FlowSwitch&lt;T&gt;, you won&rsquo;t get an icon for that as shown below&hellip;</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/0383.image_75B2D49A.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/0383.image_5F00_75B2D49A.png"><img height="109" width="205" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/7120.image_thumb_54BF61F3.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/7120.image_5F00_thumb_5F00_54BF61F3.png" alt="image" border="0" title="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" /></a></p>
<p>And you might notice that Flowchart is missing it&rsquo;s icon too. That&rsquo;s easy to sort &ndash; the actual name in the resources is Flow<strong><span style="background-color: #ffff00;">C</span></strong>hartIcon (notice the capitalisation) &ndash; so I&rsquo;ll special case that one in my converter. If you happen to care, TransactedReceiveScope is also one that I&rsquo;ve special cased as its name doesn&rsquo;t match the pattern either. As for the generic types, their icons are simply named without the generic parameter &ndash; so in the case of FlowSwitch&lt;&gt; this would be FlowSwitchIcon. Another bit of code is needed in the converter to deal with these generic activities.</p>
<h5>Step 3: Re-style the toolbox</h5>
<p>In order to display your XAML icons in the toolbox you need to re-style the toolbox and use the converter to provide the correct icon for the activities. Here&rsquo;s some XAML to get you going&hellip;</p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">Style </span><span style="color: red">TargetType</span><span style="color: blue">="{</span><span style="color: #a31515">x</span><span style="color: blue">:</span><span style="color: #a31515">Type </span><span style="color: red">sapt</span><span style="color: blue">:</span><span style="color: red">ToolboxControl</span><span style="color: blue">}"&gt;
    &lt;</span><span style="color: #a31515">Style.Resources</span><span style="color: blue">&gt;
        &lt;</span><span style="color: #a31515">local</span><span style="color: blue">:</span><span style="color: #a31515">ToolboxItemWrapperIconConverter </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Key</span><span style="color: blue">="iconConverter" </span><span style="color: red">DefaultResource</span><span style="color: blue">="GenericLeafActivityIcon"/&gt;
    &lt;/</span><span style="color: #a31515">Style.Resources</span><span style="color: blue">&gt;
    &lt;</span><span style="color: #a31515">Setter </span><span style="color: red">Property</span><span style="color: blue">="ToolTemplate"&gt;
        &lt;</span><span style="color: #a31515">Setter.Value</span><span style="color: blue">&gt;
            &lt;</span><span style="color: #a31515">DataTemplate </span><span style="color: red">DataType</span><span style="color: blue">="{</span><span style="color: #a31515">x</span><span style="color: blue">:</span><span style="color: #a31515">Type </span><span style="color: red">sapt</span><span style="color: blue">:</span><span style="color: red">ToolboxItemWrapper</span><span style="color: blue">}"&gt;
                &lt;</span><span style="color: #a31515">Grid</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">Grid.ColumnDefinitions</span><span style="color: blue">&gt;
                        &lt;</span><span style="color: #a31515">ColumnDefinition </span><span style="color: red">Width</span><span style="color: blue">="Auto"/&gt;
                        &lt;</span><span style="color: #a31515">ColumnDefinition </span><span style="color: red">Width</span><span style="color: blue">="*" </span><span style="color: red">SharedSizeGroup</span><span style="color: blue">="toolLabel"/&gt;
                    &lt;/</span><span style="color: #a31515">Grid.ColumnDefinitions</span><span style="color: blue">&gt;
                        
                    &lt;</span><span style="color: #a31515">Rectangle </span><span style="color: red">Width</span><span style="color: blue">="16" </span><span style="color: red">Height</span><span style="color: blue">="16" </span><span style="color: red">Margin</span><span style="color: blue">="4"&gt;
                        &lt;</span><span style="color: #a31515">Rectangle.Fill</span><span style="color: blue">&gt;
                            &lt;</span><span style="color: #a31515">DrawingBrush </span><span style="color: red">Drawing</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">Converter</span><span style="color: blue">={</span><span style="color: #a31515">StaticResource </span><span style="color: red">iconConverter</span><span style="color: blue">}}"/&gt;
                        &lt;/</span><span style="color: #a31515">Rectangle.Fill</span><span style="color: blue">&gt;
                    &lt;/</span><span style="color: #a31515">Rectangle</span><span style="color: blue">&gt;

                    &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">DisplayName</span><span style="color: blue">}" </span><span style="color: red">Grid.Column</span><span style="color: blue">="1" </span><span style="color: red">VerticalAlignment</span><span style="color: blue">="Center"/&gt;
                &lt;/</span><span style="color: #a31515">Grid</span><span style="color: blue">&gt;
            &lt;/</span><span style="color: #a31515">DataTemplate</span><span style="color: blue">&gt;
        &lt;/</span><span style="color: #a31515">Setter.Value</span><span style="color: blue">&gt;
    &lt;/</span><span style="color: #a31515">Setter</span><span style="color: blue">&gt;
&lt;/</span><span style="color: #a31515">Style</span><span style="color: blue">&gt;
</span></pre>
<p>This style defines a couple of grid. columns, one for the icon and another for the name of the activity. I&rsquo;ve set a size of 16 * 16 for the icon size however as this is your XAML you could change this for something larger if you so desired. You might also want to define a nice looking tooltip and, again, as it&rsquo;s XAML you could go mad!</p>
<p>In the above I&rsquo;ve set the default activity icon to &ldquo;GenericLeafActivityIcon&rdquo; which is the default that Workflow uses when displaying activities with no icons defined. You' may wish to change this for something else &ndash; but it&rsquo;s also the default used in the workflow designer too so it&rsquo;s not a bad choice.</p>
<h5>Step 4: Icons for your custom activities</h5>
<p>OK, that&rsquo;s all the standard activities dealt with &ndash; what about your own? There are two things you need to do in order to get your custom activities to play nicely with the toolbox and also the designer surface. First off you&rsquo;ll need to design an icon for your activity &ndash; I can&rsquo;t help with that other than suggesting you have a play with <a href="http://www.microsoft.com/expression/products/Design_Overview.aspx">Expression Design</a>. </p>
<p>Then you can do one of two things &ndash; either alter your activity designer and specify an Icon for it there, or ensure that you have an icon resource using the same naming convention used above &ndash; i.e. &ldquo;TheNameOfYourActivity&rdquo; + &ldquo;Icon&rdquo;. I&rsquo;d suggest you do both &ndash; my converter will look for a resource following the naming pattern convention first, and if that&rsquo;s not found it then looks for the icon on the associated designer. In order to do this however it has to construct an instance of the designer which isn&rsquo;t really that good an idea, so I&rsquo;d recommend the naming convention approach first.</p>
<p>To change the icon for the designer, all you do is specify it in the XAML for the designer&hellip;</p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">sap</span><span style="color: blue">:</span><span style="color: #a31515">ActivityDesigner <br />    </span><span style="color: red">&lt;snip&gt;</span><span style="color: blue"> <br />    </span><span style="background-color: #ffff00;"><span style="color: red">Icon</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">IfIcon</span></span><span style="color: blue"><span style="background-color: #ffff00;">}"</span>&gt;
</span></pre>
<p>Naming the icon in your custom designer isn&rsquo;t really an optional step as if you don&rsquo;t do this your activity will show the default image on the design surface.</p>
<p>With all that done you can now see the appropriate icons in the designer&hellip;</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/1768.image_33CBEF4C.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/1768.image_5F00_33CBEF4C.png"><img height="136" width="170" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/8712.image_thumb_52A2632A.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/8712.image_5F00_thumb_5F00_52A2632A.png" alt="image" border="0" title="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" /></a></p>
<p>Now that&rsquo;s looking much better! The full source code for the converter is available <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/27662E00ToolboxItemWrapperIconConverter2E00cs" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38/2766_2E00_ToolboxItemWrapperIconConverter_2E00_cs">here</a>.</p>
<p>Last but not least, if you&rsquo;re wondering why I didn&rsquo;t choose the cog icon in the toolbox it&rsquo;s not a XAML resource so I went with the default XAML one instead.</p>
<p>Cogs banished. <img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/1374.wlEmoticon-smile_7178D708.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/1374.wlEmoticon_2D00_smile_5F00_7178D708.png" alt="Smile" class="wlEmoticon wlEmoticon-smile" style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" /></p>]]></content:encoded>
    </item>
    <item>
      <title>Reading summary results from the VS2010 load test database</title>
      <link>https://docs.microsoft.com/archive/blogs/morgan/reading-summary-results-from-the-vs2010-load-test-database</link>
      <pubDate>Tue, 18 Jan 2011 11:26:00 GMT</pubDate>
      <dc:creator><![CDATA[Clibbolasbolei]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/morgan/2011/01/18/reading-summary-results-from-the-vs2010-load-test-database/</guid>
      <description><![CDATA[I’m with a customer in the labs this week doing some performance work and one of the tasks we wanted...]]></description>
      <content:encoded><![CDATA[<p>I’m with a customer in the labs this week doing some performance work and one of the tasks we wanted to do was to programmatically read the load test database in order to retrieve a table of summary data from a test run. My customer has instrumented their application well, and came prepared with 3 months of statistical data about which service calls were used over that time period. These service calls map (fairly) nicely into the unit tests we have, so we can, from this usage data, project out to any number of potential users and then see if the system will cope.</p>  <p>As an example, their instrumentation data can be grouped (it’s all in SQL) to produce a summary table something like the following…</p>  <table style="width: 600px" border="0" cellspacing="0" cellpadding="2"><tbody>     <tr>       <td valign="top" width="200"><strong>Method Name</strong></td>        <td valign="top" width="200"><strong>% calls</strong></td>        <td valign="top" width="200"><strong>Actual calls</strong></td>     </tr>      <tr>       <td valign="top" width="200">AddOnCostWithNameExistsTest</td>        <td valign="top" width="200">3.5</td>        <td valign="top" width="200">7865</td>     </tr>      <tr>       <td valign="top" width="200">CanDeletePriceParentTest</td>        <td valign="top" width="200">2.56</td>        <td valign="top" width="200">6684</td>     </tr>      <tr>       <td valign="top" width="200">CheckIfCustomerValidForLinkTest</td>        <td valign="top" width="200">7.55</td>        <td valign="top" width="200">19012</td>     </tr>      <tr>       <td valign="top" width="200">CheckIfExchangeRateExistsTest</td>        <td valign="top" width="200">4.34</td>        <td valign="top" width="200">12042</td>     </tr>   </tbody></table>  <p>So, we used these percentages to define the test mix in Visual Studio. Then we ran some short tests and I wanted to be able to output something similar from the actual results in the load test database in order to compare them.</p>  <p>The new Export To Excel tool is excellent in VS2010 for comparing one run to another, but I didn’t want that – I wanted to compare a run to my existing data. In my simple mind, if I have 3 months of calls (for 200 users), then I can use a short load test using the percentages defined to work out how many calls the system will make in, say, 8 hours. I can then extrapolate this out to 3 months, and say (with a reasonable degree of accuracy) that the system should be able to support more users.</p>  <p>My problem however was getting the data out of the load test database in a form that was usable to me. I’m a big fan of referential integrity in the database, as not only does it ensure that you can’t bung in data that is nonsensical, but tools such as SQL Management Studio can extract the schema and show you the links. After some poking around in the database I identified the two tables that were of use to me. Needless to say there were no foreign keys between these tables which is most probably due to insert performance (i.e. recording tests as fast as possible). Oh well. They are as follows…</p>  <p><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="Capture" border="0" alt="Capture" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/0574.Capture_393EB6E5.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/0574.Capture_5F00_393EB6E5.png" width="489" height="280" /></p>  <p>There’s also the LoadTestRun table which is the root as far as tests are concerned, and from that you can get the date/time of the test run and other data (such as the description of the test once you’ve annotated your run). A quick select on this table will give you a list of all the load tests you have executed, and from this you need the LoadTestRunId…</p>  <p>&#160;&#160;&#160;&#160;&#160; SELECT * FROM LoadTestRun</p>  <p>With the unique load test ID it’s a simple job to then select the summary data. I created a stored proc to do this as follows…</p>  <pre class="code"><span style="color: blue">CREATE PROCEDURE </span><span style="color: teal">GetTestSummary </span><span style="color: gray">(</span><span style="color: teal">@loadTestRunId </span><span style="color: blue">INT</span><span style="color: gray">) </span><span style="color: blue">AS
BEGIN
  SET NOCOUNT ON
  SELECT </span><span style="color: teal">LTC</span><span style="color: gray">.</span><span style="color: teal">TestCaseName</span><span style="color: gray">, </span><span style="color: teal">LTTSD</span><span style="color: gray">.</span><span style="color: teal">TestsRun</span><span style="color: gray">, </span><span style="color: magenta">ROUND</span><span style="color: gray">(</span><span style="color: teal">LTTSD</span><span style="color: gray">.</span><span style="color: teal">Average</span><span style="color: gray">,</span>2<span style="color: gray">) </span><span style="color: blue">AS </span><span style="color: red">'Average (s)'</span><span style="color: gray">, 
         </span><span style="color: magenta">ROUND</span><span style="color: gray">(</span><span style="color: teal">LTTSD</span><span style="color: gray">.</span><span style="color: teal">Minimum</span><span style="color: gray">,</span>2<span style="color: gray">) </span><span style="color: blue">AS </span><span style="color: red">'Minimum (s)'</span><span style="color: gray">, </span><span style="color: magenta">ROUND</span><span style="color: gray">(</span><span style="color: teal">LTTSD</span><span style="color: gray">.</span><span style="color: teal">Maximum</span><span style="color: gray">,</span>2<span style="color: gray">) </span><span style="color: blue">AS </span><span style="color: red">'Maximum (s)'</span><span style="color: gray">, 
         </span><span style="color: magenta">ROUND </span><span style="color: gray">(</span><span style="color: teal">LTTSD</span><span style="color: gray">.</span><span style="color: teal">Median</span><span style="color: gray">,</span>2<span style="color: gray">) </span><span style="color: blue">AS </span><span style="color: red">'Median (s)'
    </span><span style="color: blue">FROM </span><span style="color: teal">LoadTestTestSummaryData LTTSD
    </span><span style="color: gray">INNER JOIN </span><span style="color: teal">LoadTestCase LTC
      </span><span style="color: blue">ON </span><span style="color: teal">LTTSD</span><span style="color: gray">.</span><span style="color: teal">TestCaseId </span><span style="color: gray">= </span><span style="color: teal">LTC</span><span style="color: gray">.</span><span style="color: teal">TestCaseId
      </span><span style="color: gray">AND </span><span style="color: teal">LTTSD</span><span style="color: gray">.</span><span style="color: teal">LoadTestRunId </span><span style="color: gray">= </span><span style="color: teal">LTC</span><span style="color: gray">.</span><span style="color: teal">LoadTestRunId
    </span><span style="color: blue">WHERE </span><span style="color: teal">LTTSD</span><span style="color: gray">.</span><span style="color: teal">LoadTestRunId </span><span style="color: gray">= </span><span style="color: teal">@loadTestRunId </span>
    <span style="color: blue">ORDER BY </span><span style="color: teal">LTC</span><span style="color: gray">.</span><span style="color: teal">TestCaseName </span><span style="color: blue">ASC
END  
</span></pre>

<p>This produces just the output I was looking for…</p>

<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px; padding-top: 0px" title="Results" border="0" alt="Results" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/8054.Results_6CA01ADB.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/8054.Results_5F00_6CA01ADB.png" width="639" height="121" /></p>

<p>So, I can now extrapolate these figures out to see how many of these tests could run in three months, and from that work out what the likely user load the system could handle would be. It’s not perfect as table sizes will change, but it will give me a good ballpark figure.</p>

<p>One other very useful piece of data we can also extract from the customers instrumentation is the timings (as luckily these were recorded). I can then use the frequency of calls and the execution times to judge which methods I should really concentrate on tuning.</p>

<p>Hope this helps someone.</p>]]></content:encoded>
    </item>
    <item>
      <title>VS2010: Could not read result repository, Named Pipes etc</title>
      <link>https://docs.microsoft.com/archive/blogs/morgan/vs2010-could-not-read-result-repository-named-pipes-etc</link>
      <pubDate>Mon, 17 Jan 2011 06:16:00 GMT</pubDate>
      <dc:creator><![CDATA[Clibbolasbolei]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/morgan/2011/01/17/vs2010-could-not-read-result-repository-named-pipes-etc/</guid>
      <description><![CDATA[I've just come across a problem with load testing on Visual Studio 2010 (which probably amounts to a...]]></description>
      <content:encoded><![CDATA[<p>I've just come across a problem with load testing on Visual Studio 2010 (which probably amounts to a RTFM issue, but who does that anyway?)</p>
<p>When installing the load test controller I specified the machine name as '.'. Nothing in the setup told me this would be a problem, but it was. When I then ran my tests I received the following error from Visual Studio...</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/7271.CouldNotReadResults_1EA93351.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/7271.CouldNotReadResults_5F00_1EA93351.png"><img height="270" width="508" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/5127.CouldNotReadResults_thumb_5D2E80F7.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/5127.CouldNotReadResults_5F00_thumb_5F00_5D2E80F7.png" alt="CouldNotReadResults" border="0" title="CouldNotReadResults" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" /></a></p>
<p>For the benefit of search engines the full text is repeated below...</p>
<p style="padding-left: 30px;"><em>Could not read result repository: Could not access the load test results repository: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error:40 - Could not open a connection to SQL Server).</em></p>
<p style="padding-left: 30px;"><em>Will display the runtime result instead of the repository result</em>.</p>
<p>I checked everything. SQL Server was installed correctly, all network protocols were enabled, I could access the server remotely, but still the error persisted. After some head scratching <a href="http://blogs.msdn.com/robmartin">Rob</a> suggested I change the server name from &lsquo;.&rsquo; to the actual name of the server&hellip;</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/7245.SpecifyServerName_6DC67BE5.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/7245.SpecifyServerName_5F00_6DC67BE5.png"><img height="484" width="456" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/1805.SpecifyServerName_thumb_413D4BFF.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/1805.SpecifyServerName_5F00_thumb_5F00_413D4BFF.png" alt="SpecifyServerName" border="0" title="SpecifyServerName" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" /></a></p>
<p>Sure enough that did the trick. I can now read the results. Interestingly enough my previous runs were written to the database correctly, it&rsquo;s just that I couldn&rsquo;t read them from Visual Studio without making the above change. I&rsquo;ll chalk that up to experience, good to know the problem though. I would have appreciated it if the wizard had told me that &lsquo;.&rsquo; would cause problems down the line mind you. <img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/4213.wlEmoticon-smile_119F2D73.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/4213.wlEmoticon_2D00_smile_5F00_119F2D73.png" alt="Smile" class="wlEmoticon wlEmoticon-smile" style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" /></p>]]></content:encoded>
    </item>
    <item>
      <title>Workflow Activities and Data Templates</title>
      <link>https://docs.microsoft.com/archive/blogs/morgan/workflow-activities-and-data-templates</link>
      <pubDate>Wed, 22 Sep 2010 14:51:27 GMT</pubDate>
      <dc:creator><![CDATA[Clibbolasbolei]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/morgan/2010/09/22/workflow-activities-and-data-templates/</guid>
      <description><![CDATA[A.K.A. “Why won’t the workflow designer use my data template?”  I was on site with a customer today...]]></description>
      <content:encoded><![CDATA[<h5>A.K.A. “Why won’t the workflow designer use my data template?”</h5>  <p>I was on site with a customer today writing some custom activities and found a problem that wasn’t immediately obvious how I could get around it (and indeed it’s taken me some hours of head scratching and debugging to finally find the answer).</p>  <p>I have a custom activity on which I’ve defined the following property…</p>  <blockquote>   <pre class="code"><span style="color: blue">public </span><span style="color: #2b91af">Comparison </span>Comparison { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
</blockquote>
<a href="http://11011.net/software/vspaste"></a>

<p>The comparison class is one I’ve made up myself, and I have derived classes such as BooleanComparison, StringComparison and so on. The actual value of the Comparison property is set by my designer. In the designer I then want to show the appropriate UI for each type of designer, so I created some data templates…</p>

<blockquote>
  <pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">DataTemplate </span><span style="color: red">DataType</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">x</span><span style="color: blue">:</span><span style="color: #a31515">Type </span><span style="color: red">helpers</span><span style="color: blue">:</span><span style="color: red">Comparison</span><span style="color: blue">}&quot;&gt;
    &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;BOOL&quot;/&gt;
&lt;/</span><span style="color: #a31515">DataTemplate</span><span style="color: blue">&gt;

&lt;</span><span style="color: #a31515">DataTemplate </span><span style="color: red">DataType</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">x</span><span style="color: blue">:</span><span style="color: #a31515">Type </span><span style="color: red">helpers</span><span style="color: blue">:</span><span style="color: red">StringComparison</span><span style="color: blue">}&quot;&gt;
    &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;STRING&quot;/&gt;
&lt;/</span><span style="color: #a31515">DataTemplate</span><span style="color: blue">&gt;

&lt;</span><span style="color: #a31515">DataTemplate </span><span style="color: red">DataType</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">x</span><span style="color: blue">:</span><span style="color: #a31515">Type </span><span style="color: red">helpers</span><span style="color: blue">:</span><span style="color: red">DateTimeComparison</span><span style="color: blue">}&quot;&gt;
    &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;DATETIME&quot;/&gt;
&lt;/</span><span style="color: #a31515">DataTemplate</span><span style="color: blue">&gt;</span></pre>
</blockquote>
<a href="http://11011.net/software/vspaste"></a>

<p>OK, so these are hardly going to set the world on fire, but you get the idea. I then databound the Content property to a ContentPresenter so…</p>

<blockquote>
  <pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">ContentControl </span><span style="color: red">Content</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">ModelItem</span><span style="color: blue">.Comparison}&quot;/&gt;
</span></pre>
</blockquote>
<a href="http://11011.net/software/vspaste"></a>

<p>But on screen this never worked – I kept on getting the TypeName show up – a sure sign that the right data template wasn’t being selected. Puzzled, I fiddled around for some hours trying to solve this. I thought I must have the XAML wrong, so popped the lot into a new WPF project but it all worked as expected. Even more puzzling. I then decided to move the property into the designer, which changed the binding from <strong>ModelItem.Comparison</strong> to just <strong>Comparison</strong>, and lo &amp; behold it now worked.</p>

<p>Knowing a bit about how ModelItem worked under the covers (it’s a custom type converter) I twigged – the object returned from ModelItem.Comparison wasn’t a real Comparison object (or rather, it was wrapped in something, which just so happened to be the ModelItem class).</p>

<p>So, armed with this I knew I was just about there, and a quick stint in Reflector told me I should call the GetCurrentValue() method of ModelItem in order to get the actual value for my binding. So I crufted up the following converter and now all is sweet in Workflow land for me – all I have to do is add on the converter to my binding and it’ll then find the appropriate data template. </p>

<blockquote>
  <p><span style="color: blue">&lt;</span><span style="color: #a31515">ContentControl </span><span style="color: red">Content</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">ModelItem</span><span style="color: blue">.Comparison, </span><span style="color: red">Converter</span><span style="color: blue">={</span><span style="color: #a31515">StaticResource </span><span style="color: red">modelItemConverter</span><span style="color: blue">}}&quot;</span><span style="color: blue"> /&gt;</span></p>
</blockquote>
<a href="http://11011.net/software/vspaste"></a>

<p>The converter class is shown below – it’s trivial to implement but this will save you typing a few lines!</p>

<blockquote>
  <pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">ModelItemConverter </span>: <span style="color: #2b91af">IValueConverter
</span>{
    <span style="color: blue">public object </span>Convert(<span style="color: blue">object </span>value, <span style="color: #2b91af">Type </span>targetType, <span style="color: blue">object </span>parameter, System.Globalization.<span style="color: #2b91af">CultureInfo </span>culture)
    {
        <span style="color: blue">object </span>retVal = value;

        <span style="color: blue">if </span>(value <span style="color: blue">is </span><span style="color: #2b91af">ModelItem</span>)
            retVal = ((<span style="color: #2b91af">ModelItem</span>)value).GetCurrentValue();

        <span style="color: blue">return </span>retVal;
    }

    <span style="color: blue">public object </span>ConvertBack(<span style="color: blue">object </span>value, <span style="color: #2b91af">Type </span>targetType, <span style="color: blue">object </span>parameter, System.Globalization.<span style="color: #2b91af">CultureInfo </span>culture)
    {
        <span style="color: blue">return </span>value;
    }
}</pre>
</blockquote>
<a href="http://11011.net/software/vspaste"></a>

<p>Hopefully this will save someone some time!</p>]]></content:encoded>
    </item>
    <item>
      <title>Bug: Goal Based load test generates a LoadTestGoalCounterNotFoundException</title>
      <link>https://docs.microsoft.com/archive/blogs/morgan/bug-goal-based-load-test-generates-a-loadtestgoalcounternotfoundexception</link>
      <pubDate>Wed, 25 Aug 2010 06:48:34 GMT</pubDate>
      <dc:creator><![CDATA[Clibbolasbolei]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/morgan/2010/08/25/bug-goal-based-load-test-generates-a-loadtestgoalcounternotfoundexception/</guid>
      <description><![CDATA[I’m in the scalability labs with a customer this week and we’ve encountered an exception when...]]></description>
      <content:encoded><![CDATA[<p>I’m in the scalability labs with a customer this week and we’ve encountered an exception when setting up a goal based load test.</p>  <p>We have a bunch of machines, and my customer has created a set of custom performance counters that report appropriate data. The goal based test was setup to utilise a custom counter on a remote machine, but when we ran the test we got the following exception…</p>  <blockquote>   <p><strong><em>A goal based load pattern can not be applied because it specifies a performance counter (UKGC08\Availability Searches\Operations Executed / sec\) that could not be read: Category does not exist.</em></strong></p> </blockquote>  <p>Here UKGC08 is the machine name that the counter was defined upon, “Availability Searches” was the category and “Operations Executed / sec” was the counter name. There was no instance specified.</p>  <p>In addition to the above error I also received a stack trace…</p>  <blockquote>   <p><strong><em>at Microsoft.VisualStudio.TestTools.WebStress.LoadTestResultsCollector.AddOrReplaceGoalProfile(LoadTestGoalBasedLoadProfile goalProfile)          <br />at Microsoft.VisualStudio.TestTools.WebStress.LoadTestResultsCollector.AddGoalProfilesFromLoadTest(WebTestSuite suite)           <br />at Microsoft.VisualStudio.TestTools.WebStress.LoadTestResultsCollector.Start(LoadTestRigInfo rigInfo, TestRun testRun)</em></strong></p> </blockquote>  <p>Looking into the code in AddOrReplaceGoalProfile I found the error – internally this creates an instance of the <strong>PerformanceCounter</strong> class in order to read the data from this counter. The problem is that the code is currently written as follows (and thanks again to the most excellent <a href="http://reflector.red-gate.com">Reflector</a> for decompiling this for me)…</p>  <blockquote>   <pre class="code"><span style="color: #2b91af">PerformanceCounter </span>counter;

<span style="color: blue">if </span>(<span style="color: blue">string</span>.IsNullOrEmpty(goalProfile.InstanceName) || <span style="color: blue">string</span>.Equals(goalProfile.InstanceName, SINGLE_INSTANCE_NAME, <span style="color: #2b91af">StringComparison</span>.OrdinalIgnoreCase))
    counter = <span style="color: blue">new </span><span style="color: #2b91af">PerformanceCounter</span>(goalProfile.CategoryName, goalProfile.CounterName);
<span style="color: blue">else
    </span>counter = <span style="color: blue">new </span><span style="color: #2b91af">PerformanceCounter</span>(goalProfile.CategoryName, goalProfile.CounterName, goalProfile.InstanceName);

counter.MachineName = goalProfile.MachineName;</pre>
  <a href="http://11011.net/software/vspaste"></a></blockquote>

<p>The issue is that the machine name is not defined on the constructor of <strong>PerformanceCounter</strong>, and hence an exception is thrown as this code is not running on the machine that the counters are defined upon which will be the local machine or the load test controller.</p>

<p>I’ve raised this with the product team and they’re raising a bug internally, but in the meantime is there a workaround?</p>

<p>Well yes, as it happens. The code above is looking for the custom counter on the wrong machine – so the workaround is to install the counters everywhere, not just the machine under test. All I did was take the customers counters, install these locally (and on the controller, as to be fair I’m not sure which machine is running this code and didn’t test each machine individually) and voila, it all works. In the absence of a formal fix this workaround will get you running. Hope this helps!</p>]]></content:encoded>
    </item>
    <item>
      <title>Adding a Context Menu item to a Workflow 4 designer</title>
      <link>https://docs.microsoft.com/archive/blogs/morgan/adding-a-context-menu-item-to-a-workflow-4-designer</link>
      <pubDate>Mon, 05 Jul 2010 09:37:46 GMT</pubDate>
      <dc:creator><![CDATA[Clibbolasbolei]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/morgan/2010/07/05/adding-a-context-menu-item-to-a-workflow-4-designer/</guid>
      <description><![CDATA[I’m in a curious time-warp this week, as I’ve just been asked how to do something in WF4 that I...]]></description>
      <content:encoded><![CDATA[<p>I’m in a curious time-warp this week, as I’ve just been asked how to do something in WF4 that I wrote about for <a href="http://www.morganskinner.com/articles/ActivityVerbs/">WF3 in September 2005</a>. Anyhow, a customer of mine asked how to add an item to the context menu for an activity within the design surface, and so here goes…</p>  <p>Firstly you need a custom designer. Once you have a designer, open up the code behind file and create a new property of type <a href="http://msdn.microsoft.com/library/system.windows.input.ICommand.aspx">ICommand</a>.</p>  <pre class="code"><span style="color: gray">/// &lt;summary&gt;
/// </span><span style="color: green">Custom activity
</span><span style="color: gray">/// &lt;/summary&gt;
</span><span style="color: blue">public partial class </span><span style="color: #2b91af">CustomSchedulerDesigner
</span>{
    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Command used to add a banch to my activity at design time
    </span><span style="color: gray">/// &lt;/summary&gt;
    </span><span style="color: blue">public </span><span style="color: #2b91af">ICommand </span>AddBranch { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }

}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p>My activity has branches (in a similar concept to the Pick activity and the Parallel activity) so AddBranch seemed like a fairly reasonable name for the command. Some folk subscribe to the notion that all commands should be suffixed with ‘Command’, so if you would prefer please feel free to call yours AddBranchCommand. Me – I’m fine with the above.</p>

<p>Next you need an implementation of ICommand to actually do the work (and optionally enable/disable the command). What you choose is up to you – I use a DelegateCommand class that I’ve had hanging around in my snippets in VS for a year or two, you may have your own but if not a quick search on the web will bring up many DelegateCommand classes. So, I then need to add a delegate command that will be called when the user clicks my menu item. For my example the code is as simple as the following…</p>

<pre class="code"><span style="color: gray">/// &lt;summary&gt;
/// </span><span style="color: green">Custom activity
</span><span style="color: gray">/// &lt;/summary&gt;
</span><span style="color: blue">public partial class </span><span style="color: #2b91af">CustomSchedulerDesigner
</span>{
    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Command used to add a banch to my activity at design time
    </span><span style="color: gray">/// &lt;/summary&gt;
    </span><span style="color: blue">public </span><span style="color: #2b91af">ICommand </span>AddBranch { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }

    <span style="color: blue">public </span>CustomSchedulerDesigner()
    {
        InitializeComponent();

        AddBranch = <span style="color: blue">new </span><span style="color: #2b91af">DelegateCommand</span>(x =&gt; <br />            <span style="color: blue">this</span>.ModelItem.Properties[<span style="color: #a31515">&quot;Branches&quot;</span>]<br />            .Collection.Add(<span style="color: blue">new </span><span style="color: #2b91af">CustomSchedulerBranch</span>()));
    }
}</pre>

<p><a href="http://11011.net/software/vspaste"></a>Here I’m using a Lambda expression for the delegate (I love ‘em) and it looks up the Branches property of my custom activity, and to it adds a new instance of the CustomSchedulerBranch activity. The ModelItem property of a custom designer isn’t strongly typed hence the somewhat weird syntax, but you could do some work to get the actual activity instance if you wished. I took the quick route!</p>

<p>With that little lot in place all you then need to do is wire up the command inside the designer. In my XAML I added the following…</p>

<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">sap</span><span style="color: blue">:</span><span style="color: #a31515">ActivityDesigner.ContextMenu</span><span style="color: blue">&gt;
    &lt;</span><span style="color: #a31515">ContextMenu</span><span style="color: blue">&gt;
        &lt;</span><span style="color: #a31515">MenuItem </span><span style="color: red">Header</span><span style="color: blue">=&quot;Add Branch&quot; </span><span style="color: red">Command</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">AddBranch</span><span style="color: blue">}&quot;/&gt;
    &lt;/</span><span style="color: #a31515">ContextMenu</span><span style="color: blue">&gt;
&lt;/</span><span style="color: #a31515">sap</span><span style="color: blue">:</span><span style="color: #a31515">ActivityDesigner.ContextMenu</span><span style="color: blue">&gt;

</span></pre>

<p><a href="http://11011.net/software/vspaste"></a>And then you can compile your code and you should see a new menu item on screen when you display the context menu over your activity…</p>

<p><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="AddBranch" border="0" alt="AddBranch" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/6355.AddBranch_30FAB9A9.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/6355.AddBranch_5F00_30FAB9A9.png" width="443" height="338" /> </p>

<p>Voila! Clicking on the “Add Branch” menu item calls your delegate and you can then do whatever you wish within the designer code. I’ve not provided an example as mine’s been hacked around a bit but hopefully there’s enough here to make it fairly easy to follow along. The jaunty tilt in the image above is a feature of Windows Live Writer, which I use to create my blog posts. I just noticed that I could tilt images so couldn’t resist.</p>

<p>Bye for now!</p>]]></content:encoded>
    </item>
    <item>
      <title>Simplifying commands in MVVM and WPF</title>
      <link>https://docs.microsoft.com/archive/blogs/morgan/simplifying-commands-in-mvvm-and-wpf</link>
      <pubDate>Thu, 24 Jun 2010 05:10:10 GMT</pubDate>
      <dc:creator><![CDATA[Clibbolasbolei]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/morgan/2010/06/24/simplifying-commands-in-mvvm-and-wpf/</guid>
      <description><![CDATA[I’ve been using MVVM since I started WPF (I was a latecomer to the beauty that is WPF) and one of...]]></description>
      <content:encoded><![CDATA[<p>I’ve been using MVVM since I started WPF (I was a latecomer to the beauty that is WPF) and one of the things that’s always irked me is the amount of code you need to write in order to expose a command. I’ll typically write something like the following in order to create a command that I can bind to from the UI…</p>  <pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">WibbleViewModel </span>: <span style="color: #2b91af">BaseViewModel
</span>{
    <span style="color: blue">public </span>WibbleViewModel()
    {
        _thisCommand = <span style="color: blue">new </span>DelegateCommand(x =&gt; <br />            <span style="color: #2b91af">MessageBox</span>.Show(<span style="color: #a31515">&quot;You clicked ThisCommand&quot;</span>));
    }

    <span style="color: blue">public </span><span style="color: #2b91af">ICommand </span>ThisCommand
    {
        <span style="color: blue">get </span>{ <span style="color: blue">return </span>_thisCommand; }
    }

    <span style="color: blue">private </span><span style="color: #2b91af">ICommand </span>_thisCommand;
}</pre>
<a href="http://11011.net/software/vspaste"></a>The BaseViewModel class is one from my good chum <a href="http://www.thejoyofcode.com/">iJosh.</a> Anyhow, there’s a lot of code that I have to write in order to expose just one command (well, I think so anyway, aren’t computers supposed to make life easier?). Today I was writing yet another WPF app (I tend to do a lot of demos with my customers) and after writing the above yet again I had a brainwave. 

<h5><em>ICustomTypeDescriptor to the rescue</em></h5>

<p>Rather than repeat this code ad-infinitum for each command (and lets face it, WPF apps generally have lots of commands), I crufted up a sample using a custom type descriptor. If you don’t know, .NET has supported the <a href="http://msdn.microsoft.com/library/system.componentmodel.ICustomTypeDescriptor.aspx">ICustomTypeDescriptor</a> interface since the first version (indeed I wrote an article about extending the Windows Forms property grid that used ICustomTypeDescriptor on 30/11/2001!). What this interface allows you to do is to synthesize metadata about an object instance. You can for example add attributes to the metadata for an object using this interface. You can also add fields. But for the purposes of this article, I’m adding properties.</p>

<p>What’s the good of that you might say?</p>

<p>Well, what I’m trying to do is simplify the number of lines of code I have to write in order to expose commands on a given View Model. Now, when I bind to a command from the XAML I’d typically type in an expressions such as the following…</p>

<pre class="code"><font color="#000000"><span style="color: blue">&lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Grid.Column</span><span style="color: blue">=&quot;1&quot; </span><span style="color: red">Orientation</span></font><font color="#000000"><span style="color: blue">=&quot;Vertical&quot;&gt;
    &lt;</span><span style="color: #a31515">Button </span><span style="color: red">Content</span></font><span style="color: blue"><font color="#000000">=&quot;New Expense Claim&quot; <span style="color: red">Margin</span><span style="color: blue">=&quot;30,10&quot;</span><br /></font>        </span><strong><em><span style="color: red">Command</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">NewExpenseCommand</span><span style="color: blue">}&quot;</span></em></strong><span style="color: blue">/&gt;
    &lt;</span><span style="color: #a31515">Separator</span><span style="color: blue">/&gt;
    &lt;</span><span style="color: #a31515">Button </span><span style="color: red">Content</span><span style="color: blue">=&quot;Approve Claim&quot; <span style="color: blue"></span><span style="color: red">Margin</span><span style="color: blue">=&quot;30,10&quot;</span><br />        </span><strong><em><span style="color: red">Command</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">ApproveExpenseCommand</span><span style="color: blue">}&quot;</span></em></strong><span style="color: blue">/&gt;
    &lt;</span><span style="color: #a31515">Button </span><span style="color: red">Content</span><span style="color: blue">=&quot;Reject Claim&quot; <span style="color: red">Margin</span><span style="color: blue">=&quot;30,10&quot;</span><br />        </span><strong><em><span style="color: red">Command</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">RejectExpenseCommand</span><span style="color: blue">}&quot;</span></em></strong><span style="color: blue">/&gt;
&lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>Then for each of these 3 example commands I’d have to define a property getter, private variable etc etc. Now Binding in WPF is pretty clever, and it uses property descriptors in order to navigate to the value bound. </p>

<h5><em>Less Code, More Smiles</em></h5>

<p>So, all I should need to do is alter the syntax used in XAML and (with the assistance of a helper class) I could expose commands <strong>*without*</strong> all of the boilerplate code. I’d then have bindings setup as follows…</p>

<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Grid.Column</span><span style="color: blue">=&quot;1&quot; </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Vertical&quot;&gt;
    &lt;</span><span style="color: #a31515">Button </span><span style="color: red">Content</span><span style="color: blue">=&quot;New Expense Claim&quot; <span style="color: blue"></span><span style="color: red">Margin</span><span style="color: blue">=&quot;30,10&quot;</span><br />        </span><strong><em><span style="color: red">Command</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">Commands</span><span style="color: blue">.NewExpenseCommand}&quot;</span></em></strong><span style="color: blue">/&gt;
    &lt;</span><span style="color: #a31515">Separator</span><span style="color: blue">/&gt;
    &lt;</span><span style="color: #a31515">Button </span><span style="color: red">Content</span><span style="color: blue">=&quot;Approve Claim&quot; <span style="color: blue"></span><span style="color: red">Margin</span><span style="color: blue">=&quot;30,10&quot;</span><br />        </span><strong><em><span style="color: red">Command</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">Commands</span><span style="color: blue">.ApproveExpenseCommand}&quot;</span></em></strong><span style="color: blue">/&gt;
    &lt;</span><span style="color: #a31515">Button </span><span style="color: red">Content</span><span style="color: blue">=&quot;Reject Claim&quot; <span style="color: blue"></span><span style="color: red">Margin</span><span style="color: blue">=&quot;30,10&quot;</span><br />        </span><strong><em><span style="color: red">Command</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">Commands</span><span style="color: blue">.RejectExpenseCommand}&quot;</span></em></strong><span style="color: blue">/&gt;
&lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
</span></pre>

<p><a href="http://11011.net/software/vspaste"></a>Note here that I’ve prefixed the name of each command with ‘Commands’. This is a property that I’ve exposed from my View Model that uses my CommandMap class (which you can grab at the end of the article). The entire code in my View Model to expose the three commands is as follows…</p>

<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">WibbleViewModel </span>: <span style="color: #2b91af">BaseViewModel
</span>{
    <span style="color: blue">public </span>WibbleViewModel()
    {
        _commands = <span style="color: blue">new </span><span style="color: #2b91af">CommandMap</span>();
        _commands.AddCommand(<span style="color: #a31515">&quot;NewExpenseCommand&quot;</span>, <br />            x =&gt; <span style="color: #2b91af">MessageBox</span>.Show(<span style="color: #a31515">&quot;Not yet implemented&quot;</span>, <span style="color: #a31515">&quot;New Expense Claim&quot;</span>));
        _commands.AddCommand(<span style="color: #a31515">&quot;ApproveExpenseCommand&quot;</span>, <br />            x =&gt; <span style="color: #2b91af">MessageBox</span>.Show(<span style="color: #a31515">&quot;Not yet implemented&quot;</span>, <span style="color: #a31515">&quot;Approve Claim&quot;</span>));
        _commands.AddCommand(<span style="color: #a31515">&quot;RejectExpenseCommand&quot;</span>, <br />            x =&gt; <span style="color: #2b91af">MessageBox</span>.Show(<span style="color: #a31515">&quot;Not yet implemented&quot;</span>, <span style="color: #a31515">&quot;Reject Claim&quot;</span>));
    }

    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Get the list of commands
    </span><span style="color: gray">/// &lt;/summary&gt;
    </span><span style="color: blue">public </span><span style="color: #2b91af">CommandMap </span>Commands
    {
        <span style="color: blue">get </span>{ <span style="color: blue">return </span>_commands; }
    }</pre>

<pre class="code"><span style="color: blue">    private </span><span style="color: #2b91af">CommandMap </span>_commands; </pre>

<pre class="code">}</pre>

<p>Here I’ve created an instance of the CommandMap class in my constructor, exposed this as a read-only property, and then created the actual commands in the simplest way possible by calling ‘AddCommand’. There are two overloads of AddCommand as shown below…</p>

<pre class="code"><span style="color: blue">public void </span>AddCommand(<span style="color: blue">string </span>commandName, <br />                       <span style="color: #2b91af">Action</span>&lt;<span style="color: blue">object</span>&gt; executeMethod);<br />
<span style="color: blue">public void </span>AddCommand(<span style="color: blue">string </span>commandName, <br />                       <span style="color: #2b91af">Action</span>&lt;<span style="color: blue">object</span>&gt; executeMethod, <br />                       <span style="color: #2b91af">Predicate</span>&lt;<span style="color: blue">object</span>&gt; canExecuteMethod);</pre>
<a href="http://11011.net/software/vspaste"></a>

<p>The <strong>commandName</strong> argument is used to expose the ICommand to the {Binding} markup extension. If you remember, in the XAML I bound to <strong>Commands.NewExpenseCommand</strong> which, through the beauty of ICustomTypeDescriptor, ultimately gets me into my code that can return an ICommand instance. The {Binding} extension first looks for an object called <strong>Commands</strong> on the current DataContext. This gets me to my CommandMap class. The binding then asks for the <strong>NewExpenseCommand</strong> property, which is now running code in my custom type descriptor code. All I have to do is delve into a dictionary inside CommandMap that stores name/value pairs based on what I used for AddCommand, and I can synthesize a property called NewExpenseCommand (or anything else for that matter) which WPF will diligently bind to. Voila!</p>

<p>The <strong>executeMethod</strong> and <strong>canExecuteMethod</strong> properties can be supplied as Lambda functions, making your code nice and concise (under the covers I’ve reused a DelegateCommand object which I’ve been using for ages). And just for that extra bit of conciseness (if that’s a word!) I could move all of this stuff up into the BaseViewModel class. Saweet.</p>

<h5><em>The Code</em></h5>

<p>Please click on the following file to view or download the C# source code for the CommandMap class.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/3173.CommandMap.cs.txt" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38/3173.CommandMap.cs.txt">CommandMap.cs</a></p>

<p>This doesn’t have any other dependencies so you should be able to plug this in wherever you like with the minimum of fuss. The one enhancement I can think of at the moment is to cache the property descriptor collection returned from the GetProperties method of the CommandMapDescriptor class. This would require that the command collection was an observable collection and I’ve just not got round to that code as yet.</p>

<p>Let me know what you think – good/bad/ugly?</p>]]></content:encoded>
    </item>
    <item>
      <title>A practical State Machine example</title>
      <link>https://docs.microsoft.com/archive/blogs/morgan/a-practical-state-machine-example</link>
      <pubDate>Tue, 15 Jun 2010 08:29:49 GMT</pubDate>
      <dc:creator><![CDATA[Clibbolasbolei]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/morgan/2010/06/15/a-practical-state-machine-example/</guid>
      <description><![CDATA[Now that the State Machine Activity Pack has been released on Codeplex (see http://wf.codeplex.com...]]></description>
      <content:encoded><![CDATA[<p>Now that the State Machine Activity Pack has been released on Codeplex (see <a href="http://wf.codeplex.com">http://wf.codeplex.com</a> for details) I thought I should resurrect one of the samples I regularly used in the 3.x days to show a state machine example. The point of this example is to show how the state machine activities could be used to control access to a building as it’s a simple example and showcases the main features available in the state machine activity pack.</p>  <p>My example models access control to a door – the host is a WPF application (which could do with some better styling!). Imagine if you could ‘boot’ up a building. In that case each door would for sake of argument be closed and locked – this forms the initial state of the state machine. Thereafter we’re awaiting an event, which is the user unlocking the door. This might be by using a PIN pad or a smart card – the details of this are beyond the scope of the post. An overview of the states and transitions is shown in the image below.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/2287.StateMachine_6E16C802.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/2287.StateMachine_5F00_6E16C802.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="StateMachine" border="0" alt="StateMachine" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/8154.StateMachine_thumb_7DD65D06.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/8154.StateMachine_5F00_thumb_5F00_7DD65D06.png" width="468" height="484" /></a></p>  <p>When the user presents their credentials the Unlocked transition occurs – here you could optionally pass the PIN number (or card entry code) into the transition to lookup the code in a database and verify that it is correct. In my example I just transition to the ClosedUnlocked state without any verification.</p>  <p>From this state there are 3 possible things that could happen – the user could open the door (the most likely outcome), they could choose to re-lock the door for some reason, or they might not open the door within a set period in which case you would want the door to automatically re-lock itself and transition back to the ClosedLocked state. So at this point there are 3 transitions executing, two are waiting on an event (more on this in a moment) and the third (Timeout) is waiting for a Delay which in my example is 5 seconds. I’ll explain a little more about the State and Transition classes as they are critical to understanding how the state machine works.</p>  <h5>States &amp; Transitions</h5>  <p>A state machine comprises a collection of states and a collection of transitions between states. There’s always one initial state, and you can optionally have a final state (which completes the execution of the workflow instance). When you enter a state you can optionally run some activities, and similarly when you exit a state you can also execute some activities. To define the entry and exit activities, double click on the state in the designer which will show something like the following (I chose the ClosedLocked state from the above diagram)…</p>  <h5><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/0640.State_69DCCA70.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/0640.State_5F00_69DCCA70.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="State" border="0" alt="State" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/5430.State_thumb_3AAADED9.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/5430.State_5F00_thumb_5F00_3AAADED9.png" width="379" height="484" /></a> </h5>  <p>When a state activity executes it calls the Entry activity (which can of course be a Sequence so that you can run multiple activities) and we then find all outgoing transitions. We then execute each transition, which in the case of my state machine example executes a set of activities that create a bookmark and then wait for this bookmark to be resumed. This may seem a bit odd – if you have 3 transitions we schedule the Trigger activity (shown in the image below) for each of the 3 branches. When the state machine engine then does is waits for one of these activities to complete, and whichever gets in first will ‘win’ and that transition will complete.</p>  <p>&#160;</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/0640.Transition_60345C3A.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/0640.Transition_5F00_60345C3A.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="Transition" border="0" alt="Transition" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/2112.Transition_thumb_77EB93A0.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/2112.Transition_5F00_thumb_5F00_77EB93A0.png" width="344" height="484" /></a> </p>  <p>&#160;</p>  <p>Possibly the easiest way to view transitions is as a Pick activity. When you are in a given state, we effectively execute each transition branch in a similar manner to that of the Pick activity, and the first activity to complete will complete the transition. You can optionally include a Condition on the transition which is evaluated when the trigger event occurs and the transition is only completed if the condition returns true. In the ClosedLocked state we’re effectively waiting as follows…</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/4784.PickExample_75CE94D7.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/4784.PickExample_5F00_75CE94D7.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="PickExample" border="0" alt="PickExample" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/4774.PickExample_thumb_090F4B77.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/4774.PickExample_5F00_thumb_5F00_090F4B77.png" width="644" height="271" /></a> I’ve omitted any Actions in the above as the transition branch works in a slightly different manner to Pick. When the transitions Trigger activity completes (and assuming the condition evaluates to true) we’ll also execute the Action activity if you’ve created one.</p>  <p>So, in a state we’re waiting for an activity to complete, and in the above image I have a custom activity shown as the DoorUnlocked and DoorLocked activities. These are instances of the DoorEvent activity which uses a bookmark that can be resumed by the client. The code for this activity is fairly trivial and is shown below…</p>  <pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">DoorEvent </span>: <span style="color: #2b91af">NativeActivity
</span>{
<span style="color: gray">    </span><span style="color: blue">protected override bool </span>CanInduceIdle
    {
        <span style="color: blue">get </span>{ <span style="color: blue">return true</span>; }
    }

    [<span style="color: #2b91af">RequiredArgument</span>]
    <span style="color: blue">public </span><span style="color: #2b91af">InArgument</span>&lt;<span style="color: blue">string</span>&gt; BookmarkName { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }

<span style="color: blue">    protected override void </span>Execute(<span style="color: #2b91af">NativeActivityContext </span>context)
    {
        context.CreateBookmark(BookmarkName.Get(context), <span style="color: blue">new </span><span style="color: #2b91af">BookmarkCallback</span>(OnBookmarkResumed));
    }

 <span style="color: gray">   </span><span style="color: blue">private void </span>OnBookmarkResumed(<span style="color: #2b91af">NativeActivityContext </span>context, <span style="color: #2b91af">Bookmark </span>bookmark, <span style="color: blue">object </span>state)
    {
    }
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p>Not a great deal going on there really – it has a mandatory BookmarkName property which defines the name of the bookmark we’re using. In the example, the name of the bookmark matches the transition label.</p>

<h5>Hosting in WPF</h5>

<p>In the example I’m using a WPF host, and using the MVVM pattern (here with only a View Model) to maintain the user interface. The UI needs to know what state the state machine is in in order to resume appropriate bookmarks, so in each state activity I pass the state out to the View Model using another custom activity. This updates a property on the view model which in turn enables/disables parts of the UI.</p>

<p>There are a couple of classes used in the example for view models – the MainViewModel class is the root of the application, and it contains a set of DoorModel instances, one for each door shown on the UI. When a DoorModel is created it creates a WorkflowApplication instance and adds an extension to the instance (IDoor) that the door model implements. It is this extension that the workflow calls back to the door model on when notifying state changes. The pseudo code for the system is shown below…</p>

<ul>
  <li>The DoorModel instance is created. I set its name (shown on screen). </li>

  <li>An instance of the state machine is created inside a WorkflowApplication instance. This is passed an interface back to the door model that owns it (IDoor). </li>

  <li>The state machine starts up and immediately executes the first state activity ‘ClosedLocked’. This executes the SetDoorState activity which calls IDoor.SetState() and passes an enum value to the method to indicate what state the machine is in. </li>

  <li>The UI is updated to enable/disable commands as appropriate based on the state of the workflow. </li>
</ul>

<p>Thereafter the UI is in charge of the state machine. When a command such as ‘Unlock’ is executed, it simply resumes the appropriate bookmark on the state machine…</p>

<pre class="code">_unlockCommand = <span style="color: blue">new </span><span style="color: #2b91af">DelegateCommand</span>((unused) =&gt;
    {
        _stateMachine.ResumeBookmark(<span style="color: #a31515">&quot;Unlocked&quot;</span>, <span style="color: blue">null</span>);
    },
    (unused) =&gt;
    {
        <span style="color: blue">return this</span>.DoorState == <span style="color: #2b91af">DoorState</span>.ClosedLocked;
    });</pre>

<p><a href="http://11011.net/software/vspaste"></a>Here I’m using a DelegateCommand class so that I can use lambda functions to respond to the command (and also to define whether the command is valid or not based on the current state).</p>

<p>That’s pretty much all there is to it – as the user clicks around on the UI it executes the appropriate command, this resumes a bookmark which will then force a transition in the workflow, and when a new state is entered this calls back to the view model to indicate the new state. Simple.</p>

<p>There’s one other part of the application I wanted to call out and that’s the use of a custom PlaySound action on each transition. This simply plays a sound to indicate the state of the door (well, sort of!) when the transition completes. As an example there’s one sound used when the timeout happens but another when the door is manually locked. I initially defined these sounds in the ‘Entry’ element of each State activity, but this didn’t indicate the particular transition that had just occurred – i.e. there was no way to distinguish how the state machine had transitioned to the ClosedLocked state to allow me to play a different sound on entry to that activity.</p>

<p>When you run the application you’ll see the following wonderful UI…</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/8883.DoorLocked_66D73FF0.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/8883.DoorLocked_5F00_66D73FF0.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="DoorLocked" border="0" alt="DoorLocked" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/0488.DoorLocked_thumb_50A1249E.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/0488.DoorLocked_5F00_thumb_5F00_50A1249E.png" width="424" height="392" /></a> If you click on the Unlock button the workflow executes and changes the state to ClosedUnlocked. You’ll also see a couple more buttons show up that correspond to the now valid states (Lock and Open). If you unlock a door and then leave it for around 5 seconds the door will automatically lock again. For all transitions you’ll also be rewarded with some sounds – if these don’t work check the PlaySound activities in each transition and choose your own files to play (I’m on Windows 7 so the directory and files might be different from your machine).</p>

<h5>The Code</h5>

<p>Click <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/1588.Doors.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38/1588.Doors.zip">here</a> to download the source code and VS project. Feel free to tart up the user interface!</p>]]></content:encoded>
    </item>
    <item>
      <title>Creating multiple activities from the toolbox</title>
      <link>https://docs.microsoft.com/archive/blogs/morgan/creating-multiple-activities-from-the-toolbox</link>
      <pubDate>Fri, 11 Jun 2010 03:38:44 GMT</pubDate>
      <dc:creator><![CDATA[Clibbolasbolei]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/morgan/2010/06/11/creating-multiple-activities-from-the-toolbox/</guid>
      <description><![CDATA[This blog post will show you how you can add a custom tool to the toolbox which, when selected, will...]]></description>
      <content:encoded><![CDATA[<p>This blog post will show you how you can add a custom tool to the toolbox which, when selected, will drop a custom activity onto the designer surface. In addition I’ll also show how to get non-activity classes onto the toolbox. There are many times when you might want to do this – a couple are outlined below…</p>  <ul>   <li>You wish to drop a number of related activities, in a similar manner to when a Parallel is created and within it two branches are created for you </li>    <li>You have an item which is not an activity that you would like to drop onto the designer surface (such as the PickBranch) </li> </ul>  <p>When you create custom activities, Visual Studio will automagically add these to the toolbox (as long as they are within the same solution file). When you drag and drop an activity this activity is added to the designer. You can however augment this behaviour by implementing the IActivityTemplateFactory interface, which is used in preference to construction of the actual activity.</p>  <p>So, you can create a placeholder activity that shows up on the toolbox, but when it’s dropped it constructs an entirely different sent of activities on the designer surface. All you do is implement the <strong>Create</strong> method of <a href="http://msdn.microsoft.com/library/System.Activities.Presentation.IActivityTemplateFactory">IActivityTemplateFactory</a> and within this you can then create any activities (and optionally hook these together as you need).</p>  <h5>Stage 1 – Dropping related activities</h5>  <p>First up create a Workflow Console Application and then add an Activity Library project to the same solution. You can remove the Activity1.xaml file as we’ll not need that. Then add a reference to both the <strong>WindowsBase</strong> and also <strong>System.Activities.Presentation</strong> assemblies.</p>  <p>Next you can code up the Create method. An example is shown below…</p>  <pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">Dropper </span>: <span style="color: #2b91af">Activity</span>, <span style="color: #2b91af">IActivityTemplateFactory
</span>{
    <span style="color: blue">public </span><span style="color: #2b91af">Activity </span>Create(<span style="color: #2b91af">DependencyObject </span>target)
    {
        <span style="color: #2b91af">Pick </span>pick = <span style="color: blue">new </span><span style="color: #2b91af">Pick</span>();
        <span style="color: #2b91af">PickBranch </span>item = <span style="color: blue">new </span><span style="color: #2b91af">PickBranch</span>();
        item.DisplayName = <span style="color: #a31515">&quot;Branch1&quot;</span>;
        pick.Branches.Add(item);
        <span style="color: #2b91af">PickBranch </span>branch2 = <span style="color: blue">new </span><span style="color: #2b91af">PickBranch</span>();
        branch2.DisplayName = <span style="color: #a31515">&quot;Branch2&quot;</span>;
        pick.Branches.Add(branch2);
        <span style="color: blue">return </span>pick;
    }
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p>I shamelessly stole the code above from the <strong>PickWithTwoBranchesFactory</strong> class from the framework. Have a look in Reflector to find all classes that derive from IActivityTemplateFactory to get some ideas as to what the inbuilt factories do.</p>

<p>When you compile up your project you’ll find the ‘Dropper’ activity on the toolbox, and when you drag &amp; drop an instance of this activity you’ll get a Pick with two branches. Sorted.</p>

<p>Well, sort of.</p>

<p>I mentioned at the start of the article that I’d show how to drop not only a bunch of related activities, but also something that doesn’t derive from the Activity class. Your first thought might be to change the <strong>Create</strong> method and return (for example) a PickBanch, however there’s a problem. The return type is defined as Activity, so using this method to add non-Activity derived classes isn’t going to work.</p>

<h5>Stage 2 – Adding non-Activity classes to the toolbox</h5>

<p>If you are hosting the Workflow Designer yourself then this is as easy as adding anything else to the toolbox – you simply get hold of the ToolboxControl and add a new tool to it…</p>

<pre class="code"><span style="color: blue">private void </span>InitializeToolbox()
{
    <span style="color: #2b91af">ToolboxControl </span>toolbox = <span style="color: blue">new </span><span style="color: #2b91af">ToolboxControl</span>();
    <span style="color: #2b91af">ToolboxCategory </span>cat = <span style="color: blue">new </span><span style="color: #2b91af">ToolboxCategory</span>(<span style="color: #a31515">&quot;Activities&quot;</span>);
    cat.Tools.Add(<span style="color: blue">new </span><span style="color: #2b91af">ToolboxItemWrapper</span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">Sequence</span>), <span style="color: #a31515">&quot;Sequence&quot;</span>));
    cat.Tools.Add(<span style="color: blue">new </span><span style="color: #2b91af">ToolboxItemWrapper</span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">If</span>), <span style="color: #a31515">&quot;If/Else&quot;</span>));
    cat.Tools.Add(<span style="color: blue">new </span><span style="color: #2b91af">ToolboxItemWrapper</span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">Assign</span>), <span style="color: #a31515">&quot;Assign&quot;</span>));
    cat.Tools.Add(<span style="color: blue">new </span><span style="color: #2b91af">ToolboxItemWrapper</span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">Message</span>), <span style="color: #a31515">&quot;MessageBox&quot;</span>));
    cat.Tools.Add(<span style="color: blue">new </span><span style="color: #2b91af">ToolboxItemWrapper</span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">Pick</span>), <span style="color: #a31515">&quot;Pick&quot;</span>));
    cat.Tools.Add(<span style="color: blue">new </span><span style="color: #2b91af">ToolboxItemWrapper</span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">PickBranch</span>), <span style="color: #a31515">&quot;PickBranch&quot;</span>));
    toolbox.Categories.Add(cat);

    <span style="color: blue">this</span>.SetValue(<span style="color: blue">ref </span>_toolbox, toolbox, <span style="color: #a31515">&quot;Toolbox&quot;</span>);
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p>Here I’ve added a bunch of activities and also a PickBranch (which isn’t an Activity) to my toolbox. Simple.</p>

<p>The problem comes however when you want to do this within Visual Studio. The Workflow folks have very nicely integrated any custom activities into the toolbox so they show up as if by magic, but in order to get something onto the toolbox that isn’t an Activity you have to do a bit more work.</p>

<h5>Stage 3 – Adding non-Activity classes to the toolbox in Visual Studio</h5>

<p>There are currently (as far as I know!) two ways to do this. One is somewhat more involved than the other so I’ll present the easier of the two here. The first way is to create a Visual Studio Extensibility project which, when registered with Visual Studio, adds new items to the toolbox. The code for this is a bit on the gnarly side and there’s already an example of this available online (see the State Machine activity pack available on <a href="http://wf.codeplex.com/">codeplex</a>) so instead I’ll do the cheap &amp; cheerful approach.</p>

<p>In the second case what you can do is update the toolbox in Visual Studio from within the activity designer code itself. The trick (if you can call it that) in this instance is to add code to your activity designer that updates the toolbox when your main activity is added to the designer. There’s a nice managed interface that you can use from within your code which is <a href="http://msdn.microsoft.com/library/System.Activities.Presentation.IActivityToolboxService">IActivityToolboxService</a>.</p>

<p>What you need to do here is create an activity, add a designer to it, and within the designer you can then hook events (in particular the addition of the activity to the design surface), and at this point you can then add your other items to the toolbox.</p>

<p>In my example I’ve create a DayScheduler activity, which when dropped onto the design surface constructs two branches for you as I’ve also implemented IActivityTemplateFactory to construct these brnaches and add them as well…</p>

<p><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="DayScheduler" border="0" alt="DayScheduler" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/6378.DayScheduler_1.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/6378.DayScheduler_5F00_1.png" width="750" height="186" /> </p>

<p>The activity contains a number of branches similar to the Parallel activity – indeed I modelled most of the code on that activity as mine is very similar. When you drop the DayScheduler onto the designer it constructs two braches which are instances of the DaySchedulerBranch class. This class isn’t an activity – it’s simply a class derived from Object (in the same way as ParallelBranch is).</p>

<p>There' are two mandatory properties on the DayScheduleBranch – Action (an Activity) and ScheduleDays (an enum). This second property defines which day of the week the child activity will be scheduled – so the DayScheduler will execute children (pun intended) based on the current day of the week. In the example code when I add a DayScheduler activity I construct two branches – one that executes on weekdays only and another that executes on weekends only. You can add in any number of branches and select which days the child activities execute on. I defined an enum for this containing individual weekdays, and used the [Flags] attribute to also include all weekdays and both weekend days to make your life easier when selecting which day(s) your child activities should run.</p>

<p>The main point of the code is to show how, within Visual Studio, you can add non-Activity classes to the toolbox. This is done within the designer for the DayScheduler activity and the main parts of this designer class are shown below…</p>

<pre class="code"><span style="color: gray">/// &lt;summary&gt;
/// </span><span style="color: green">This designer updates the toolbox to add in a new tool as necessary
</span><span style="color: gray">/// &lt;/summary&gt;
</span><span style="color: blue">public partial class </span><span style="color: #2b91af">DaySchedulerDesigner
</span>{
    <span style="color: blue">public </span>DaySchedulerDesigner()
    {
        InitializeComponent();

        <span style="color: green">// Use the same cateory name as the assembly
        </span>_category = <span style="color: blue">this</span>.GetType().Assembly.GetName().Name;
    }

    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Hook the property change notification
    </span><span style="color: gray">/// &lt;/summary&gt;
    /// &lt;param name=&quot;newItem&quot;&gt;&lt;/param&gt;
    </span><span style="color: blue">protected override void </span>OnModelItemChanged(<span style="color: blue">object </span>newItem)
    {
        <span style="color: blue">base</span>.OnModelItemChanged(newItem);

        <span style="color: blue">if </span>(<span style="color: blue">null </span>== _toolbox)
            _toolbox = <span style="color: blue">this</span>.Context.Services.GetService&lt;<span style="color: #2b91af">IActivityToolboxService</span>&gt;();

        AddToolboxItem();
    }

    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Add the tool to the toolbox
    </span><span style="color: gray">/// &lt;/summary&gt;
    </span><span style="color: blue">private void </span>AddToolboxItem()
    {
        <span style="color: blue">bool </span>exists = _toolbox.EnumCategories().Contains(_category);

        <span style="color: blue">if </span>(!exists)
            _toolbox.AddCategory(_category);

        <span style="color: blue">string </span>_toolName = <span style="color: blue">typeof</span>(<span style="color: #2b91af">DaySchedulerBranch</span>).AssemblyQualifiedName;
        <span style="color: blue">bool </span>toolExists = _toolbox.EnumItems(_category).Contains(_toolName);

        <span style="color: blue">if </span>(!toolExists)
        {
            _toolbox.AddItem(_toolName, _category);
        }
    }

    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Stores a link to the toolbox
    </span><span style="color: gray">/// &lt;/summary&gt;
    </span><span style="color: blue">private </span><span style="color: #2b91af">IActivityToolboxService </span>_toolbox;

    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Defines the category that this tool is added to
    </span><span style="color: gray">/// &lt;/summary&gt;
    </span><span style="color: blue">private string </span>_category;
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p>The code overrides the OnModelItemChanged method which calls AddToolboxItem(). OnModelItemChanged is called when you drop the DayScheduler activity onto the designer, and here I obtain a reference to the IActivityToolboxService interface which is used to add/enumerat and delete items from the toolbox.</p>

<p>Within AddToolboxItem I then check if the category and tool have already been defined, and if not simply call the relevant methods to add the tool to the toolbox.</p>

<p>So, within Visual studio you’ll initially see just the DayScheduler activity within the toolbox, however once you’ve dropped an instance of this onto the designer you’ll then see the following in the toolbox…</p>

<p><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="DaySchedulerBranch" border="0" alt="DaySchedulerBranch" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/7360.DaySchedulerBranch_1.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/7360.DaySchedulerBranch_5F00_1.png" width="296" height="131" /> </p>

<p>You can then of course use this to drop an instance of the branch activity onto the design surface. Voila!</p>

<h5>The Download</h5>

<p>I’ve create a VS2010 project that includes all of the code for you to look at. Please download from <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/5040.UpdatingTheToolbox.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38/5040.UpdatingTheToolbox.zip">here</a>. If the code works it was written by me, if not I don’t know who wrote it.</p>]]></content:encoded>
    </item>
    <item>
      <title>Designers for custom activities</title>
      <link>https://docs.microsoft.com/archive/blogs/morgan/designers-for-custom-activities</link>
      <pubDate>Wed, 09 Jun 2010 05:27:22 GMT</pubDate>
      <dc:creator><![CDATA[Clibbolasbolei]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/morgan/2010/06/09/designers-for-custom-activities/</guid>
      <description><![CDATA[When writing a custom activity you’ll typically want to provide a custom designer which is used when...]]></description>
      <content:encoded><![CDATA[<p>When writing a custom activity you’ll typically want to provide a custom designer which is used when rendering your activity on the design surface. Visual Studio will look for designers using a couple of methods – one old, one new. In this post I’ll show how to use both methods and explain the differences.</p>  <p>Visual Studio has had the concept of designers from the first version of the framework, and this method uses the <a href="http://msdn.microsoft.com/library/System.ComponentModel.DesignerAttribute">[Designer]</a> attribute. To associate a designer with an activity you could write the following code…</p>  <pre class="code">[<span style="color: #2b91af">Designer</span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">CustomWriteLineDesigner</span>))]
<span style="color: blue">public class </span><span style="color: #2b91af">CustomWriteLine </span>: <span style="color: #2b91af">CodeActivity
</span>{
    <span style="color: blue">protected override void </span>Execute(<span style="color: #2b91af">CodeActivityContext </span>context)
    {
        <span style="color: green">// Your code here...
    </span>}
}</pre>

<p><a href="http://11011.net/software/vspaste"></a>Here the <a href="http://msdn.microsoft.com/library/System.ComponentModel.DesignerAttribute">[Designer]</a> attribute is using <strong>typeof</strong> to associate the designer class with the activity. The problem here is that there’s a hard-link between the activity class and its designer – usually you would create a designer in a separate assembly so that at runtime you would not need to load up the assembly that contains the designer(s).</p>

<p>In order to provide a soft-link you can use another override of the <a href="http://msdn.microsoft.com/library/System.ComponentModel.DesignerAttribute">[Designer]</a> attribute which takes a fully qualified type-name as in the following…</p>

<pre class="code">[<span style="color: #2b91af">Designer</span>(<span style="color: #a31515">&quot;CustomActivities.Designers.CustomWriteLineDesigner, CustomActivities.Designers&quot;</span>)]
<span style="color: blue">public class </span><span style="color: #2b91af">CustomWriteLine </span>: <span style="color: #2b91af">CodeActivity
</span>{
    <span style="color: blue">protected override void </span>Execute(<span style="color: #2b91af">CodeActivityContext </span>context)
    {
        <span style="color: green">// Your code here...
    </span>}
}</pre>

<p><a href="http://11011.net/software/vspaste"></a>This ensures that the activity assembly doesn’t need to add a reference to the designers assembly so all is good. Well, sort of.</p>

<p>The problem with the above is that the designer is more or less hard-coded, and if you wished to add a different designer you would have a hard job doing this.</p>

<h5>The new way</h5>

<p>If you look at any of the standard activities that come with Workflow 4 you’ll notice a distinct absence of any <a href="http://msdn.microsoft.com/library/System.ComponentModel.DesignerAttribute">[Designer]</a> attributes, so how does Visual Studio find the right designer? With WF 4 we now support the concept of registering a designer in another class – as in all things, every problem in computing can be solved by adding another level of indirection.</p>

<p>In this case it’s the <a href="http://msdn.microsoft.com/library/System.Activities.Presentation.Metadata.IRegisterMetadata">IRegisterMetadata</a> interface which is defined in the System.Activities.Presentation.Metadata namespace. This interface has one simple method – <strong>Register()</strong> which is called by Visual Studio under certain circumstances in order to register the designer (and indeed any other attributes) for your activity.</p>

<p>If you use Reflector you’ll find several classes that derive from this interface and they’re typically called &quot;DesignerMetadata”. If you’re hosting the WF designer yourself you need to add in the following call to ensure that the designers are registered for all standard activities…</p>

<pre class="code"><span style="color: blue">new </span><span style="color: #2b91af">DesignerMetadata</span>().Register();</pre>
<a href="http://11011.net/software/vspaste"></a>

<p>Internally the method constructs an instance of the <a href="http://msdn.microsoft.com/library/System.Activities.Presentation.Metadata.AttributeTableBuilder">AttributeTableBuilder</a> class, constructs a number of custom attributes, adds these to the builder and then calls AddAttributeTable on the <a href="http://msdn.microsoft.com/library/System.Activities.Presentation.Metadata.MetadataStore">MetadataStore</a> class…</p>

<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">DesignerMetadata </span>: <span style="color: #2b91af">IRegisterMetadata
</span>{
    <span style="color: blue">public void </span>Register()
    {
        <span style="color: #2b91af">AttributeTableBuilder </span>builder = <span style="color: blue">new </span><span style="color: #2b91af">AttributeTableBuilder</span>();

        builder.AddCustomAttributes(<span style="color: blue">typeof</span>(<span style="color: #2b91af">CustomWriteLine</span>), 
            <span style="color: blue">new </span><span style="color: #2b91af">DesignerAttribute</span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">CustomWriteLineDesigner</span>)));

        <span style="color: #2b91af">MetadataStore</span>.AddAttributeTable(builder.CreateTable());
    }
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p>In effect this code is simply using the <a href="http://msdn.microsoft.com/library/System.ComponentModel.TypeDescriptor">TypeDescriptor</a> class to add on a custom type provider, which is then used by the designer to find the <a href="http://msdn.microsoft.com/library/System.ComponentModel.DesignerAttribute">[Designer]</a> attribute (and possibly others) for any object added to the design surface. So, rather than have a hard reference from the Activity to its designer class, now we’re using an indirect method to register the designer. We’re still using the same attribute, but applying it in a separate assembly.</p>

<p>The nice thing here is that it allows you to completely change the look and feel of the standard activities as you can add in your own designer for any of them. Instead of calling DesignerMetadata.Register you can do the job yourself, and replace any standard designers with your own. I’d urge caution here – you might end up writing a load of designer code but it’s there if you wish to use it.</p>

<h5>Integration with Visual Studio</h5>

<p>Having gone to all the bother of creating your own class that derives from <a href="http://msdn.microsoft.com/library/System.Activities.Presentation.Metadata.IRegisterMetadata">IRegisterMetadata</a>, how do you tell Visual Studio to use this?</p>

<p>In this instance you need to do two things (and both are very important)…</p>

<ul>
  <li>If your creating CustomActivities.dll, create another assembly called CustomActivities<strong>.Design</strong>.dll </li>

  <li>Make sure that both assemblies reside in the same directory </li>
</ul>

<p>The last point may well trip you up – especially if you’re developing both assemblies in the same solution and you want the registration to update as you’re working. Even if you’re test project contains a reference to both dll’s the designer won’t update on the user interface in Visual Studio *unless* both assemblies build to the same directory (or rather, the *.Design.dll assembly builds to the same directory as the activity assembly).</p>

<p>The best way to ensure that the second point is sorted is to update the properties for the design assembly in Visual Studio and change the output path to be the same directory as your activity assembly…</p>

<p><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="CustomActivities" border="0" alt="CustomActivities" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/65/38/metablogapi/5444.CustomActivities_1.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-65-38-metablogapi/5444.CustomActivities_5F00_1.png" width="710" height="266" /> </p>

<p>Make sure you alter the output path for both the Debug and Release builds. And I love writing documentation so I always provide a documentation file to go along with my code. Yes – seriously!</p>

<h5>One more tweak</h5>

<p>There’s one more thing you can do to alter the design time behaviour of your activities and that’s to create another assembly that contains designers, but this time you’ll call it CustomActivities<strong>.VisualStudio.Design</strong>.dll.</p>

<p>If Visual Studio finds this assembly it will use this in addition to the .Design.dll. So, you could have one designer for mere mortals and another for developers. Maybe there are some properties that you only want developers to access – one example might be you wish to provide developers with an expression text box to define the value for an argument, but provide just a regular text box to less sophisticated users.</p>

<p>You can download a sample project from <a title="http://www.morganskinner.com/stuff/designtimeactivities.zip" href="http://www.morganskinner.com/stuff/designtimeactivities.zip">http://www.morganskinner.com/stuff/designtimeactivities.zip</a> which shows off the above. Change from a Debug/Release build to the Developer build and then reload the Workflow1.xaml file to see a different designer.</p>]]></content:encoded>
    </item>
  </channel>
</rss>