<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Patrick Cauldwell's Blog</title>
    <link>http://www.cauldwell.net/patrick/blog/</link>
    <description>stuff I do at work, and occasionally some stuff I don't</description>
    <language>en-us</language>
    <copyright>Patrick Cauldwell</copyright>
    <lastBuildDate>Wed, 27 Oct 2010 21:32:51 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>patrick@cauldwell.net</managingEditor>
    <webMaster>patrick@cauldwell.net</webMaster>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=9b42e67a-97fb-468b-94ba-f5a6bfe8af28</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,9b42e67a-97fb-468b-94ba-f5a6bfe8af28.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,9b42e67a-97fb-468b-94ba-f5a6bfe8af28.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=9b42e67a-97fb-468b-94ba-f5a6bfe8af28</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
It’s not uncommon to want to dynamically add new sections to an XML file, such as
a config file, without having to recompile existing code for processing said XML file. 
One common example is the way that .NET’s app.config file supports a config section
/ config section handler model.  You can add new arbitrary XML that is specific
to a particular bit of code in its schema, then register a “handler” for that config
section so that the standard System.Configuration classes can read and deal with that
otherwise unknown schema.  
</p>
        <p>
Rather then explicitly registering “handlers” in the XML file itself, we can use the
Managed Extensibility Framework (MEF), which is now a fully baked part of the .NET
4 framework.  
</p>
        <p>
Let’s say I start off with a configuration file that looks like this
</p>
        <pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;configuration&gt;
  &lt;products&gt;
    &lt;product name="Product1"&gt;
      &lt;P1Config&gt;
        &lt;secretP1Value&gt;42&lt;/secretP1Value&gt;
      &lt;/P1Config&gt;
    &lt;/product&gt;
    &lt;product name="Product2"&gt;
      &lt;Product2Config&gt;
        &lt;installedFeatures&gt;
          &lt;feature id="1"/&gt;
          &lt;feature id="36"/&gt;
        &lt;/installedFeatures&gt;
      &lt;/Product2Config&gt;
    &lt;/product&gt;
  &lt;/products&gt;
&lt;/configuration&gt;</pre>
        <p>
I want to be able to add new &lt;product&gt; sections in the future which will contain
XML that only that particular product’s plugin will know what to do with.  
</p>
        <p>
MEF is all about the “plugin” pattern.  It allows me to declare “Exported” contracts
that plugins essentially publish for use, and to declare that other components “Import”
those plugins, meaning they require a runtime instance of one or more of those published
exports.  For the sake of the above example, I’ve defined an interface that each
product plugin will need to support to process the XML from its config section.
</p>
        <pre class="brush: csharp;">interface IProductPlugin
{
    bool Configure(XElement config);
}</pre>
        <p>
When the overall XML file is processed, an instance of each product’s plugin will
be instantiated and “fed” the XElement that represents its config section.  MEF
makes it easy to choose which plugin gets loaded for each section using named contracts. 
The following two plugins
</p>
        <pre class="brush: csharp;">[Export("Product1", typeof(IProductPlugin))]
public class ProductOnePlugin : IProductPlugin
{
    public bool Configure(XElement config)
    {
        var secret = from el in config.Descendants()
                     where el.Name == "secretP1Value"
                     select el.Value;

        Debug.WriteLine(secret.FirstOrDefault());

        return true;
    }
}

[Export("Product2", typeof(IProductPlugin))]
public class ProductTwoPlugin : IProductPlugin
{
    public bool Configure(XElement config)
    {
        var installed = from el in config.Descendants()
                        where el.Name == "feature"
                        select el.Attribute("id").Value;

        foreach (var off in installed)
        {
            Debug.WriteLine(off);
        }

        return true;
    }
}</pre>
        <p>
both export the IProductPlugin interface, but they also declare a name under which
it will be exported.  We can use a corresponding “name” attribute in the &lt;product&gt;
element of each section to get the right plugin.  At runtime, the code to load
the file reads each product element and instantiates the right plugin by asking MEF
for the named instance from MEF’s catalog.
</p>
        <pre class="brush: csharp;">XDocument top = XDocument.Load(s);
var products = from product in top.Root.Element("products").Elements()
               select product;

foreach (var prod in products)
{
    string name = prod.Attribute("name").Value;
    var plugin = _container.GetExport&lt;IProductPlugin&gt;(name);
    plugin.Value.Configure(prod);
}</pre>
        <p>
The key in this case is the GetExport method.  It optionally takes that arbitrary
string and tries to find the right instance from the catalog.  In this particular
case, for the sake of simplicity, the catalog is loaded from the running assembly.
</p>
        <pre class="brush: csharp;">_container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
_container.ComposeParts(this);</pre>
        <p>
In practice, I would use the DirectoryCatalog class to build the catalog from all
the assemblies in one directory, which would allow new plugin assemblies to be simply
dropped into place without anything needing to be compiled.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Using MEF for extensible XML processing</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,9b42e67a-97fb-468b-94ba-f5a6bfe8af28.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/UsingMEFForExtensibleXMLProcessing.aspx</link>
      <pubDate>Wed, 27 Oct 2010 21:32:51 GMT</pubDate>
      <description>&lt;p&gt;
It’s not uncommon to want to dynamically add new sections to an XML file, such as
a config file, without having to recompile existing code for processing said XML file.&amp;#160;
One common example is the way that .NET’s app.config file supports a config section
/ config section handler model.&amp;#160; You can add new arbitrary XML that is specific
to a particular bit of code in its schema, then register a “handler” for that config
section so that the standard System.Configuration classes can read and deal with that
otherwise unknown schema.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
Rather then explicitly registering “handlers” in the XML file itself, we can use the
Managed Extensibility Framework (MEF), which is now a fully baked part of the .NET
4 framework.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
Let’s say I start off with a configuration file that looks like this
&lt;/p&gt;
&lt;pre class="brush: xml;"&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;
&amp;lt;configuration&amp;gt;
  &amp;lt;products&amp;gt;
    &amp;lt;product name=&amp;quot;Product1&amp;quot;&amp;gt;
      &amp;lt;P1Config&amp;gt;
        &amp;lt;secretP1Value&amp;gt;42&amp;lt;/secretP1Value&amp;gt;
      &amp;lt;/P1Config&amp;gt;
    &amp;lt;/product&amp;gt;
    &amp;lt;product name=&amp;quot;Product2&amp;quot;&amp;gt;
      &amp;lt;Product2Config&amp;gt;
        &amp;lt;installedFeatures&amp;gt;
          &amp;lt;feature id=&amp;quot;1&amp;quot;/&amp;gt;
          &amp;lt;feature id=&amp;quot;36&amp;quot;/&amp;gt;
        &amp;lt;/installedFeatures&amp;gt;
      &amp;lt;/Product2Config&amp;gt;
    &amp;lt;/product&amp;gt;
  &amp;lt;/products&amp;gt;
&amp;lt;/configuration&amp;gt;&lt;/pre&gt;
&lt;p&gt;
I want to be able to add new &amp;lt;product&amp;gt; sections in the future which will contain
XML that only that particular product’s plugin will know what to do with.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
MEF is all about the “plugin” pattern.&amp;#160; It allows me to declare “Exported” contracts
that plugins essentially publish for use, and to declare that other components “Import”
those plugins, meaning they require a runtime instance of one or more of those published
exports.&amp;#160; For the sake of the above example, I’ve defined an interface that each
product plugin will need to support to process the XML from its config section.
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;interface IProductPlugin
{
    bool Configure(XElement config);
}&lt;/pre&gt;
&lt;p&gt;
When the overall XML file is processed, an instance of each product’s plugin will
be instantiated and “fed” the XElement that represents its config section.&amp;#160; MEF
makes it easy to choose which plugin gets loaded for each section using named contracts.&amp;#160;
The following two plugins
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;[Export(&amp;quot;Product1&amp;quot;, typeof(IProductPlugin))]
public class ProductOnePlugin : IProductPlugin
{
    public bool Configure(XElement config)
    {
        var secret = from el in config.Descendants()
                     where el.Name == &amp;quot;secretP1Value&amp;quot;
                     select el.Value;

        Debug.WriteLine(secret.FirstOrDefault());

        return true;
    }
}

[Export(&amp;quot;Product2&amp;quot;, typeof(IProductPlugin))]
public class ProductTwoPlugin : IProductPlugin
{
    public bool Configure(XElement config)
    {
        var installed = from el in config.Descendants()
                        where el.Name == &amp;quot;feature&amp;quot;
                        select el.Attribute(&amp;quot;id&amp;quot;).Value;

        foreach (var off in installed)
        {
            Debug.WriteLine(off);
        }

        return true;
    }
}&lt;/pre&gt;
&lt;p&gt;
both export the IProductPlugin interface, but they also declare a name under which
it will be exported.&amp;#160; We can use a corresponding “name” attribute in the &amp;lt;product&amp;gt;
element of each section to get the right plugin.&amp;#160; At runtime, the code to load
the file reads each product element and instantiates the right plugin by asking MEF
for the named instance from MEF’s catalog.
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;XDocument top = XDocument.Load(s);
var products = from product in top.Root.Element(&amp;quot;products&amp;quot;).Elements()
               select product;

foreach (var prod in products)
{
    string name = prod.Attribute(&amp;quot;name&amp;quot;).Value;
    var plugin = _container.GetExport&amp;lt;IProductPlugin&amp;gt;(name);
    plugin.Value.Configure(prod);
}&lt;/pre&gt;
&lt;p&gt;
The key in this case is the GetExport method.&amp;#160; It optionally takes that arbitrary
string and tries to find the right instance from the catalog.&amp;#160; In this particular
case, for the sake of simplicity, the catalog is loaded from the running assembly.
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;_container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
_container.ComposeParts(this);&lt;/pre&gt;
&lt;p&gt;
In practice, I would use the DirectoryCatalog class to build the catalog from all
the assemblies in one directory, which would allow new plugin assemblies to be simply
dropped into place without anything needing to be compiled.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,9b42e67a-97fb-468b-94ba-f5a6bfe8af28.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=c32e2886-5843-45a8-9051-3966b92a01fe</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,c32e2886-5843-45a8-9051-3966b92a01fe.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,c32e2886-5843-45a8-9051-3966b92a01fe.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=c32e2886-5843-45a8-9051-3966b92a01fe</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I’ll be <a href="http://padnug.org/meetings.aspx?ID=225">speaking at PADNUG</a> next
Tuesday about the wonders of WF 4 and how to apply it to real world problems. 
We’ll look at what problems WF solves, when it might be appropriate, and how to get
started building your own workflows.  We’ll also look at using WF/WCF integration
to create “declarative services” or “workflow services” quickly and easily.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Intro to Windows Workflow 4</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,c32e2886-5843-45a8-9051-3966b92a01fe.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/IntroToWindowsWorkflow4.aspx</link>
      <pubDate>Wed, 27 Oct 2010 16:40:47 GMT</pubDate>
      <description>&lt;p&gt;
I’ll be &lt;a href="http://padnug.org/meetings.aspx?ID=225"&gt;speaking at PADNUG&lt;/a&gt; next
Tuesday about the wonders of WF 4 and how to apply it to real world problems.&amp;#160;
We’ll look at what problems WF solves, when it might be appropriate, and how to get
started building your own workflows.&amp;#160; We’ll also look at using WF/WCF integration
to create “declarative services” or “workflow services” quickly and easily.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,c32e2886-5843-45a8-9051-3966b92a01fe.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=8e51fbca-77fe-45e8-8c03-d1967c494b5c</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,8e51fbca-77fe-45e8-8c03-d1967c494b5c.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,8e51fbca-77fe-45e8-8c03-d1967c494b5c.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=8e51fbca-77fe-45e8-8c03-d1967c494b5c</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
As of this week, I’m now working at WebMD Health Service in NW Portland.  I’m
looking forward to working with the very smart people here, and learning about the
latest in ASP.NET and Agile development in the enterprise.
</p>
        <p>
More information to follow as the situation warrants. <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://www.cauldwell.net/patrick/blog/content/binary/WindowsLiveWriter/Changeofscene_A1BC/wlEmoticon-smile_2.png" /></p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Change of scene</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,8e51fbca-77fe-45e8-8c03-d1967c494b5c.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/ChangeOfScene.aspx</link>
      <pubDate>Wed, 15 Sep 2010 18:30:54 GMT</pubDate>
      <description>&lt;p&gt;
As of this week, I’m now working at WebMD Health Service in NW Portland.&amp;#160; I’m
looking forward to working with the very smart people here, and learning about the
latest in ASP.NET and Agile development in the enterprise.
&lt;/p&gt;
&lt;p&gt;
More information to follow as the situation warrants. &lt;img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://www.cauldwell.net/patrick/blog/content/binary/WindowsLiveWriter/Changeofscene_A1BC/wlEmoticon-smile_2.png" /&gt;
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,8e51fbca-77fe-45e8-8c03-d1967c494b5c.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=a7121a47-fa7d-4271-afd0-d9e87f5095f1</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,a7121a47-fa7d-4271-afd0-d9e87f5095f1.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,a7121a47-fa7d-4271-afd0-d9e87f5095f1.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=a7121a47-fa7d-4271-afd0-d9e87f5095f1</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">A while back I posted a <a href="http://www.cauldwell.net/patrick/blog/DefaultButtonSemanticsInSilverlightRevisited.aspx">revision </a>to
my original default button sample that made it a bit easier to use, but there was
still an issue...  If you invoke the button while the focus is still in a text
box, any changes made to the text in the text box may not get pushed into the databinding
source, since by default that happens when the text box loses focus.  I didn't
come up with a good solution, but luckily somebody did. :)  I got the following
revision from Glenn Orr, and this should solve the problem.  If you have any
custom data entry controls, etc. you may have to add additional clauses to handle
them, but this will work with text boxes for sure.<br /><br />
Change the OnKeyUp method to look like this...<br /><pre><span style="font-family: Consolas; color: blue;"><br /></span><span style="font-family: Consolas;"></span></pre><br /><pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">private void OnKeyUp(object sender, KeyEventArgs arg)
{
	  if (arg.Key == Key.Enter)
			  if (peer != null)
			   {
					   if (sender is TextBox)
					  {
							   BindingExpression expression = (sender as TextBox).GetBindingExpression(TextBox.TextProperty);
							   expression.UpdateSource();
					  }
					  ((IInvokeProvider)peer).Invoke();
			  }
}</pre>
This will make sure that any changes get pushed into the databinding source before
the button is invoked. Thanks Glenn!<br /><hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Default button semantics in Silverlight, once more</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,a7121a47-fa7d-4271-afd0-d9e87f5095f1.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/DefaultButtonSemanticsInSilverlightOnceMore.aspx</link>
      <pubDate>Thu, 02 Sep 2010 17:00:05 GMT</pubDate>
      <description>A while back I posted a &lt;a href="http://www.cauldwell.net/patrick/blog/DefaultButtonSemanticsInSilverlightRevisited.aspx"&gt;revision &lt;/a&gt;to
my original default button sample that made it a bit easier to use, but there was
still an issue...&amp;nbsp; If you invoke the button while the focus is still in a text
box, any changes made to the text in the text box may not get pushed into the databinding
source, since by default that happens when the text box loses focus.&amp;nbsp; I didn't
come up with a good solution, but luckily somebody did. :)&amp;nbsp; I got the following
revision from Glenn Orr, and this should solve the problem.&amp;nbsp; If you have any
custom data entry controls, etc. you may have to add additional clauses to handle
them, but this will work with text boxes for sure.&lt;br&gt;
&lt;br&gt;
Change the OnKeyUp method to look like this...&lt;br&gt;
&lt;pre&gt;&lt;span style="font-family: Consolas; color: blue;"&gt;
&lt;br&gt;
&lt;/span&gt;&lt;span style="font-family: Consolas;"&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;br&gt;
&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;private void OnKeyUp(object sender, KeyEventArgs arg)
{
	  if (arg.Key == Key.Enter)
			  if (peer != null)
			   {
					   if (sender is TextBox)
					  {
							   BindingExpression expression = (sender as TextBox).GetBindingExpression(TextBox.TextProperty);
							   expression.UpdateSource();
					  }
					  ((IInvokeProvider)peer).Invoke();
			  }
}&lt;/pre&gt;
This will make sure that any changes get pushed into the databinding source before
the button is invoked. Thanks Glenn!&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,a7121a47-fa7d-4271-afd0-d9e87f5095f1.aspx</comments>
      <category>Silverlight</category>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=0817f628-d359-4430-815e-48e9ed69ce26</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,0817f628-d359-4430-815e-48e9ed69ce26.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,0817f628-d359-4430-815e-48e9ed69ce26.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=0817f628-d359-4430-815e-48e9ed69ce26</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
The sample app I used for my Code Camp presentation is <a href="http://www.cauldwell.net/patrick/files/codecamp.zip">here</a>. 
I’ll post details about the sample later in the week.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Code Camp sample app</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,0817f628-d359-4430-815e-48e9ed69ce26.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/CodeCampSampleApp.aspx</link>
      <pubDate>Mon, 24 May 2010 03:26:25 GMT</pubDate>
      <description>&lt;p&gt;
The sample app I used for my Code Camp presentation is &lt;a href="http://www.cauldwell.net/patrick/files/codecamp.zip"&gt;here&lt;/a&gt;.&amp;#160;
I’ll post details about the sample later in the week.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,0817f628-d359-4430-815e-48e9ed69ce26.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=50a99489-e5e6-481c-879b-784fd7b9ddfc</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,50a99489-e5e6-481c-879b-784fd7b9ddfc.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,50a99489-e5e6-481c-879b-784fd7b9ddfc.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=50a99489-e5e6-481c-879b-784fd7b9ddfc</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
While I guess I understand why this would be a problem, I don’t understand why it
worked before…
</p>
        <p>
If I want to create a style for a button, let’s say with a red background, I might
create a brush resource that defines my special color of red, then reference that
brush in a style resource like so
</p>
        <pre class="brush: xml;">&lt;SolidColorBrush x:Key="TheBrush"&gt;
    &lt;SolidColorBrush.Color&gt;Red&lt;/SolidColorBrush.Color&gt;
&lt;/SolidColorBrush&gt;            
&lt;Style x:Key="RedButton" TargetType="Button"&gt;
    &lt;Setter Property="Background" Value="{StaticResource TheBrush}"/&gt;
&lt;/Style&gt;</pre>
        <p>
That works just fine.  I get a red button like this
</p>
        <p>
          <a href="http://www.cauldwell.net/patrick/blog/images/WPF4breakingchangebetweenRCandRelease_B305/image.png">
            <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/WPF4breakingchangebetweenRCandRelease_B305/image_thumb.png" width="90" height="42" />
          </a>
        </p>
        <p>
If the two resources are in the opposite order
</p>
        <pre class="brush: xml;">&lt;Style x:Key="RedButton" TargetType="Button"&gt;
    &lt;Setter Property="Background" Value="{StaticResource TheBrush}"/&gt;
&lt;/Style&gt;
&lt;SolidColorBrush x:Key="TheBrush"&gt;
    &lt;SolidColorBrush.Color&gt;Red&lt;/SolidColorBrush.Color&gt;
&lt;/SolidColorBrush&gt; </pre>
        <p>
        </p>
        <p>
then at runtime I’m going to end up with an exception because the resource “TheBrush”
can’t be found.  Hmmm.  I suppose that makes sense if we imagine the XAML
processor instancing objects as it comes to them in the XZML file.  It would
try to instance “RedButton” and not be able to create the static reference to “TheBrush”
because that object hasn’t been instanced yet.
</p>
        <p>
If I happen to apply that style some something in my XAML 
</p>
        <pre class="brush: xml; highlight: [2];">&lt;Button 
    Style="{StaticResource RedButton}" 
    Content="Red Button" Height="23"
    Click="button1_Click" /&gt;</pre>
        <p>
I’ll get a compile error.  OK.  If, however, the reference to “RedButton”
is in something like a DataTemplate that doesn’t get applied until runtime, then I
get a rather jarring runtime exception instead.  
</p>
        <p>
Again, I suppose this behavior makes sense given my theoretical model of the XAML
processor (though it smacks of C++-ishness).  What doesn’t make sense is why
it worked just fine in the RC, and just recompiling in the release of VS 2010 I now
get runtime exceptions.  Something obviously changed in the way resources are
loaded and/or referenced at runtime.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>WPF 4: breaking change between RC and Release</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,50a99489-e5e6-481c-879b-784fd7b9ddfc.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/WPF4BreakingChangeBetweenRCAndRelease.aspx</link>
      <pubDate>Thu, 15 Apr 2010 20:02:03 GMT</pubDate>
      <description>&lt;p&gt;
While I guess I understand why this would be a problem, I don’t understand why it
worked before…
&lt;/p&gt;
&lt;p&gt;
If I want to create a style for a button, let’s say with a red background, I might
create a brush resource that defines my special color of red, then reference that
brush in a style resource like so
&lt;/p&gt;
&lt;pre class="brush: xml;"&gt;&amp;lt;SolidColorBrush x:Key=&amp;quot;TheBrush&amp;quot;&amp;gt;
    &amp;lt;SolidColorBrush.Color&amp;gt;Red&amp;lt;/SolidColorBrush.Color&amp;gt;
&amp;lt;/SolidColorBrush&amp;gt;            
&amp;lt;Style x:Key=&amp;quot;RedButton&amp;quot; TargetType=&amp;quot;Button&amp;quot;&amp;gt;
    &amp;lt;Setter Property=&amp;quot;Background&amp;quot; Value=&amp;quot;{StaticResource TheBrush}&amp;quot;/&amp;gt;
&amp;lt;/Style&amp;gt;&lt;/pre&gt;
&lt;p&gt;
That works just fine.&amp;#160; I get a red button like this
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.cauldwell.net/patrick/blog/images/WPF4breakingchangebetweenRCandRelease_B305/image.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/WPF4breakingchangebetweenRCandRelease_B305/image_thumb.png" width="90" height="42" /&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
If the two resources are in the opposite order
&lt;/p&gt;
&lt;pre class="brush: xml;"&gt;&amp;lt;Style x:Key=&amp;quot;RedButton&amp;quot; TargetType=&amp;quot;Button&amp;quot;&amp;gt;
    &amp;lt;Setter Property=&amp;quot;Background&amp;quot; Value=&amp;quot;{StaticResource TheBrush}&amp;quot;/&amp;gt;
&amp;lt;/Style&amp;gt;
&amp;lt;SolidColorBrush x:Key=&amp;quot;TheBrush&amp;quot;&amp;gt;
    &amp;lt;SolidColorBrush.Color&amp;gt;Red&amp;lt;/SolidColorBrush.Color&amp;gt;
&amp;lt;/SolidColorBrush&amp;gt; &lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
then at runtime I’m going to end up with an exception because the resource “TheBrush”
can’t be found.&amp;#160; Hmmm.&amp;#160; I suppose that makes sense if we imagine the XAML
processor instancing objects as it comes to them in the XZML file.&amp;#160; It would
try to instance “RedButton” and not be able to create the static reference to “TheBrush”
because that object hasn’t been instanced yet.
&lt;/p&gt;
&lt;p&gt;
If I happen to apply that style some something in my XAML 
&lt;/p&gt;
&lt;pre class="brush: xml; highlight: [2];"&gt;&amp;lt;Button 
    Style=&amp;quot;{StaticResource RedButton}&amp;quot; 
    Content=&amp;quot;Red Button&amp;quot; Height=&amp;quot;23&amp;quot;
    Click=&amp;quot;button1_Click&amp;quot; /&amp;gt;&lt;/pre&gt;
&lt;p&gt;
I’ll get a compile error.&amp;#160; OK.&amp;#160; If, however, the reference to “RedButton”
is in something like a DataTemplate that doesn’t get applied until runtime, then I
get a rather jarring runtime exception instead.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
Again, I suppose this behavior makes sense given my theoretical model of the XAML
processor (though it smacks of C++-ishness).&amp;#160; What doesn’t make sense is why
it worked just fine in the RC, and just recompiling in the release of VS 2010 I now
get runtime exceptions.&amp;#160; Something obviously changed in the way resources are
loaded and/or referenced at runtime.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,50a99489-e5e6-481c-879b-784fd7b9ddfc.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=0106405c-8a3a-4b4b-9400-ecd078e6d6ec</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,0106405c-8a3a-4b4b-9400-ecd078e6d6ec.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,0106405c-8a3a-4b4b-9400-ecd078e6d6ec.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=0106405c-8a3a-4b4b-9400-ecd078e6d6ec</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
We just caught this one this morning…  It looks like WF 4 reuses activity instances
across workflow instances.  So if I have a WorkflowService that’s hosted in IIS,
and I call it from two different client threads at the same time, the two workflow
instances now running on the server may be using the same activity instances for child
activities.  The documentation is not clear on this point, but that’s the behavior
we observed.  
</p>
        <p>
The implication is that you have to treat calls to your Activity’s Execute method
as stateless, and not maintain any state in your activity between calls to Execute. 
(Our specific problem was around EntityFramework containers.  Apparently they
don’t like being called on multiple threads. :) )
</p>
        <p>
Makes sense, but it’s not clear at all from the documentation that it would be the
case.  You can rely on the thread safety of your InArguments and OutArguments,
since they are accessed through the context, but private fields are right out unless
whatever you store in them is also threadsafe.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Workflow 4 Activity instances may be reused</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,0106405c-8a3a-4b4b-9400-ecd078e6d6ec.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/Workflow4ActivityInstancesMayBeReused.aspx</link>
      <pubDate>Fri, 12 Feb 2010 19:14:40 GMT</pubDate>
      <description>&lt;p&gt;
We just caught this one this morning…&amp;#160; It looks like WF 4 reuses activity instances
across workflow instances.&amp;#160; So if I have a WorkflowService that’s hosted in IIS,
and I call it from two different client threads at the same time, the two workflow
instances now running on the server may be using the same activity instances for child
activities.&amp;#160; The documentation is not clear on this point, but that’s the behavior
we observed.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
The implication is that you have to treat calls to your Activity’s Execute method
as stateless, and not maintain any state in your activity between calls to Execute.&amp;#160;
(Our specific problem was around EntityFramework containers.&amp;#160; Apparently they
don’t like being called on multiple threads. :) )
&lt;/p&gt;
&lt;p&gt;
Makes sense, but it’s not clear at all from the documentation that it would be the
case.&amp;#160; You can rely on the thread safety of your InArguments and OutArguments,
since they are accessed through the context, but private fields are right out unless
whatever you store in them is also threadsafe.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,0106405c-8a3a-4b4b-9400-ecd078e6d6ec.aspx</comments>
      <category>.NET 4</category>
      <category>Web Services</category>
      <category>WF</category>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=484a23ed-2508-4ba2-baa0-5a2efa13d325</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,484a23ed-2508-4ba2-baa0-5a2efa13d325.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,484a23ed-2508-4ba2-baa0-5a2efa13d325.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=484a23ed-2508-4ba2-baa0-5a2efa13d325</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This is probably one of those things that is obvious to everyone but me, but just
in case it’s not… 
</p>
        <p>
We’re using Unity as our IoC container, and we are also using .NET 4 Workflow Services
hosted in IIS, meaning .xamlx files that are served up by IIS 7.  In order to
get full value out of Unity, we need one instance of the Unity container that gets
properly configured somewhere that is then available to any WF activity that might
need to resolve a reference.  But…since IIS is hosting, there’s no direct access
to the WorkflowServiceHost to add the Unity container as an extension (which is how
we do it in places where we are hosting using WorkflowApplication in WPF apps, etc.). 
I suspected that the solution was a WCF Service Behavior extension, because that’s
how you set up a tracking participant if you are hosted in IIS, and luckily that turned
out to be the case.  I’d been putting off nailing it down because I suspected
it was hard, but as luck would have it (or, rather, the cleverness of the ServiceModel
team) it’s not hard at all.
</p>
        <p>
First, we need a behavior extension that creates (and ultimately configures) the Unity
container.  It has to implement IServiceBehavior, since we need it to be a service
behavior to get access to the host.
</p>
        <pre class="brush: csharp;">public class UnityServiceBehavior : IServiceBehavior
{

    #region IServiceBehavior Members

    public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection&lt;ServiceEndpoint&gt; endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {
        
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {
         WorkflowServiceHost host = serviceHostBase as WorkflowServiceHost;
         if (host != null)
         {
             IUnityContainer container = new UnityContainer();
             host.WorkflowExtensions.Add&lt;IUnityContainer&gt;(delegate { return container; });
         }
   
    }

    public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {
        
    }

    #endregion
}</pre>
Secondly, we want it to be configurable through web.config, which calls for a BehaviorExtensionElement.  <pre class="brush: csharp;">public class UnityBehaviorElementExtension : BehaviorExtensionElement
{
    public override Type BehaviorType
    {
        get { return typeof(UnityServiceBehavior); }
    }

    protected override object CreateBehavior()
    {
        return new UnityServiceBehavior();
    }
}</pre><p>
Then, in our web.config, just register the extension, which in turn will configure
and return behavior.
</p><pre class="brush: xml;">&lt;system.serviceModel&gt;
  &lt;behaviors&gt;
    &lt;serviceBehaviors&gt;
      &lt;behavior&gt;
        &lt;!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --&gt;
        &lt;serviceMetadata httpGetEnabled="true"/&gt;
        &lt;!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information --&gt;
        &lt;serviceDebug includeExceptionDetailInFaults="false"/&gt;
        &lt;unityExtension/&gt;
      &lt;/behavior&gt;
    &lt;/serviceBehaviors&gt;
  &lt;/behaviors&gt;
  &lt;extensions&gt;
    &lt;behaviorExtensions&gt;
      &lt;add name="unityExtension" type="UnityBehavior.UnityBehaviorElementExtension, UnityBehavior, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/&gt;
    &lt;/behaviorExtensions&gt;
  &lt;/extensions&gt;
  &lt;serviceHostingEnvironment multipleSiteBindingsEnabled="true" /&gt;
&lt;/system.serviceModel&gt;</pre><p>
In this case, the fact that the behavior element doesn’t include a name means the
set of behaviors it contains will be applied to any WCF service that is relying on
the default configuration (one of the coolest things in .NET 4!) which is how our
.xamlx file works in this example.
</p><p>
Once all that’s done, from any activity in my .xamlx workflow I can access the IUnityContainer
interface as an extension.
</p><pre class="brush: csharp;">public sealed class CheckForUnity : CodeActivity
{
    // Define an activity input argument of type string
    public OutArgument&lt;bool&gt; HasUnity { get; set; }

    // If your activity returns a value, derive from CodeActivity&lt;TResult&gt;
    // and return the value from the Execute method.
    protected override void Execute(CodeActivityContext context)
    {
        IUnityContainer container = context.GetExtension&lt;IUnityContainer&gt;();

        context.SetValue&lt;bool&gt;(HasUnity, (container != null));
    }
}</pre><br /><hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Unity and WorkflowServices hosted in IIS</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,484a23ed-2508-4ba2-baa0-5a2efa13d325.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/UnityAndWorkflowServicesHostedInIIS.aspx</link>
      <pubDate>Thu, 11 Feb 2010 01:03:13 GMT</pubDate>
      <description>&lt;p&gt;
This is probably one of those things that is obvious to everyone but me, but just
in case it’s not… 
&lt;/p&gt;
&lt;p&gt;
We’re using Unity as our IoC container, and we are also using .NET 4 Workflow Services
hosted in IIS, meaning .xamlx files that are served up by IIS 7.&amp;#160; In order to
get full value out of Unity, we need one instance of the Unity container that gets
properly configured somewhere that is then available to any WF activity that might
need to resolve a reference.&amp;#160; But…since IIS is hosting, there’s no direct access
to the WorkflowServiceHost to add the Unity container as an extension (which is how
we do it in places where we are hosting using WorkflowApplication in WPF apps, etc.).&amp;#160;
I suspected that the solution was a WCF Service Behavior extension, because that’s
how you set up a tracking participant if you are hosted in IIS, and luckily that turned
out to be the case.&amp;#160; I’d been putting off nailing it down because I suspected
it was hard, but as luck would have it (or, rather, the cleverness of the ServiceModel
team) it’s not hard at all.
&lt;/p&gt;
&lt;p&gt;
First, we need a behavior extension that creates (and ultimately configures) the Unity
container.&amp;#160; It has to implement IServiceBehavior, since we need it to be a service
behavior to get access to the host.
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public class UnityServiceBehavior : IServiceBehavior
{

    #region IServiceBehavior Members

    public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection&amp;lt;ServiceEndpoint&amp;gt; endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {
        
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {
         WorkflowServiceHost host = serviceHostBase as WorkflowServiceHost;
         if (host != null)
         {
             IUnityContainer container = new UnityContainer();
             host.WorkflowExtensions.Add&amp;lt;IUnityContainer&amp;gt;(delegate { return container; });
         }
   
    }

    public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {
        
    }

    #endregion
}&lt;/pre&gt;
Secondly, we want it to be configurable through web.config, which calls for a BehaviorExtensionElement.&amp;#160; &lt;pre class="brush: csharp;"&gt;public class UnityBehaviorElementExtension : BehaviorExtensionElement
{
    public override Type BehaviorType
    {
        get { return typeof(UnityServiceBehavior); }
    }

    protected override object CreateBehavior()
    {
        return new UnityServiceBehavior();
    }
}&lt;/pre&gt;
&lt;p&gt;
Then, in our web.config, just register the extension, which in turn will configure
and return behavior.
&lt;/p&gt;
&lt;pre class="brush: xml;"&gt;&amp;lt;system.serviceModel&amp;gt;
  &amp;lt;behaviors&amp;gt;
    &amp;lt;serviceBehaviors&amp;gt;
      &amp;lt;behavior&amp;gt;
        &amp;lt;!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --&amp;gt;
        &amp;lt;serviceMetadata httpGetEnabled=&amp;quot;true&amp;quot;/&amp;gt;
        &amp;lt;!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information --&amp;gt;
        &amp;lt;serviceDebug includeExceptionDetailInFaults=&amp;quot;false&amp;quot;/&amp;gt;
        &amp;lt;unityExtension/&amp;gt;
      &amp;lt;/behavior&amp;gt;
    &amp;lt;/serviceBehaviors&amp;gt;
  &amp;lt;/behaviors&amp;gt;
  &amp;lt;extensions&amp;gt;
    &amp;lt;behaviorExtensions&amp;gt;
      &amp;lt;add name=&amp;quot;unityExtension&amp;quot; type=&amp;quot;UnityBehavior.UnityBehaviorElementExtension, UnityBehavior, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&amp;quot;/&amp;gt;
    &amp;lt;/behaviorExtensions&amp;gt;
  &amp;lt;/extensions&amp;gt;
  &amp;lt;serviceHostingEnvironment multipleSiteBindingsEnabled=&amp;quot;true&amp;quot; /&amp;gt;
&amp;lt;/system.serviceModel&amp;gt;&lt;/pre&gt;
&lt;p&gt;
In this case, the fact that the behavior element doesn’t include a name means the
set of behaviors it contains will be applied to any WCF service that is relying on
the default configuration (one of the coolest things in .NET 4!) which is how our
.xamlx file works in this example.
&lt;/p&gt;
&lt;p&gt;
Once all that’s done, from any activity in my .xamlx workflow I can access the IUnityContainer
interface as an extension.
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public sealed class CheckForUnity : CodeActivity
{
    // Define an activity input argument of type string
    public OutArgument&amp;lt;bool&amp;gt; HasUnity { get; set; }

    // If your activity returns a value, derive from CodeActivity&amp;lt;TResult&amp;gt;
    // and return the value from the Execute method.
    protected override void Execute(CodeActivityContext context)
    {
        IUnityContainer container = context.GetExtension&amp;lt;IUnityContainer&amp;gt;();

        context.SetValue&amp;lt;bool&amp;gt;(HasUnity, (container != null));
    }
}&lt;/pre&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,484a23ed-2508-4ba2-baa0-5a2efa13d325.aspx</comments>
      <category>.NET 4</category>
      <category>Unity</category>
      <category>WF</category>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=a8f3e360-995b-4a81-821e-3ebcf9f72272</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,a8f3e360-995b-4a81-821e-3ebcf9f72272.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,a8f3e360-995b-4a81-821e-3ebcf9f72272.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=a8f3e360-995b-4a81-821e-3ebcf9f72272</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Feedburner has apparently started decorating the URLs they embed to link back to my
full posts, which is causing my decrepit version of dasBlog to yak up 404’s. 
I’m working on it now, and apologize for the inconvenience.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Feedburner URL changes causing problems, working on it&amp;hellip;</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,a8f3e360-995b-4a81-821e-3ebcf9f72272.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/FeedburnerURLChangesCausingProblemsWorkingOnIthellip.aspx</link>
      <pubDate>Wed, 16 Dec 2009 17:51:04 GMT</pubDate>
      <description>&lt;p&gt;
Feedburner has apparently started decorating the URLs they embed to link back to my
full posts, which is causing my decrepit version of dasBlog to yak up 404’s.&amp;#160;
I’m working on it now, and apologize for the inconvenience.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,a8f3e360-995b-4a81-821e-3ebcf9f72272.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=2666beef-4547-4503-8801-e63729cab54b</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,2666beef-4547-4503-8801-e63729cab54b.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,2666beef-4547-4503-8801-e63729cab54b.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=2666beef-4547-4503-8801-e63729cab54b</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Just in case someone is googling (binging?) this later…
</p>
        <p>
If you are running Visual Studio 2010 (Beta 2) on Windows 7, and you want to create
a Windows Identity Foundation STS or relying party application, you need to run VS
as an administrator, or it won’t create the project correctly.  I suspect it’s
because it’s trying to install a cert, but there is some other stuff that fails too,
probably as a result.  Once I ran VS as an admin, it all works fine.  
</p>
        <p>
And, just for the record, WIF is awesome!  I’ve build an STS and relying app
by hand for WCF 3, and this is SOOOOO much easier.  Excellent work guys!
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>WIF + VS 2010 + Win 7</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,2666beef-4547-4503-8801-e63729cab54b.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/WIFVS2010Win7.aspx</link>
      <pubDate>Wed, 16 Dec 2009 00:16:05 GMT</pubDate>
      <description>&lt;p&gt;
Just in case someone is googling (binging?) this later…
&lt;/p&gt;
&lt;p&gt;
If you are running Visual Studio 2010 (Beta 2) on Windows 7, and you want to create
a Windows Identity Foundation STS or relying party application, you need to run VS
as an administrator, or it won’t create the project correctly.&amp;#160; I suspect it’s
because it’s trying to install a cert, but there is some other stuff that fails too,
probably as a result.&amp;#160; Once I ran VS as an admin, it all works fine.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
And, just for the record, WIF is awesome!&amp;#160; I’ve build an STS and relying app
by hand for WCF 3, and this is SOOOOO much easier.&amp;#160; Excellent work guys!
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,2666beef-4547-4503-8801-e63729cab54b.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=5881acf2-819f-48e0-8090-620af4852550</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,5881acf2-819f-48e0-8090-620af4852550.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,5881acf2-819f-48e0-8090-620af4852550.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=5881acf2-819f-48e0-8090-620af4852550</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I’m trying to get a handle on WF 4 (which is awesome, BTW) and currently working on
persistence.  We have a need to encrypt the workflow instance data, and it took
me quite some time to figure out how that might best be done.  The biggest drawback
to working with WF 4 right now is that the documentation is pretty lame.  There
are very few samples, and beta 2 hasn’t been around long enough to generate the “this
is how you solve that problem” blog posts we’ve all come to depend upon.  I looked
at PersistenceParticipant, but couldn’t see a good way to make that do what I wanted,
then a bunch more time trying to figure out what was going on in the SqlWorkflowInstanceStore,
etc.  
</p>
        <p>
I think I’ve got a workable solution, although I’ve yet to actually try it out. 
Turns out that the SqlWorkflowInstanceStore keeps all that good data in varbinary(MAX)
columns, and only messes with them via a set of stored procs that get created when
you create the instance store schema.  It should be an easy thing to modify said
stored procs to use native SQL 2005/2008 column level encryption, without having to
change the schema at all.  
</p>
        <p>
I’ll let you know if it works…
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Encrypting workflow instance data</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,5881acf2-819f-48e0-8090-620af4852550.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/EncryptingWorkflowInstanceData.aspx</link>
      <pubDate>Wed, 25 Nov 2009 21:30:39 GMT</pubDate>
      <description>&lt;p&gt;
I’m trying to get a handle on WF 4 (which is awesome, BTW) and currently working on
persistence.&amp;#160; We have a need to encrypt the workflow instance data, and it took
me quite some time to figure out how that might best be done.&amp;#160; The biggest drawback
to working with WF 4 right now is that the documentation is pretty lame.&amp;#160; There
are very few samples, and beta 2 hasn’t been around long enough to generate the “this
is how you solve that problem” blog posts we’ve all come to depend upon.&amp;#160; I looked
at PersistenceParticipant, but couldn’t see a good way to make that do what I wanted,
then a bunch more time trying to figure out what was going on in the SqlWorkflowInstanceStore,
etc.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
I think I’ve got a workable solution, although I’ve yet to actually try it out.&amp;#160;
Turns out that the SqlWorkflowInstanceStore keeps all that good data in varbinary(MAX)
columns, and only messes with them via a set of stored procs that get created when
you create the instance store schema.&amp;#160; It should be an easy thing to modify said
stored procs to use native SQL 2005/2008 column level encryption, without having to
change the schema at all.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
I’ll let you know if it works…
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,5881acf2-819f-48e0-8090-620af4852550.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=4a467c1a-e678-406f-836e-fc31283dc521</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,4a467c1a-e678-406f-836e-fc31283dc521.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,4a467c1a-e678-406f-836e-fc31283dc521.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=4a467c1a-e678-406f-836e-fc31283dc521</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This one stumped me for a bit today, so I wanted to get it out there for the search
engines to find... I created a new WCF Service Library project in VS 2010, taking
all the defaults and targeting .NET 4.0. I needed to add a [WebGet] attribute so that
I could make REST calls to the service. To do that, you need a reference to System.ServiceModel.Web.dll.
It didn't show up on the list of .NET references in the Add Reference... dialog. OK,
weird. So then I tracked down the file manually and added it. It got added to the
list of references, but showed up with the yellow-triangle "I don't know how
to find this reference" icon. Huh. 
</p>
        <p>
The problem turned out to be that for some reason, the project got created with a
target framework of .NET 4.0 Client Profile, which doesn't include that assembly.
Once I switched to the full .NET 4.0 target, it works just fine. The Client Profile
seems like a strange choice for a WCF Service Library.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Can't reference System.ServiceModel.Web from WCF Library project</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,4a467c1a-e678-406f-836e-fc31283dc521.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/CantReferenceSystemServiceModelWebFromWCFLibraryProject.aspx</link>
      <pubDate>Wed, 25 Nov 2009 21:23:57 GMT</pubDate>
      <description>&lt;p&gt;
This one stumped me for a bit today, so I wanted to get it out there for the search
engines to find... I created a new WCF Service Library project in VS 2010, taking
all the defaults and targeting .NET 4.0. I needed to add a [WebGet] attribute so that
I could make REST calls to the service. To do that, you need a reference to System.ServiceModel.Web.dll.
It didn't show up on the list of .NET references in the Add Reference... dialog. OK,
weird. So then I tracked down the file manually and added it. It got added to the
list of references, but showed up with the yellow-triangle &amp;quot;I don't know how
to find this reference&amp;quot; icon. Huh. 
&lt;/p&gt;
&lt;p&gt;
The problem turned out to be that for some reason, the project got created with a
target framework of .NET 4.0 Client Profile, which doesn't include that assembly.
Once I switched to the full .NET 4.0 target, it works just fine. The Client Profile
seems like a strange choice for a WCF Service Library.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,4a467c1a-e678-406f-836e-fc31283dc521.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=40ce04f0-9468-4ec8-b89d-652586aad76c</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,40ce04f0-9468-4ec8-b89d-652586aad76c.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,40ce04f0-9468-4ec8-b89d-652586aad76c.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=40ce04f0-9468-4ec8-b89d-652586aad76c</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
So I’m trying to figure out how to use WF 4 as a controller for a Prism app, and already
I’m running into some interesting behavior.  First off, in anything but a very
simple solution, custom activities don’t show up in the toolbox like they should. 
That’s not a huge deal, but annoying. 
</p>
        <p>
Of greater interest (concern?) is the fact that if I put my workflow XAML file in
the main WPF app solution, everything builds and runs just fine, except the workflow
does absolutely nothing.  It just finished successfully, having run none of it’s
activities.  If I take exactly the same XAML file and put it in another assembly,
then run it from the WPF app, it works just like it should.  I’m guessing this
is a byproduct of the new unified XAML engine, but I haven’t had time (or inclination
really) to delve.  Mostly it just means I have to have at least one superfluous
assembly, which for now isn’t too high a price to pay.  
</p>
        <p>
The day I installed beta 2, I managed to crash the workflow designer about 10 times,
but it seems to have settled down now.  Overall, I really appreciate the new
model for WF, which seems much more composable and easy to use.  
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>WPF/WF 4 challenge of the day</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,40ce04f0-9468-4ec8-b89d-652586aad76c.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/WPFWF4ChallengeOfTheDay.aspx</link>
      <pubDate>Mon, 09 Nov 2009 17:09:28 GMT</pubDate>
      <description>&lt;p&gt;
So I’m trying to figure out how to use WF 4 as a controller for a Prism app, and already
I’m running into some interesting behavior.&amp;#160; First off, in anything but a very
simple solution, custom activities don’t show up in the toolbox like they should.&amp;#160;
That’s not a huge deal, but annoying. 
&lt;/p&gt;
&lt;p&gt;
Of greater interest (concern?) is the fact that if I put my workflow XAML file in
the main WPF app solution, everything builds and runs just fine, except the workflow
does absolutely nothing.&amp;#160; It just finished successfully, having run none of it’s
activities.&amp;#160; If I take exactly the same XAML file and put it in another assembly,
then run it from the WPF app, it works just like it should.&amp;#160; I’m guessing this
is a byproduct of the new unified XAML engine, but I haven’t had time (or inclination
really) to delve.&amp;#160; Mostly it just means I have to have at least one superfluous
assembly, which for now isn’t too high a price to pay.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
The day I installed beta 2, I managed to crash the workflow designer about 10 times,
but it seems to have settled down now.&amp;#160; Overall, I really appreciate the new
model for WF, which seems much more composable and easy to use.&amp;#160; 
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,40ce04f0-9468-4ec8-b89d-652586aad76c.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=6a5d42ea-032c-42d9-9e24-461245469fd1</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,6a5d42ea-032c-42d9-9e24-461245469fd1.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,6a5d42ea-032c-42d9-9e24-461245469fd1.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=6a5d42ea-032c-42d9-9e24-461245469fd1</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I realize this is a bit late, but as of just about 4 weeks ago I’m now the Architect
at <a href="http://www.eidpassport.com">Eid Passport</a>.  I’m really looking
forward to building some cool stuff, with a team that’s had quite a bit of experience
in this space.  
</p>
        <p>
In short, Eid Passport makes perimeter security systems for secure facilities, and
manages access to those facilities by vendors.  For example, say you are the
Coke delivery guy at a military base.  It’s a hassle to get through the gate
every time you deliver, since they have to make sure it’s OK for you to be on the
base.  Now the Coke guy has the option of going to our kiosk at the base and
signing up for an access card that will allow him to spend much less time getting
in and out.  We do some background checks, employment verification (does he still
really work for Coke, etc.) and then issue a credential that he can use to get through
the gate.  Now Coke delivery guy can make <em>N</em> more deliveries in a day
because he’s not spending time at the gate.  This is a new domain for me, so
there’s a lot to learn, but it’s pretty exciting stuff.  All the way from a handheld
scanner that reads all kinds of cards to back end access control and data processing
servers.  
</p>
        <p>
If any of that sounds interesting to you, we’re looking for some additional developers. 
There are instructions on the website (see above) for how to submit your resume if
you are interested.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>The new gig</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,6a5d42ea-032c-42d9-9e24-461245469fd1.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/TheNewGig.aspx</link>
      <pubDate>Fri, 06 Nov 2009 17:32:28 GMT</pubDate>
      <description>&lt;p&gt;
I realize this is a bit late, but as of just about 4 weeks ago I’m now the Architect
at &lt;a href="http://www.eidpassport.com"&gt;Eid Passport&lt;/a&gt;.&amp;#160; I’m really looking
forward to building some cool stuff, with a team that’s had quite a bit of experience
in this space.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
In short, Eid Passport makes perimeter security systems for secure facilities, and
manages access to those facilities by vendors.&amp;#160; For example, say you are the
Coke delivery guy at a military base.&amp;#160; It’s a hassle to get through the gate
every time you deliver, since they have to make sure it’s OK for you to be on the
base.&amp;#160; Now the Coke guy has the option of going to our kiosk at the base and
signing up for an access card that will allow him to spend much less time getting
in and out.&amp;#160; We do some background checks, employment verification (does he still
really work for Coke, etc.) and then issue a credential that he can use to get through
the gate.&amp;#160; Now Coke delivery guy can make &lt;em&gt;N&lt;/em&gt; more deliveries in a day
because he’s not spending time at the gate.&amp;#160; This is a new domain for me, so
there’s a lot to learn, but it’s pretty exciting stuff.&amp;#160; All the way from a handheld
scanner that reads all kinds of cards to back end access control and data processing
servers.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
If any of that sounds interesting to you, we’re looking for some additional developers.&amp;#160;
There are instructions on the website (see above) for how to submit your resume if
you are interested.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,6a5d42ea-032c-42d9-9e24-461245469fd1.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=0aa76e13-9130-4044-b16c-ecf2fc46e58f</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,0aa76e13-9130-4044-b16c-ecf2fc46e58f.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,0aa76e13-9130-4044-b16c-ecf2fc46e58f.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=0aa76e13-9130-4044-b16c-ecf2fc46e58f</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
We’ve added some new classes to the <a href="http://www.sftsrc.com">SoftSource</a> training <a href="http://events.sftsrc.com">calendar</a>,
including a one-day <a href="http://events.sftsrc.com/EventDescription.aspx?EventId=1076&amp;AbstractId=687">Blend
2</a> class, and <a href="http://events.sftsrc.com/EventDescription.aspx?EventId=1061&amp;AbstractId=682">SQL
2008 for Developers</a>.  Other offerings coming up are “Agile in a Day”, WPF,
WCF, ASP.NET 3.5, LINQ, Silverlight, and of course, C#.  Discounts available
for multiple students from the same organization, and custom on-site training also.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>New classes in the lineup</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,0aa76e13-9130-4044-b16c-ecf2fc46e58f.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/NewClassesInTheLineup.aspx</link>
      <pubDate>Wed, 17 Jun 2009 17:19:27 GMT</pubDate>
      <description>&lt;p&gt;
We’ve added some new classes to the &lt;a href="http://www.sftsrc.com"&gt;SoftSource&lt;/a&gt; training &lt;a href="http://events.sftsrc.com"&gt;calendar&lt;/a&gt;,
including a one-day &lt;a href="http://events.sftsrc.com/EventDescription.aspx?EventId=1076&amp;amp;AbstractId=687"&gt;Blend
2&lt;/a&gt; class, and &lt;a href="http://events.sftsrc.com/EventDescription.aspx?EventId=1061&amp;amp;AbstractId=682"&gt;SQL
2008 for Developers&lt;/a&gt;.&amp;#160; Other offerings coming up are “Agile in a Day”, WPF,
WCF, ASP.NET 3.5, LINQ, Silverlight, and of course, C#.&amp;#160; Discounts available
for multiple students from the same organization, and custom on-site training also.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,0aa76e13-9130-4044-b16c-ecf2fc46e58f.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=49140780-5f83-46da-8079-e6389a39a490</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,49140780-5f83-46da-8079-e6389a39a490.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,49140780-5f83-46da-8079-e6389a39a490.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=49140780-5f83-46da-8079-e6389a39a490</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
A month or so ago I posted on a <a href="http://www.cauldwell.net/patrick/blog/ALdquodefaultButtonrdquoInSilverlight.aspx">solution</a> for
simulating “default button” semantics in a Silverlight app, meaning that if you are
entering text in a text box and you hit the enter key, the “default button” for the
“page” should be pressed.  Very natural for form entry, etc.  
</p>
        <p>
An issue came up (discovered by <a href="http://johnpapa.net/">John Papa</a>) with
the solution in a Prism app, because my solution depends on being able to find the
“default” button in the visual tree using the FindName method.  That means that
you have to be high enough up the visual tree to find the button, since it only works
“down” the tree.  In a Prism app, it’s not necessarily clear where “high enough”
might be.  Plus, because the solution requires unique names, and Prism modules
may have nothing to do with one another, they may have duplicate names, etc.
</p>
        <p>
Here’s a revision to the solution that doesn’t require unique names, and doesn’t require
any static references that might interfere with proper garbage collection… 
</p>
        <p>
First, a new object called DefaultButtonHub that keeps track of the relationship between
text boxes and buttons.  It also exposes an Attached Property that takes a DefaultButtonHub
reference so we can hook up text boxes and buttons to the “hub” in XAML.
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:4c5596a4-5334-43ea-a5fc-014754ff037a" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">public class DefaultButtonHub
{
   ButtonAutomationPeer peer = null;

   private void Attach(DependencyObject source)
   {
       if (source is Button)
       {
           peer = new ButtonAutomationPeer(source as Button);
       }
       else if (source is TextBox)
       {
           TextBox tb = source as TextBox;
           tb.KeyUp += OnKeyUp;
       }
       else if (source is PasswordBox)
       {
           PasswordBox pb = source as PasswordBox;
           pb.KeyUp += OnKeyUp;
       }
   }

   private void OnKeyUp(object sender, KeyEventArgs arg)
   {
       if(arg.Key == Key.Enter)
           if (peer != null)
               ((IInvokeProvider)peer).Invoke();
   }

   public static DefaultButtonHub GetDefaultHub(DependencyObject obj)
   {
       return (DefaultButtonHub)obj.GetValue(DefaultHubProperty);
   }

   public static void SetDefaultHub(DependencyObject obj, DefaultButtonHub value)
   {
       obj.SetValue(DefaultHubProperty, value);
   }

   // Using a DependencyProperty as the backing store for DefaultHub.  This enables animation, styling, binding, etc...
   public static readonly DependencyProperty DefaultHubProperty =
       DependencyProperty.RegisterAttached("DefaultHub", typeof(DefaultButtonHub), typeof(DefaultButtonHub), new PropertyMetadata(OnHubAttach));

   private static void OnHubAttach(DependencyObject source, DependencyPropertyChangedEventArgs prop)
   {
       DefaultButtonHub hub = prop.NewValue as DefaultButtonHub;
       hub.Attach(source);
   }

}</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
Basically we’re expecting that both the text boxes and the button will register themselves
with the “hub”.  If it’s a button that’s being registered, we wrap it in a ButtonAutomationPeer
so we can “press” it later.  If it’s a text box, we hook up a KeyUp handler that
will “press” the button if it’s there.  The requirement in the XAML is only marginally
heavier than in my previous solution…we have to add a resource of type DefaultButtonHub,
and point the button and text boxes at it using the {StaticResource} markup extension.
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:28f99d3a-6b2a-4ff1-8c7c-a058329caeb0" class="wlWriterEditableSmartContent">
          <pre class="brush: xml; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">&lt;UserControl x:Class="DefaultButton.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:my="clr-namespace:DefaultButton"
    Width="400" Height="300"&gt;
    &lt;UserControl.Resources&gt;
        &lt;my:DefaultButtonHub x:Key="defaultHub"/&gt;
    &lt;/UserControl.Resources&gt;
    &lt;Grid x:Name="LayoutRoot" Background="White"&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition/&gt;
            &lt;RowDefinition/&gt;
        &lt;/Grid.RowDefinitions&gt;
        &lt;TextBox x:Name="theText" Grid.Row="0"
                 my:DefaultButtonHub.DefaultHub="{StaticResource defaultHub}"/&gt;
        &lt;Button x:Name="theButton" Grid.Row="1" Content="Default"
                Click="theButton_Click" my:DefaultButtonHub.DefaultHub="{StaticResource defaultHub}"/&gt;
    &lt;/Grid&gt;
&lt;/UserControl&gt;</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
Note that the new DefaultHub attached property is applied to both the text box and
the button, each pointing the the single resource.  This way everything gets
wired up property, there isn’t any problem with name resolution (aside from the usual
resource name scoping) and everything will get cleaned up if the form needs to be
GC’d.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Default button semantics in Silverlight revisited</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,49140780-5f83-46da-8079-e6389a39a490.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/DefaultButtonSemanticsInSilverlightRevisited.aspx</link>
      <pubDate>Thu, 11 Jun 2009 19:03:22 GMT</pubDate>
      <description>&lt;p&gt;
A month or so ago I posted on a &lt;a href="http://www.cauldwell.net/patrick/blog/ALdquodefaultButtonrdquoInSilverlight.aspx"&gt;solution&lt;/a&gt; for
simulating “default button” semantics in a Silverlight app, meaning that if you are
entering text in a text box and you hit the enter key, the “default button” for the
“page” should be pressed.&amp;nbsp; Very natural for form entry, etc.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
An issue came up (discovered by &lt;a href="http://johnpapa.net/"&gt;John Papa&lt;/a&gt;) with
the solution in a Prism app, because my solution depends on being able to find the
“default” button in the visual tree using the FindName method.&amp;nbsp; That means that
you have to be high enough up the visual tree to find the button, since it only works
“down” the tree.&amp;nbsp; In a Prism app, it’s not necessarily clear where “high enough”
might be.&amp;nbsp; Plus, because the solution requires unique names, and Prism modules
may have nothing to do with one another, they may have duplicate names, etc.
&lt;/p&gt;
&lt;p&gt;
Here’s a revision to the solution that doesn’t require unique names, and doesn’t require
any static references that might interfere with proper garbage collection… 
&lt;/p&gt;
&lt;p&gt;
First, a new object called DefaultButtonHub that keeps track of the relationship between
text boxes and buttons.&amp;nbsp; It also exposes an Attached Property that takes a DefaultButtonHub
reference so we can hook up text boxes and buttons to the “hub” in XAML.
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:4c5596a4-5334-43ea-a5fc-014754ff037a" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;public class DefaultButtonHub
{
   ButtonAutomationPeer peer = null;

   private void Attach(DependencyObject source)
   {
       if (source is Button)
       {
           peer = new ButtonAutomationPeer(source as Button);
       }
       else if (source is TextBox)
       {
           TextBox tb = source as TextBox;
           tb.KeyUp += OnKeyUp;
       }
       else if (source is PasswordBox)
       {
           PasswordBox pb = source as PasswordBox;
           pb.KeyUp += OnKeyUp;
       }
   }

   private void OnKeyUp(object sender, KeyEventArgs arg)
   {
       if(arg.Key == Key.Enter)
           if (peer != null)
               ((IInvokeProvider)peer).Invoke();
   }

   public static DefaultButtonHub GetDefaultHub(DependencyObject obj)
   {
       return (DefaultButtonHub)obj.GetValue(DefaultHubProperty);
   }

   public static void SetDefaultHub(DependencyObject obj, DefaultButtonHub value)
   {
       obj.SetValue(DefaultHubProperty, value);
   }

   // Using a DependencyProperty as the backing store for DefaultHub.  This enables animation, styling, binding, etc...
   public static readonly DependencyProperty DefaultHubProperty =
       DependencyProperty.RegisterAttached("DefaultHub", typeof(DefaultButtonHub), typeof(DefaultButtonHub), new PropertyMetadata(OnHubAttach));

   private static void OnHubAttach(DependencyObject source, DependencyPropertyChangedEventArgs prop)
   {
       DefaultButtonHub hub = prop.NewValue as DefaultButtonHub;
       hub.Attach(source);
   }

}&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
Basically we’re expecting that both the text boxes and the button will register themselves
with the “hub”.&amp;nbsp; If it’s a button that’s being registered, we wrap it in a ButtonAutomationPeer
so we can “press” it later.&amp;nbsp; If it’s a text box, we hook up a KeyUp handler that
will “press” the button if it’s there.&amp;nbsp; The requirement in the XAML is only marginally
heavier than in my previous solution…we have to add a resource of type DefaultButtonHub,
and point the button and text boxes at it using the {StaticResource} markup extension.
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:28f99d3a-6b2a-4ff1-8c7c-a058329caeb0" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: xml; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;&amp;lt;UserControl x:Class="DefaultButton.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:my="clr-namespace:DefaultButton"
    Width="400" Height="300"&amp;gt;
    &amp;lt;UserControl.Resources&amp;gt;
        &amp;lt;my:DefaultButtonHub x:Key="defaultHub"/&amp;gt;
    &amp;lt;/UserControl.Resources&amp;gt;
    &amp;lt;Grid x:Name="LayoutRoot" Background="White"&amp;gt;
        &amp;lt;Grid.RowDefinitions&amp;gt;
            &amp;lt;RowDefinition/&amp;gt;
            &amp;lt;RowDefinition/&amp;gt;
        &amp;lt;/Grid.RowDefinitions&amp;gt;
        &amp;lt;TextBox x:Name="theText" Grid.Row="0"
                 my:DefaultButtonHub.DefaultHub="{StaticResource defaultHub}"/&amp;gt;
        &amp;lt;Button x:Name="theButton" Grid.Row="1" Content="Default"
                Click="theButton_Click" my:DefaultButtonHub.DefaultHub="{StaticResource defaultHub}"/&amp;gt;
    &amp;lt;/Grid&amp;gt;
&amp;lt;/UserControl&amp;gt;&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
Note that the new DefaultHub attached property is applied to both the text box and
the button, each pointing the the single resource.&amp;nbsp; This way everything gets
wired up property, there isn’t any problem with name resolution (aside from the usual
resource name scoping) and everything will get cleaned up if the form needs to be
GC’d.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,49140780-5f83-46da-8079-e6389a39a490.aspx</comments>
      <category>Silverlight</category>
      <category>Work</category>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=c1dec284-c7c5-4742-b96e-22dcd1975d74</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,c1dec284-c7c5-4742-b96e-22dcd1975d74.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,c1dec284-c7c5-4742-b96e-22dcd1975d74.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=c1dec284-c7c5-4742-b96e-22dcd1975d74</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Last <a href="http://www.cauldwell.net/patrick/blog/NETRIAServicesFromScratch.aspx">time</a>,
I talked about how to build a Domain Service from scratch using whatever POCO you
have lying around.  Now it’s time to talk about how that works on the client
side…
</p>
        <p>
One of the coolest things about RIA Services is that you don’t even have to “Add Service
Reference…” to get a reference to the Domain Service.  If your Silverlight project
is linked to the ASP.NET project correctly (see the RIA Services doc for how this
works) the build steps will take care of generating the right code in your Silverlight
project, and away you go.  There are several ways of accessing the service client-side,
from dead-easy to a bit more involved.  We’ll start with dead easy.  
</p>
        <p>
The very easiest way to get things hooked up is to use the DomainDataSource control. 
It wraps your DomainDataContext (the client-side generated bit) with a data source
you can bind directly against in XAML.
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:279e77b7-a94f-4eb3-b698-6c72bbf848a3" class="wlWriterEditableSmartContent">
          <pre class="brush: xml; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">&lt;ria:DomainDataSource x:Name="PeopleDataSource" LoadMethodName="LoadPersons" AutoLoad="True"&gt;
  &lt;ria:DomainDataSource.DomainContext&gt;
      &lt;services:PeopleDomainContext/&gt;
  &lt;/ria:DomainDataSource.DomainContext&gt;
&lt;/ria:DomainDataSource&gt;
&lt;dataControls:DataForm x:Name="dfPeople" CanUserAddItems="True" CanUserDeleteItems="true"
                     ItemsSource="{Binding ElementName=PeopleDataSource, Path=Data}" 
                     ItemEditEnded="dfPeople_ItemEditEnded"&gt;
&lt;/dataControls:DataForm&gt;</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
The LoadMethodName attribute on the DomainDataSource tells it what method on the DomainContext
to call in order to correctly populate the data context.  You can also pass parameters
defined in XAML to the Load method if you only need to load a subset.  The DataForm
control is bound to the Data property of the DomainDataSource, and away you go. 
You get this
</p>
        <p>
          <a href="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image.png">
            <img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_thumb.png" width="438" height="281" />
          </a>
        </p>
        <p>
Because the Insert/Update/Delete methods are implemented on the server-side DomainService,
the DataForm automagically enables the edit, add and delete buttons at the top. 
If I edit or add a record, the save button shows up…
</p>
        <p>
          <a href="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_3.png">
            <img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_thumb_3.png" width="448" height="287" />
          </a>
        </p>
        <p>
Pressing either the Save or Cancel button fires the ItemEditEnded event, which we
can grab to submit the changes back to the server
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:61ef5152-d951-4742-8042-f2981031a464" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">private void dfPeople_ItemEditEnded(object sender, DataFormItemEditEndedEventArgs e)
{
  if (e.EditAction == DataFormEditAction.Commit)
      PeopleDataSource.SubmitChanges();
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
this is the very simplest case.  Calling SubmitChanges() here will send the edits/inserts
up to the server right away.  For the sake of bandwidth, etc. I might want to
implement my own “Save” button that batches up a whole set of change to the server
rather than committing each edit individually.  You would still call PeopleDataSource.SubmitChanges,
but not in response to the DataForm’s events.  
</p>
        <p>
One of the great things about the way this works on the client side is that way the
data validation attributes we set on the server-side POCO objects get propagated to
the client.  For example, the server side LastName property looks like this (at
least in the metadata class…)
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:a24de189-0bf0-4d3a-b486-9105fc6ade9e" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">[Required]
[RegularExpression("[a-zA-z]*")]
public string LastName;
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
The property that gets generated on the client side is
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:e47b1c66-9465-4a43-b623-55c64a8249ee" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">[DataMember()]
[RegularExpression("[a-zA-z]*")]
[Required()]
public string LastName
{
  get
  {
      return this._lastName;
  }
  set
  {
      if ((this._lastName != value))
      {
          this.ValidateProperty("LastName", value);
          this.RaiseDataMemberChanging("LastName");
          this._lastName = value;
          this.RaiseDataMemberChanged("LastName");
      }
  }
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
It maintains the [Required] and [RegularExpression] attributes.  Plus, in the
property setter, it calls ValidateProperty, which uses reflection to examine those
attributes and throw validation exceptions if necessary.  By default, then, I
get UI on the Silverlight client for validation.
</p>
        <p>
          <a href="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_4.png">
            <img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_thumb_4.png" width="449" height="288" />
          </a>
        </p>
        <p>
The DataForm provides the UI around both the field in question and the summary at
the bottom.  In this case, I probably don’t want to tell the user what RegEx
I’m validating against, so I need to add the ErrorMessage property to the validation
attribute
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:16a66730-1d71-416f-9f72-c73fc9f617aa" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">[Required]
[RegularExpression("[a-zA-z]*", ErrorMessage="Alpha characters only please!")]
public string LastName;
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
          <a href="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_5.png">
            <img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_thumb_5.png" width="455" height="292" />
          </a>
        </p>
        <p>
When that error is corrected and I press the Save button, the Custom Validation routine
is applied (see <a href="http://www.cauldwell.net/patrick/blog/NETRIAServicesFromScratch.aspx">last
post</a> for details)
</p>
        <p>
          <a href="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_6.png">
            <img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_thumb_6.png" width="463" height="297" />
          </a> 
</p>
        <p>
When all the errors are corrected, and the save happens (and gets committed back to
the server) the DataForm is updated to show the correct ID value (from the server)
as well as the calculated Age property.
</p>
        <p>
          <a href="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_7.png">
            <img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_thumb_7.png" width="466" height="299" />
          </a>
        </p>
        <p>
For next to no work, I get a pretty good user experience for browsing, editing, inserting
and deleting records.  If I wanted a bit more control, I could load the data
into the DataContext myself, and then setup the databinding, rather than using the
DomainDataSource in XAML
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:b239a716-d51d-4f0d-ab90-f9a97d4f0540" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">private PeopleDomainContext _context = new PeopleDomainContext();

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
  if (_context.Persons.Count == 0)
  {
      _context.Loaded += (s, arg) =&gt; loadPeople();
      _context.LoadPersons();
  }
  else
      loadPeople();
}

private void loadPeople()
{
  dfPeople.ItemsSource = _context.Persons;
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
This would give me an opportunity to only load some people based on parameters, or
whatever else I wanted to do to affect the loading of data before the data binding
happens.  
</p>
        <p>
        </p>
        <p>
Next time… more cool things you can do with the DomainDataContext
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>RIA Services: the client side</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,c1dec284-c7c5-4742-b96e-22dcd1975d74.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/RIAServicesTheClientSide.aspx</link>
      <pubDate>Fri, 05 Jun 2009 21:47:59 GMT</pubDate>
      <description>&lt;p&gt;
Last &lt;a href="http://www.cauldwell.net/patrick/blog/NETRIAServicesFromScratch.aspx"&gt;time&lt;/a&gt;,
I talked about how to build a Domain Service from scratch using whatever POCO you
have lying around.&amp;#160; Now it’s time to talk about how that works on the client
side…
&lt;/p&gt;
&lt;p&gt;
One of the coolest things about RIA Services is that you don’t even have to “Add Service
Reference…” to get a reference to the Domain Service.&amp;#160; If your Silverlight project
is linked to the ASP.NET project correctly (see the RIA Services doc for how this
works) the build steps will take care of generating the right code in your Silverlight
project, and away you go.&amp;#160; There are several ways of accessing the service client-side,
from dead-easy to a bit more involved.&amp;#160; We’ll start with dead easy.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
The very easiest way to get things hooked up is to use the DomainDataSource control.&amp;#160;
It wraps your DomainDataContext (the client-side generated bit) with a data source
you can bind directly against in XAML.
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:279e77b7-a94f-4eb3-b698-6c72bbf848a3" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: xml; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;&amp;lt;ria:DomainDataSource x:Name=&amp;quot;PeopleDataSource&amp;quot; LoadMethodName=&amp;quot;LoadPersons&amp;quot; AutoLoad=&amp;quot;True&amp;quot;&amp;gt;
  &amp;lt;ria:DomainDataSource.DomainContext&amp;gt;
      &amp;lt;services:PeopleDomainContext/&amp;gt;
  &amp;lt;/ria:DomainDataSource.DomainContext&amp;gt;
&amp;lt;/ria:DomainDataSource&amp;gt;
&amp;lt;dataControls:DataForm x:Name=&amp;quot;dfPeople&amp;quot; CanUserAddItems=&amp;quot;True&amp;quot; CanUserDeleteItems=&amp;quot;true&amp;quot;
                     ItemsSource=&amp;quot;{Binding ElementName=PeopleDataSource, Path=Data}&amp;quot; 
                     ItemEditEnded=&amp;quot;dfPeople_ItemEditEnded&amp;quot;&amp;gt;
&amp;lt;/dataControls:DataForm&amp;gt;&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
The LoadMethodName attribute on the DomainDataSource tells it what method on the DomainContext
to call in order to correctly populate the data context.&amp;#160; You can also pass parameters
defined in XAML to the Load method if you only need to load a subset.&amp;#160; The DataForm
control is bound to the Data property of the DomainDataSource, and away you go.&amp;#160;
You get this
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_thumb.png" width="438" height="281" /&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Because the Insert/Update/Delete methods are implemented on the server-side DomainService,
the DataForm automagically enables the edit, add and delete buttons at the top.&amp;#160;
If I edit or add a record, the save button shows up…
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_3.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_thumb_3.png" width="448" height="287" /&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Pressing either the Save or Cancel button fires the ItemEditEnded event, which we
can grab to submit the changes back to the server
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:61ef5152-d951-4742-8042-f2981031a464" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;private void dfPeople_ItemEditEnded(object sender, DataFormItemEditEndedEventArgs e)
{
  if (e.EditAction == DataFormEditAction.Commit)
      PeopleDataSource.SubmitChanges();
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
this is the very simplest case.&amp;#160; Calling SubmitChanges() here will send the edits/inserts
up to the server right away.&amp;#160; For the sake of bandwidth, etc. I might want to
implement my own “Save” button that batches up a whole set of change to the server
rather than committing each edit individually.&amp;#160; You would still call PeopleDataSource.SubmitChanges,
but not in response to the DataForm’s events.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
One of the great things about the way this works on the client side is that way the
data validation attributes we set on the server-side POCO objects get propagated to
the client.&amp;#160; For example, the server side LastName property looks like this (at
least in the metadata class…)
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:a24de189-0bf0-4d3a-b486-9105fc6ade9e" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;[Required]
[RegularExpression(&amp;quot;[a-zA-z]*&amp;quot;)]
public string LastName;
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
The property that gets generated on the client side is
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:e47b1c66-9465-4a43-b623-55c64a8249ee" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;[DataMember()]
[RegularExpression(&amp;quot;[a-zA-z]*&amp;quot;)]
[Required()]
public string LastName
{
  get
  {
      return this._lastName;
  }
  set
  {
      if ((this._lastName != value))
      {
          this.ValidateProperty(&amp;quot;LastName&amp;quot;, value);
          this.RaiseDataMemberChanging(&amp;quot;LastName&amp;quot;);
          this._lastName = value;
          this.RaiseDataMemberChanged(&amp;quot;LastName&amp;quot;);
      }
  }
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
It maintains the [Required] and [RegularExpression] attributes.&amp;#160; Plus, in the
property setter, it calls ValidateProperty, which uses reflection to examine those
attributes and throw validation exceptions if necessary.&amp;#160; By default, then, I
get UI on the Silverlight client for validation.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_4.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_thumb_4.png" width="449" height="288" /&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
The DataForm provides the UI around both the field in question and the summary at
the bottom.&amp;#160; In this case, I probably don’t want to tell the user what RegEx
I’m validating against, so I need to add the ErrorMessage property to the validation
attribute
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:16a66730-1d71-416f-9f72-c73fc9f617aa" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;[Required]
[RegularExpression(&amp;quot;[a-zA-z]*&amp;quot;, ErrorMessage=&amp;quot;Alpha characters only please!&amp;quot;)]
public string LastName;
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
&lt;a href="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_5.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_thumb_5.png" width="455" height="292" /&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
When that error is corrected and I press the Save button, the Custom Validation routine
is applied (see &lt;a href="http://www.cauldwell.net/patrick/blog/NETRIAServicesFromScratch.aspx"&gt;last
post&lt;/a&gt; for details)
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_6.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_thumb_6.png" width="463" height="297" /&gt;&lt;/a&gt;&amp;#160;
&lt;/p&gt;
&lt;p&gt;
When all the errors are corrected, and the save happens (and gets committed back to
the server) the DataForm is updated to show the correct ID value (from the server)
as well as the calculated Age property.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_7.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.cauldwell.net/patrick/blog/images/RIAServicestheclientside_CFB3/image_thumb_7.png" width="466" height="299" /&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
For next to no work, I get a pretty good user experience for browsing, editing, inserting
and deleting records.&amp;#160; If I wanted a bit more control, I could load the data
into the DataContext myself, and then setup the databinding, rather than using the
DomainDataSource in XAML
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:b239a716-d51d-4f0d-ab90-f9a97d4f0540" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;private PeopleDomainContext _context = new PeopleDomainContext();

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
  if (_context.Persons.Count == 0)
  {
      _context.Loaded += (s, arg) =&amp;gt; loadPeople();
      _context.LoadPersons();
  }
  else
      loadPeople();
}

private void loadPeople()
{
  dfPeople.ItemsSource = _context.Persons;
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
This would give me an opportunity to only load some people based on parameters, or
whatever else I wanted to do to affect the loading of data before the data binding
happens.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
Next time… more cool things you can do with the DomainDataContext
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,c1dec284-c7c5-4742-b96e-22dcd1975d74.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=7ac6946a-d494-433d-a0c2-5737ae2e9ee8</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,7ac6946a-d494-433d-a0c2-5737ae2e9ee8.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,7ac6946a-d494-433d-a0c2-5737ae2e9ee8.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=7ac6946a-d494-433d-a0c2-5737ae2e9ee8</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Most of the demos/samples I’ve looked at so far for <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=76bb3a07-3846-4564-b0c3-27972bcaabce&amp;displaylang=en">RIA
Services</a> have started with a LINQ to SQL or ADO.NET Entity model and generated
Domain Service classes from those.  I decided to start from something super simple
(a POCO, if you will) and work up from there.  I started with a canonical 
“Person” class
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:c0d7eccf-2fd5-43f8-8f63-1952d006701e" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">public partial class Person : INotifyPropertyChanged
{
   #region INotifyPropertyChanged Members

   public event PropertyChangedEventHandler PropertyChanged;

   #endregion

   protected virtual void Changed(string propertyName)
   {
       PropertyChangedEventHandler handler = PropertyChanged;
       if (handler != null)
       {
           handler(this, new PropertyChangedEventArgs(propertyName));
       }
   }

   private int _personId;
   public int PersonId
   {
       get
       {
           return _personId;
       }
       set
       {
           if (_personId != value)
           {
               _personId = value;
               Changed("PersonId");
           }
       }
   }

   private string _firstName;
   public string FirstName
   {
...
   }
   private string _lastName;
   public string LastName
   {
...
   }
   private System.DateTime _birthDate;
   public System.DateTime BirthDate
   {
...
   }
}</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
Nothing to see here.  It’s just a simple POCO that supports INotifyPropertyChanged
for databinding.  Note that it’s a partial class…  The simplest path would
be to add RIA Services attributes directly to these properties for things like data
validation, but I wanted to try out all the features, so I split out the metadata
into another file
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:70bb36b8-81ba-48fc-8512-e36482d4ed2e" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">[MetadataTypeAttribute(typeof(RiaServices.Web.Person.PersonMetadata))]
public partial class Person
{

   internal sealed class PersonMetadata
   {
       [Key]
       [Required]
       public int PersonId;

       [Required]
       [RegularExpression("[a-zA-z]*")]
       public string FirstName;

       [Required]
       [RegularExpression("[a-zA-z]*")]
       public string LastName;

       [Required]
       public DateTime BirthDate;
   }
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
This is kind of an interesting trick, and allows me to separate out all the RIA specific
metadata from the original class definition.  This makes total sense when you
look at the way they handle LINQ to SQL, for example.  In that case you already
have Entity classes defined by the LINQ to SQL wizard, so this extra metadata class
allows you to associate the right attributes without touching the (generated) LINQ
to SQL classes.  Clever.  Notice that the metadata class uses fields, not
properties, and just matches the names for the sake of simplicity.
</p>
        <p>
In this case, the additional metadata defines data validation rules that get enforced
both server and client side.  There are other attributes to enforcing string
length and ranges.  
</p>
        <p>
This all works because RIA Services generates “proxy” entity classes on the client
side that are Silverlight compilable and also DataContracts (for serializing, which
is cool…).  However, what happens if I have a calculated property that’s not
just storage?  There’s a solution for that too, and it involves another piece
of the partial class
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:09baa7be-63e0-47af-9d21-d18ecf0d1fcb" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">public partial class Person
{
   [Shared]
   public int Age
   {
       get
       {
           this.Changed("Age");
           return Convert.ToInt32(Math.Floor((DateTime.Now - _birthDate).Days / 365.25));
       }
   }

}</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
This bit goes in a file called Person.shared.cs, and it will be copied to the client
project and compiled there as well as on the server.  The [Shared] attribute
marks the bits that need to be thus propagated.  Again, clever.  Of course,
any such shared code has to compile in Silverlight.
</p>
        <p>
The other piece of code I want to share (using the same method) is a custom validator. 
In addition to the [Required] or [RegularExpression] attributes used above, you can
register a custom validation routine that can examine the state of the entity as a
whole.  The validation routine looks like this
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:1eef0b66-a7ec-418b-b4d3-9bb6ac09199d" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">[Shared]
public class PersonValidator
{
   public static bool IsPersonValid(Person p, ValidationContext context, out ValidationResult result)
   {
       bool valid = true;

       result = null;

       if (p.Age &gt; 130)
           valid = false;

       if (!valid)
       {
           result = new ValidationResult("Birthdate is invalid, people can't be that old", new []{"BirthDate"});
       }

       return valid;

   }
}</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
That’s in a file called PersonValidator.shared.cs, so that it will be available client
and server-side.  It’s associated with the Person entity with an additional attribute
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:d75e9da4-a94d-4440-b0ac-e9beb3db8ed7" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; highlight: 1 ;">[CustomValidation(typeof(PersonValidator), "IsPersonValid")]
[MetadataTypeAttribute(typeof(RiaServices.Web.Person.PersonMetadata))]
public partial class Person
...</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
With the Person entity all ready, I can expose it to the client by creating a new
DomainService class with methods for Get, Insert, Update, Delete, etc.
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:9a554f7f-e2a6-4f0e-b838-7c7ee3bd3b71" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">[EnableClientAccess()]
public class PeopleDomainService : DomainService
{
   public IQueryable&lt;Person&gt; GetPersons()
   {

       return PeopleData.Persons.AsQueryable&lt;Person&gt;();
   }

   public IQueryable&lt;Person&gt; GetPerson(int personId)
   {
       return (from p in PeopleData.Persons
               where p.PersonId == personId
               select p).AsQueryable&lt;Person&gt;();
   }

   public void UpdatePerson(Person person)
   {
       Person oldP = (from p in PeopleData.Persons
                      where p.PersonId == person.PersonId
                      select p).FirstOrDefault();

       if (oldP != null)
       {
           PeopleData.Persons.Remove(oldP);
           PeopleData.Persons.Add(person);
       }
   }

   public void InsertPerson(Person person)
   {
       if (person.PersonId == 0)
       {
           int max = PeopleData.Persons.Max(p =&gt; p.PersonId);
           person.PersonId = max + 1;
       }

       PeopleData.Persons.Add(person);
   }

   public void DeletePerson(Person person)
   {
       Person oldP = (from p in PeopleData.Persons
                      where p.PersonId == person.PersonId
                      select p).FirstOrDefault();

       if (oldP != null)
       {
           PeopleData.Persons.Remove(oldP);
       }
   }
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
PeopleData.Persons in this case is a List&lt;Person&gt; that’s populated with some
sample data.  The [EnableClientAccess] attribute causes the build-time bits to
generate a client side proxy for calling the service without the client project needing
a service reference.  It really makes the Silverlight and the Web projects feel
like parts of the same app rather than disconnected pieces.  
</p>
        <p>
The corresponding class that is generated on the client side is a DomainDataContext,
which feels much like a LINQ to SQL DataContext only it’s lazy-loaded like the Astoria
ones.  The GetPersons method on the server results in LoadPersons on the client,
etc.  If I hadn’t implemented the Insert/Update/Delete methods on the server
side, the DomainDataContext would simple behave like a read only data source. 
This model works really well with the DataForm class.  If I set the ItemsSource
of the DataForm to the Persons “table” in the client side data context, it will properly
enable/disable the add/delete buttons depending on the capabilities of the data context. 
Neat.  
</p>
        <p>
Coming in future posts… hooking up the PersonDataContext to the Silverlight 3 UI,
and in ASP.NET
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>.NET RIA Services from Scratch</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,7ac6946a-d494-433d-a0c2-5737ae2e9ee8.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/NETRIAServicesFromScratch.aspx</link>
      <pubDate>Tue, 02 Jun 2009 22:53:18 GMT</pubDate>
      <description>&lt;p&gt;
Most of the demos/samples I’ve looked at so far for &lt;a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=76bb3a07-3846-4564-b0c3-27972bcaabce&amp;amp;displaylang=en"&gt;RIA
Services&lt;/a&gt; have started with a LINQ to SQL or ADO.NET Entity model and generated
Domain Service classes from those.&amp;nbsp; I decided to start from something super simple
(a POCO, if you will) and work up from there.&amp;nbsp; I started with a canonical&amp;nbsp;
“Person” class
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:c0d7eccf-2fd5-43f8-8f63-1952d006701e" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;public partial class Person : INotifyPropertyChanged
{
   #region INotifyPropertyChanged Members

   public event PropertyChangedEventHandler PropertyChanged;

   #endregion

   protected virtual void Changed(string propertyName)
   {
       PropertyChangedEventHandler handler = PropertyChanged;
       if (handler != null)
       {
           handler(this, new PropertyChangedEventArgs(propertyName));
       }
   }

   private int _personId;
   public int PersonId
   {
       get
       {
           return _personId;
       }
       set
       {
           if (_personId != value)
           {
               _personId = value;
               Changed("PersonId");
           }
       }
   }

   private string _firstName;
   public string FirstName
   {
...
   }
   private string _lastName;
   public string LastName
   {
...
   }
   private System.DateTime _birthDate;
   public System.DateTime BirthDate
   {
...
   }
}&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
Nothing to see here.&amp;nbsp; It’s just a simple POCO that supports INotifyPropertyChanged
for databinding.&amp;nbsp; Note that it’s a partial class…&amp;nbsp; The simplest path would
be to add RIA Services attributes directly to these properties for things like data
validation, but I wanted to try out all the features, so I split out the metadata
into another file
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:70bb36b8-81ba-48fc-8512-e36482d4ed2e" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;[MetadataTypeAttribute(typeof(RiaServices.Web.Person.PersonMetadata))]
public partial class Person
{

   internal sealed class PersonMetadata
   {
       [Key]
       [Required]
       public int PersonId;

       [Required]
       [RegularExpression("[a-zA-z]*")]
       public string FirstName;

       [Required]
       [RegularExpression("[a-zA-z]*")]
       public string LastName;

       [Required]
       public DateTime BirthDate;
   }
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
This is kind of an interesting trick, and allows me to separate out all the RIA specific
metadata from the original class definition.&amp;nbsp; This makes total sense when you
look at the way they handle LINQ to SQL, for example.&amp;nbsp; In that case you already
have Entity classes defined by the LINQ to SQL wizard, so this extra metadata class
allows you to associate the right attributes without touching the (generated) LINQ
to SQL classes.&amp;nbsp; Clever.&amp;nbsp; Notice that the metadata class uses fields, not
properties, and just matches the names for the sake of simplicity.
&lt;/p&gt;
&lt;p&gt;
In this case, the additional metadata defines data validation rules that get enforced
both server and client side.&amp;nbsp; There are other attributes to enforcing string
length and ranges.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
This all works because RIA Services generates “proxy” entity classes on the client
side that are Silverlight compilable and also DataContracts (for serializing, which
is cool…).&amp;nbsp; However, what happens if I have a calculated property that’s not
just storage?&amp;nbsp; There’s a solution for that too, and it involves another piece
of the partial class
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:09baa7be-63e0-47af-9d21-d18ecf0d1fcb" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;public partial class Person
{
   [Shared]
   public int Age
   {
       get
       {
           this.Changed("Age");
           return Convert.ToInt32(Math.Floor((DateTime.Now - _birthDate).Days / 365.25));
       }
   }

}&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
This bit goes in a file called Person.shared.cs, and it will be copied to the client
project and compiled there as well as on the server.&amp;nbsp; The [Shared] attribute
marks the bits that need to be thus propagated.&amp;nbsp; Again, clever.&amp;nbsp; Of course,
any such shared code has to compile in Silverlight.
&lt;/p&gt;
&lt;p&gt;
The other piece of code I want to share (using the same method) is a custom validator.&amp;nbsp;
In addition to the [Required] or [RegularExpression] attributes used above, you can
register a custom validation routine that can examine the state of the entity as a
whole.&amp;nbsp; The validation routine looks like this
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:1eef0b66-a7ec-418b-b4d3-9bb6ac09199d" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;[Shared]
public class PersonValidator
{
   public static bool IsPersonValid(Person p, ValidationContext context, out ValidationResult result)
   {
       bool valid = true;

       result = null;

       if (p.Age &amp;gt; 130)
           valid = false;

       if (!valid)
       {
           result = new ValidationResult("Birthdate is invalid, people can't be that old", new []{"BirthDate"});
       }

       return valid;

   }
}&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
That’s in a file called PersonValidator.shared.cs, so that it will be available client
and server-side.&amp;nbsp; It’s associated with the Person entity with an additional attribute
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:d75e9da4-a94d-4440-b0ac-e9beb3db8ed7" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; highlight: 1 ;"&gt;[CustomValidation(typeof(PersonValidator), "IsPersonValid")]
[MetadataTypeAttribute(typeof(RiaServices.Web.Person.PersonMetadata))]
public partial class Person
...&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
With the Person entity all ready, I can expose it to the client by creating a new
DomainService class with methods for Get, Insert, Update, Delete, etc.
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:9a554f7f-e2a6-4f0e-b838-7c7ee3bd3b71" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;[EnableClientAccess()]
public class PeopleDomainService : DomainService
{
   public IQueryable&amp;lt;Person&amp;gt; GetPersons()
   {

       return PeopleData.Persons.AsQueryable&amp;lt;Person&amp;gt;();
   }

   public IQueryable&amp;lt;Person&amp;gt; GetPerson(int personId)
   {
       return (from p in PeopleData.Persons
               where p.PersonId == personId
               select p).AsQueryable&amp;lt;Person&amp;gt;();
   }

   public void UpdatePerson(Person person)
   {
       Person oldP = (from p in PeopleData.Persons
                      where p.PersonId == person.PersonId
                      select p).FirstOrDefault();

       if (oldP != null)
       {
           PeopleData.Persons.Remove(oldP);
           PeopleData.Persons.Add(person);
       }
   }

   public void InsertPerson(Person person)
   {
       if (person.PersonId == 0)
       {
           int max = PeopleData.Persons.Max(p =&amp;gt; p.PersonId);
           person.PersonId = max + 1;
       }

       PeopleData.Persons.Add(person);
   }

   public void DeletePerson(Person person)
   {
       Person oldP = (from p in PeopleData.Persons
                      where p.PersonId == person.PersonId
                      select p).FirstOrDefault();

       if (oldP != null)
       {
           PeopleData.Persons.Remove(oldP);
       }
   }
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
PeopleData.Persons in this case is a List&amp;lt;Person&amp;gt; that’s populated with some
sample data.&amp;nbsp; The [EnableClientAccess] attribute causes the build-time bits to
generate a client side proxy for calling the service without the client project needing
a service reference.&amp;nbsp; It really makes the Silverlight and the Web projects feel
like parts of the same app rather than disconnected pieces.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
The corresponding class that is generated on the client side is a DomainDataContext,
which feels much like a LINQ to SQL DataContext only it’s lazy-loaded like the Astoria
ones.&amp;nbsp; The GetPersons method on the server results in LoadPersons on the client,
etc.&amp;nbsp; If I hadn’t implemented the Insert/Update/Delete methods on the server
side, the DomainDataContext would simple behave like a read only data source.&amp;nbsp;
This model works really well with the DataForm class.&amp;nbsp; If I set the ItemsSource
of the DataForm to the Persons “table” in the client side data context, it will properly
enable/disable the add/delete buttons depending on the capabilities of the data context.&amp;nbsp;
Neat.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
Coming in future posts… hooking up the PersonDataContext to the Silverlight 3 UI,
and in ASP.NET
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,7ac6946a-d494-433d-a0c2-5737ae2e9ee8.aspx</comments>
      <category>RIA Services</category>
      <category>Silverlight</category>
      <category>Work</category>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=064786e2-4c83-47e5-b897-b276f428c781</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,064786e2-4c83-47e5-b897-b276f428c781.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,064786e2-4c83-47e5-b897-b276f428c781.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=064786e2-4c83-47e5-b897-b276f428c781</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Shaun and I will be doing a one-day training, “<a href="http://events.sftsrc.com/EventDescription.aspx?EventId=1062&amp;AbstractId=681">Practical
Silverlight 3</a>”, in lovely San Francisco, CA on July 8th.  It’s a full day
of Silverlighty goodness, starting with the basics and movin’ on up.  We like
to think of it as a 300 level technical introduction to the subject, so you will come
away with a better understanding of the fundamentals, and where to look next.
</p>
        <p>
Topics include
</p>
        <ul>
          <li>
An introduction to Silverlight 3</li>
          <li>
All about controls (styling, templating, building your own)</li>
          <li>
Integrating with the browser</li>
          <li>
Communicating with the server via WCF, REST/POX, Sockets, you name it</li>
        </ul>
        <p>
If you are or will be in NorCal, come check it out.  It’s a good introduction
for a very reasonable price.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Silverlight: Taking it on the road</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,064786e2-4c83-47e5-b897-b276f428c781.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/SilverlightTakingItOnTheRoad.aspx</link>
      <pubDate>Thu, 28 May 2009 23:38:16 GMT</pubDate>
      <description>&lt;p&gt;
Shaun and I will be doing a one-day training, “&lt;a href="http://events.sftsrc.com/EventDescription.aspx?EventId=1062&amp;amp;AbstractId=681"&gt;Practical
Silverlight 3&lt;/a&gt;”, in lovely San Francisco, CA on July 8th.&amp;#160; It’s a full day
of Silverlighty goodness, starting with the basics and movin’ on up.&amp;#160; We like
to think of it as a 300 level technical introduction to the subject, so you will come
away with a better understanding of the fundamentals, and where to look next.
&lt;/p&gt;
&lt;p&gt;
Topics include
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
An introduction to Silverlight 3&lt;/li&gt;
&lt;li&gt;
All about controls (styling, templating, building your own)&lt;/li&gt;
&lt;li&gt;
Integrating with the browser&lt;/li&gt;
&lt;li&gt;
Communicating with the server via WCF, REST/POX, Sockets, you name it&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
If you are or will be in NorCal, come check it out.&amp;#160; It’s a good introduction
for a very reasonable price.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,064786e2-4c83-47e5-b897-b276f428c781.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=6594227c-d582-4e66-98ef-be3bc0a5244c</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,6594227c-d582-4e66-98ef-be3bc0a5244c.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,6594227c-d582-4e66-98ef-be3bc0a5244c.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=6594227c-d582-4e66-98ef-be3bc0a5244c</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://www.sftsrc.com">SoftSource</a> developer <a href="http://www.debuggingblog.com">Prashant
Sinha</a> is going to be presenting on <a href="http://portlandcodecamp.org/session.aspx?sid=3dd15647-a032-4448-b259-70728b23ad14">“Production
Debugging for Silverlight and ASP.NET”</a> at Code Camp.  Prashant is a debugging
wiz, and teaches our two-day .NET debugging course, so this should be a very useful
session.  
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Debugging session at PDX Code Camp</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,6594227c-d582-4e66-98ef-be3bc0a5244c.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/DebuggingSessionAtPDXCodeCamp.aspx</link>
      <pubDate>Tue, 26 May 2009 20:51:11 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://www.sftsrc.com"&gt;SoftSource&lt;/a&gt; developer &lt;a href="http://www.debuggingblog.com"&gt;Prashant
Sinha&lt;/a&gt; is going to be presenting on &lt;a href="http://portlandcodecamp.org/session.aspx?sid=3dd15647-a032-4448-b259-70728b23ad14"&gt;“Production
Debugging for Silverlight and ASP.NET”&lt;/a&gt; at Code Camp.&amp;#160; Prashant is a debugging
wiz, and teaches our two-day .NET debugging course, so this should be a very useful
session.&amp;#160; 
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,6594227c-d582-4e66-98ef-be3bc0a5244c.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=4864bfbe-c60e-4829-b092-092ed46cde82</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,4864bfbe-c60e-4829-b092-092ed46cde82.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,4864bfbe-c60e-4829-b092-092ed46cde82.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=4864bfbe-c60e-4829-b092-092ed46cde82</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In my <a href="http://www.amazon.com/dp/0470259248?tag=patricvikkica-20&amp;camp=14573&amp;creative=327641&amp;linkCode=as1&amp;creativeASIN=0470259248&amp;adid=0806NXZ2A5V5VPGTAE5D&amp;">book</a>,
I talked a bit about programming by contract and how that makes everyone’s lives easier. 
Say I have a method that divides one integer by another
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:dfce7d2c-7373-4959-ae45-84cf2ae78204" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">public double Divide(int dividend, int divisor)
{
  return dividend / divisor;
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
I’d like to be able to let callers know that they can’t pass a 0 for the divisor,
because that will result in a DivideByZeroException, and nobody wants that. 
In the past I had a couple of choices on how to express that, mostly involving writing
different kids of code, because C# doesn’t have a native expression of design by contract
like Eiffel does.  One way is to use Debug.Assert
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:225e6e36-d5f2-417d-99bd-9aa339fc66a2" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">public double Divide(int dividend, int divisor)
{
  Debug.Assert(divisor != 0);

  return dividend / divisor;
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
        </p>
        <p>
That way any caller that passes a 0 will get an assertion dialog at runtime, which
brings it pretty dramatically to everyone’s attention.  The assumption is that
using the Debug.Assert will flush out all cases where people are incorrectly calling
my method during development, so it’s OK that the assertion will get compiled out
of my Release build.  However, that doesn’t make it impossible for a caller to
pass a 0 at runtime and cause the exception.  Another option is explicitly checking
parameters and throwing a different exception.
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:15cc7a83-ea90-4d71-a05e-4f361652cc58" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">public double Divide(int dividend, int divisor)
{
  if (divisor == 0)
      throw new ArgumentException("divisor cannot be zero", "divisor");

  return dividend / divisor;
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
          <a href="http://codebetter.com/blogs/patricksmacchia/archive/2009/05/17/book-review-code-leader-by-patrick-cauldwell-a-digression-on-contracts.aspx">Patrick</a> argues
that this has now moved from defining contract to defining behavior, and I can agree
with that, although I’d probably argue that it defines both contract and behavior
since I’ve extended the functionality of the Debug.Assert to the release build, while
also protecting my internal state from bad data.  But that’s really a separate
discussion… :)
</p>
        <p>
Now thanks to the <a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx">Microsoft
Code Contracts</a> project, I have a third option.  The Code Contracts project
is the evolution of the work done on Spec#, but in a language neutral way.  The
Code Contracts tools are currently available from DevLabs for VS 2008, as well as
shipping with VS 2010 B 1.  Just at the moment, there are more features in the
DevLabs version that what made it into the 2010 beta.  With Code Contracts, I
can rewrite my Divide method like this
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:de17865f-a475-4949-9f7c-68013b211d3e" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">public double Divide(int dividend, int divisor)
{
  Contract.Requires(divisor != 0);

  return dividend / divisor;
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
I like the syntax, as it calls out quite explicitly that I’m talking about contract,
and making an explicit requirement.  The default behavior of this method at runtime
is identical to Debug.Assert, it brings up an assertion dialog and brings everything
to a screeching halt. However, it’s configurable at build time, so I can have it throw
exceptions instead, or do whatever might be appropriate for my environment if the
contract is violated.  I can even get the best of both worlds, with a generic
version of Requires that specifies an exception
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:80a3b1b7-94eb-4dfe-bc89-1895ef757aa9" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">public double Divide(int dividend, int divisor)
{
  Contract.Requires&lt;ArgumentException&gt;(divisor != 0, "divisor");

  return dividend / divisor;
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
I could configure this to bring up the assertion dialog in Debug builds, but throw
ArgumentNullException in Release builds.  Good stuff. 
</p>
        <p>
The example above demonstrates a required “precondition”.  With Code Contracts,
I can also specify “postconditions”.  
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:640f428b-ea7b-4994-8b7f-389e352dbb36" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">public void Transfer(Account from, Account to, decimal amount)
{
  Contract.Requires(from != null);
  Contract.Requires(to != null);
  Contract.Requires(amount &gt; 0);
  Contract.Ensures(from.Balance &gt;= 0);

  if (from.Balance &lt; 0 || from.Balance &lt; amount)
      throw new InsufficientFundsException();

  from.Balance -= amount;
  to.Balance += amount;

}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
This isn’t the greatest example, but basically the Transfer method is promising (with
the Contract.Ensures method) that it won’t ever leave the Balance a negative number. 
Again, this is arguably behavior rather than contract, but you get the point.  
</p>
        <p>
A really nifty feature is that I can write an interface definition and associate it
with a set of contract calls, so that anyone who implements the interface will automatically
“inherit” the contract validation.  The syntax is a bit weird, but you can see
why it would need to be like this…
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:6aaea4a2-2c02-43ae-bf54-2609c119a94e" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">[ContractClass(typeof(ContractForCalucluator))]
interface ICalculator
{
   int Add(int op1, int op2);
   double Divide(int dividend, int divisor);
}

[ContractClassFor(typeof(ICalculator))]
class ContractForCalucluator : ICalculator
{
   #region ICalculator Members

   public int Add(int op1, int op2)
   {
       return default(int);
   }

   public double Divide(int dividend, int divisor)
   {
       Contract.Requires(divisor != 0);

       return default(double);
   }

   #endregion
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
Now any class that implements ICalculator will have the contract validated for the
Divide method.  Cool.  The last thing I want to point out is that the team
included a handy sample of how to work with contract validation in your MSTest unit
test code.  The Contract class exposes an event called ContractFailed, and I
can subscribe to the event to decide what happens on a failure.  For a test assembly,
I can do this
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:2d2c7b05-8398-467c-b1d1-ddeef3b7fb8b" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">[AssemblyInitialize]
public static void AssemblyInitialize(TestContext tc)
{
  Contract.ContractFailed += (sender, e) =&gt;
  {
      e.SetHandled();
      e.SetUnwind();
      Assert.Fail(e.FailureKind.ToString() + " : " + e.Message);
  };
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
which will translate contract failures into test failures with very explicit error
messages.  In the case of my Divide method if I run this test
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:5727431d-7999-4bd2-94ec-eec819769016" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">[TestMethod()]
public void DivideContractViolation()
{
  Calculator target = new Calculator(); 
  int dividend = 12; 
  int divisor = 0; 
  double actual;
  actual = target.Divide(dividend, divisor);
  Assert.Fail("Should have failed");
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
I get a test failure of
</p>
        <blockquote>
          <p>
Test method CalculatorTests.CalculatorTest.DivideContractViolation threw exception: 
System.Diagnostics.Contracts.ContractException: Precondition failed: divisor != 0
divisor ---&gt;  Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException:
Assert.Fail failed. Precondition : Precondition failed: divisor != 0 divisor.
</p>
        </blockquote>
        <p>
Cool.  This is definitely something I’ll be looking at more in the future.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Code Contracts</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,4864bfbe-c60e-4829-b092-092ed46cde82.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/CodeContracts.aspx</link>
      <pubDate>Thu, 21 May 2009 21:50:38 GMT</pubDate>
      <description>&lt;p&gt;
In my &lt;a href="http://www.amazon.com/dp/0470259248?tag=patricvikkica-20&amp;amp;camp=14573&amp;amp;creative=327641&amp;amp;linkCode=as1&amp;amp;creativeASIN=0470259248&amp;amp;adid=0806NXZ2A5V5VPGTAE5D&amp;amp;"&gt;book&lt;/a&gt;,
I talked a bit about programming by contract and how that makes everyone’s lives easier.&amp;#160;
Say I have a method that divides one integer by another
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:dfce7d2c-7373-4959-ae45-84cf2ae78204" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public double Divide(int dividend, int divisor)
{
  return dividend / divisor;
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
I’d like to be able to let callers know that they can’t pass a 0 for the divisor,
because that will result in a DivideByZeroException, and nobody wants that.&amp;#160;
In the past I had a couple of choices on how to express that, mostly involving writing
different kids of code, because C# doesn’t have a native expression of design by contract
like Eiffel does.&amp;#160; One way is to use Debug.Assert
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:225e6e36-d5f2-417d-99bd-9aa339fc66a2" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public double Divide(int dividend, int divisor)
{
  Debug.Assert(divisor != 0);

  return dividend / divisor;
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
That way any caller that passes a 0 will get an assertion dialog at runtime, which
brings it pretty dramatically to everyone’s attention.&amp;#160; The assumption is that
using the Debug.Assert will flush out all cases where people are incorrectly calling
my method during development, so it’s OK that the assertion will get compiled out
of my Release build.&amp;#160; However, that doesn’t make it impossible for a caller to
pass a 0 at runtime and cause the exception.&amp;#160; Another option is explicitly checking
parameters and throwing a different exception.
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:15cc7a83-ea90-4d71-a05e-4f361652cc58" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public double Divide(int dividend, int divisor)
{
  if (divisor == 0)
      throw new ArgumentException(&amp;quot;divisor cannot be zero&amp;quot;, &amp;quot;divisor&amp;quot;);

  return dividend / divisor;
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
&lt;a href="http://codebetter.com/blogs/patricksmacchia/archive/2009/05/17/book-review-code-leader-by-patrick-cauldwell-a-digression-on-contracts.aspx"&gt;Patrick&lt;/a&gt; argues
that this has now moved from defining contract to defining behavior, and I can agree
with that, although I’d probably argue that it defines both contract and behavior
since I’ve extended the functionality of the Debug.Assert to the release build, while
also protecting my internal state from bad data.&amp;#160; But that’s really a separate
discussion… :)
&lt;/p&gt;
&lt;p&gt;
Now thanks to the &lt;a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx"&gt;Microsoft
Code Contracts&lt;/a&gt; project, I have a third option.&amp;#160; The Code Contracts project
is the evolution of the work done on Spec#, but in a language neutral way.&amp;#160; The
Code Contracts tools are currently available from DevLabs for VS 2008, as well as
shipping with VS 2010 B 1.&amp;#160; Just at the moment, there are more features in the
DevLabs version that what made it into the 2010 beta.&amp;#160; With Code Contracts, I
can rewrite my Divide method like this
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:de17865f-a475-4949-9f7c-68013b211d3e" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public double Divide(int dividend, int divisor)
{
  Contract.Requires(divisor != 0);

  return dividend / divisor;
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
I like the syntax, as it calls out quite explicitly that I’m talking about contract,
and making an explicit requirement.&amp;#160; The default behavior of this method at runtime
is identical to Debug.Assert, it brings up an assertion dialog and brings everything
to a screeching halt. However, it’s configurable at build time, so I can have it throw
exceptions instead, or do whatever might be appropriate for my environment if the
contract is violated.&amp;#160; I can even get the best of both worlds, with a generic
version of Requires that specifies an exception
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:80a3b1b7-94eb-4dfe-bc89-1895ef757aa9" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public double Divide(int dividend, int divisor)
{
  Contract.Requires&amp;lt;ArgumentException&amp;gt;(divisor != 0, &amp;quot;divisor&amp;quot;);

  return dividend / divisor;
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
I could configure this to bring up the assertion dialog in Debug builds, but throw
ArgumentNullException in Release builds.&amp;#160; Good stuff. 
&lt;/p&gt;
&lt;p&gt;
The example above demonstrates a required “precondition”.&amp;#160; With Code Contracts,
I can also specify “postconditions”.&amp;#160; 
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:640f428b-ea7b-4994-8b7f-389e352dbb36" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public void Transfer(Account from, Account to, decimal amount)
{
  Contract.Requires(from != null);
  Contract.Requires(to != null);
  Contract.Requires(amount &amp;gt; 0);
  Contract.Ensures(from.Balance &amp;gt;= 0);

  if (from.Balance &amp;lt; 0 || from.Balance &amp;lt; amount)
      throw new InsufficientFundsException();

  from.Balance -= amount;
  to.Balance += amount;

}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
This isn’t the greatest example, but basically the Transfer method is promising (with
the Contract.Ensures method) that it won’t ever leave the Balance a negative number.&amp;#160;
Again, this is arguably behavior rather than contract, but you get the point.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
A really nifty feature is that I can write an interface definition and associate it
with a set of contract calls, so that anyone who implements the interface will automatically
“inherit” the contract validation.&amp;#160; The syntax is a bit weird, but you can see
why it would need to be like this…
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:6aaea4a2-2c02-43ae-bf54-2609c119a94e" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;[ContractClass(typeof(ContractForCalucluator))]
interface ICalculator
{
   int Add(int op1, int op2);
   double Divide(int dividend, int divisor);
}

[ContractClassFor(typeof(ICalculator))]
class ContractForCalucluator : ICalculator
{
   #region ICalculator Members

   public int Add(int op1, int op2)
   {
       return default(int);
   }

   public double Divide(int dividend, int divisor)
   {
       Contract.Requires(divisor != 0);

       return default(double);
   }

   #endregion
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
Now any class that implements ICalculator will have the contract validated for the
Divide method.&amp;#160; Cool.&amp;#160; The last thing I want to point out is that the team
included a handy sample of how to work with contract validation in your MSTest unit
test code.&amp;#160; The Contract class exposes an event called ContractFailed, and I
can subscribe to the event to decide what happens on a failure.&amp;#160; For a test assembly,
I can do this
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:2d2c7b05-8398-467c-b1d1-ddeef3b7fb8b" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;[AssemblyInitialize]
public static void AssemblyInitialize(TestContext tc)
{
  Contract.ContractFailed += (sender, e) =&amp;gt;
  {
      e.SetHandled();
      e.SetUnwind();
      Assert.Fail(e.FailureKind.ToString() + &amp;quot; : &amp;quot; + e.Message);
  };
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
which will translate contract failures into test failures with very explicit error
messages.&amp;#160; In the case of my Divide method if I run this test
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:5727431d-7999-4bd2-94ec-eec819769016" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;[TestMethod()]
public void DivideContractViolation()
{
  Calculator target = new Calculator(); 
  int dividend = 12; 
  int divisor = 0; 
  double actual;
  actual = target.Divide(dividend, divisor);
  Assert.Fail(&amp;quot;Should have failed&amp;quot;);
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
I get a test failure of
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
Test method CalculatorTests.CalculatorTest.DivideContractViolation threw exception:&amp;#160;
System.Diagnostics.Contracts.ContractException: Precondition failed: divisor != 0
divisor ---&amp;gt;&amp;#160; Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException:
Assert.Fail failed. Precondition : Precondition failed: divisor != 0 divisor.
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Cool.&amp;#160; This is definitely something I’ll be looking at more in the future.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,4864bfbe-c60e-4829-b092-092ed46cde82.aspx</comments>
      <category>Code Construction</category>
      <category>Testing</category>
      <category>Work</category>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=ff37319d-3c19-42ad-abe7-0a7be61b317e</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,ff37319d-3c19-42ad-abe7-0a7be61b317e.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,ff37319d-3c19-42ad-abe7-0a7be61b317e.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=ff37319d-3c19-42ad-abe7-0a7be61b317e</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Not this weekend but next (5/30) is <a href="http://portlandcodecamp.org">PDX Code
Camp 2009</a>.  A whole day of free software learning and general nerdy hanging
out.  I’ll be talking about building business apps in Silverlight 3, and my <a href="http://www.sftsrc.com">SoftSource</a> compadre
Tim Johnson is going to be talking about making your web application more accessible
for people with disabilities.  There are also a host of other sessions including
some big names like Ward Cunningham, so it’s an event not to be missed, and cheap
at twice the price!
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>PDX Code Camp is coming up&amp;hellip;</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,ff37319d-3c19-42ad-abe7-0a7be61b317e.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/PDXCodeCampIsComingUphellip.aspx</link>
      <pubDate>Wed, 20 May 2009 20:45:43 GMT</pubDate>
      <description>&lt;p&gt;
Not this weekend but next (5/30) is &lt;a href="http://portlandcodecamp.org"&gt;PDX Code
Camp 2009&lt;/a&gt;.&amp;#160; A whole day of free software learning and general nerdy hanging
out.&amp;#160; I’ll be talking about building business apps in Silverlight 3, and my &lt;a href="http://www.sftsrc.com"&gt;SoftSource&lt;/a&gt; compadre
Tim Johnson is going to be talking about making your web application more accessible
for people with disabilities.&amp;#160; There are also a host of other sessions including
some big names like Ward Cunningham, so it’s an event not to be missed, and cheap
at twice the price!
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,ff37319d-3c19-42ad-abe7-0a7be61b317e.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=fa25181c-c4a7-4d8b-947a-6d14bc07ee12</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,fa25181c-c4a7-4d8b-947a-6d14bc07ee12.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,fa25181c-c4a7-4d8b-947a-6d14bc07ee12.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=fa25181c-c4a7-4d8b-947a-6d14bc07ee12</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This came up in class yesterday, so I did a little digging.  Everyone may already
know this, but it came as news to me. :)
</p>
        <p>
If I’ve got a collection in memory, as well as a LINQ to SQL DataContext
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:863b2a97-d5bd-42de-87fa-dfdd99572795" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">List&lt;FavoriteFood&gt; foods = new List&lt;FavoriteFood&gt;(){
	new FavoriteFood{CustomerID = "ALFKI", Favorite="Chips"},
	new FavoriteFood{CustomerID = "ANATR", Favorite = "Fish"}};

NorthwindDataContext context = new NorthwindDataContext();
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
and I want to do an INNER JOIN between the <code>foods</code> list and the Customer
table in Northwind, it would seem like this should do it
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:14223c48-ead8-4350-ac80-44224c210c41" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">var bad = (from cust in context.Customers
         join f in foods on cust.CustomerID equals f.CustomerID
         select new
         {
             cust.ContactName,
             f.Favorite
         }).ToList();
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
but sadly, no.
</p>
        <p>
          <a href="http://www.cauldwell.net/patrick/blog/images/LINQjoiningdatainmemorywithdatainSQLServ_BF72/image.png">
            <img style="border-width: 0px; display: inline;" title="image" alt="image" src="http://www.cauldwell.net/patrick/blog/images/LINQjoiningdatainmemorywithdatainSQLServ_BF72/image_thumb.png" border="0" width="419" height="258" />
          </a>
        </p>
        <p>
if you stop to think about it, it totally makes sense that it wouldn’t work like that,
since there’s no way to translate that into SQL in any rational way to send to SQL
server.  
</p>
        <p>
OK, so the next step would be to first get the customers in memory, then do the join
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:991fb98d-884f-407f-b472-8e82fc69b354" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">//this executes the whole query, thus retrieving the entire customer table
var customers = (from c in context.Customers
             select c).ToList();

//an inner join between the customers from SQL and the in-memory list
var inner = from cust in customers
     join f in foods on cust.CustomerID equals f.CustomerID
     select new
     {
         cust.ContactName,
         f.Favorite
     };
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
That works, but I’ve had to pull the entire Customer table into memory just to join
two rows.  If I wanted to do a LEFT OUTER JOIN, I’d need that anyway, like so
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:70268c0d-75a2-4c83-bf0e-df7eb45d01c3" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">//here's the left outer join between the customer list from SQL 
//and the in-memory favorites
var leftouter = from cust in customers
             join f in foods on cust.CustomerID equals f.CustomerID into custFoods
             from custFood in custFoods.DefaultIfEmpty()
             select new
             {
                 cust.ContactName,
                 Favorite = custFood == null ? null : custFood.Favorite
             };
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
but I want an inner join without pulling down all the customers, so I need to only
fetch those rows that will join from Customer
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:26850cad-8cbd-4d00-b6b4-37cf6151d284" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">//this is how you manage the IN clause
var x = from c1 in context.Customers
     where (from cf in foods
           select cf.CustomerID).Contains(c1.CustomerID)
     select c1;

//Note that to join the result in x back to the foods collection you would have to 
//execute the query just like with customers above...
var littleInnerJoin = from filteredCustomer in x.ToList()
                   join f in foods on filteredCustomer.CustomerID equals f.CustomerID
                   select new
                       {
                           filteredCustomer.ContactName,
                           f.Favorite
                       };
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
It’s two steps, but now I’ve just loaded the rows that will join into memory, and
then done the join with LINQ to Objects.  It bears a little thinking about, but
doesn’t seem like too much overhead, IMHO.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>LINQ: joining data in memory with data in SQL Server</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,fa25181c-c4a7-4d8b-947a-6d14bc07ee12.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/LINQJoiningDataInMemoryWithDataInSQLServer.aspx</link>
      <pubDate>Wed, 20 May 2009 20:38:43 GMT</pubDate>
      <description>&lt;p&gt;
This came up in class yesterday, so I did a little digging.&amp;nbsp; Everyone may already
know this, but it came as news to me. :)
&lt;/p&gt;
&lt;p&gt;
If I’ve got a collection in memory, as well as a LINQ to SQL DataContext
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:863b2a97-d5bd-42de-87fa-dfdd99572795" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;List&amp;lt;FavoriteFood&amp;gt; foods = new List&amp;lt;FavoriteFood&amp;gt;(){
	new FavoriteFood{CustomerID = "ALFKI", Favorite="Chips"},
	new FavoriteFood{CustomerID = "ANATR", Favorite = "Fish"}};

NorthwindDataContext context = new NorthwindDataContext();
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
and I want to do an INNER JOIN between the &lt;code&gt;foods&lt;/code&gt; list and the Customer
table in Northwind, it would seem like this should do it
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:14223c48-ead8-4350-ac80-44224c210c41" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;var bad = (from cust in context.Customers
         join f in foods on cust.CustomerID equals f.CustomerID
         select new
         {
             cust.ContactName,
             f.Favorite
         }).ToList();
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
but sadly, no.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.cauldwell.net/patrick/blog/images/LINQjoiningdatainmemorywithdatainSQLServ_BF72/image.png"&gt;&lt;img style="border-width: 0px; display: inline;" title="image" alt="image" src="http://www.cauldwell.net/patrick/blog/images/LINQjoiningdatainmemorywithdatainSQLServ_BF72/image_thumb.png" border="0" width="419" height="258"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
if you stop to think about it, it totally makes sense that it wouldn’t work like that,
since there’s no way to translate that into SQL in any rational way to send to SQL
server.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
OK, so the next step would be to first get the customers in memory, then do the join
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:991fb98d-884f-407f-b472-8e82fc69b354" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;//this executes the whole query, thus retrieving the entire customer table
var customers = (from c in context.Customers
             select c).ToList();

//an inner join between the customers from SQL and the in-memory list
var inner = from cust in customers
     join f in foods on cust.CustomerID equals f.CustomerID
     select new
     {
         cust.ContactName,
         f.Favorite
     };
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
That works, but I’ve had to pull the entire Customer table into memory just to join
two rows.&amp;nbsp; If I wanted to do a LEFT OUTER JOIN, I’d need that anyway, like so
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:70268c0d-75a2-4c83-bf0e-df7eb45d01c3" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;//here's the left outer join between the customer list from SQL 
//and the in-memory favorites
var leftouter = from cust in customers
             join f in foods on cust.CustomerID equals f.CustomerID into custFoods
             from custFood in custFoods.DefaultIfEmpty()
             select new
             {
                 cust.ContactName,
                 Favorite = custFood == null ? null : custFood.Favorite
             };
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
but I want an inner join without pulling down all the customers, so I need to only
fetch those rows that will join from Customer
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:26850cad-8cbd-4d00-b6b4-37cf6151d284" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;//this is how you manage the IN clause
var x = from c1 in context.Customers
     where (from cf in foods
           select cf.CustomerID).Contains(c1.CustomerID)
     select c1;

//Note that to join the result in x back to the foods collection you would have to 
//execute the query just like with customers above...
var littleInnerJoin = from filteredCustomer in x.ToList()
                   join f in foods on filteredCustomer.CustomerID equals f.CustomerID
                   select new
                       {
                           filteredCustomer.ContactName,
                           f.Favorite
                       };
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
It’s two steps, but now I’ve just loaded the rows that will join into memory, and
then done the join with LINQ to Objects.&amp;nbsp; It bears a little thinking about, but
doesn’t seem like too much overhead, IMHO.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,fa25181c-c4a7-4d8b-947a-6d14bc07ee12.aspx</comments>
      <category>Work</category>
      <category>LINQ</category>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=94fb91a2-2c6c-422f-a48e-3f46aabcd8a2</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,94fb91a2-2c6c-422f-a48e-3f46aabcd8a2.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,94fb91a2-2c6c-422f-a48e-3f46aabcd8a2.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=94fb91a2-2c6c-422f-a48e-3f46aabcd8a2</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Let’s say I’ve got to the effort of creating a modal dialog or it’s equivalent in
a Silverlight application.  What I would like to complete the picture is a “default”
button, so that if I hit the Enter key while in a text box, the dialog will be “submitted”. 
There are probably several ways of achieving this end, but I wanted something that
was simple, and encapsulated in an attached property so the consumer wouldn’t have
to deal with much code.  I wrote the attached property so that I could use it
on text boxes like this
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:53e11dba-4d3e-4301-8129-6611a235d4fe" class="wlWriterEditableSmartContent">
          <pre class="brush: xml; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">&lt;TextBox x:Name="theText" VerticalAlignment="Center" Margin="10,0,10,0" 
	Grid.Row="0" my:DefaultButtonService.DefaultButton="theButton"/&gt;</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <p>
where “theButton” here is the default button I want to be pressed when the Enter key
happens inside my text box.  The downside is that I have to apply this property
to every text box on the page, but so be it, that seems like a relatively small price
to pay.  So I got as far as finding the named button in the visual tree, but
the the question was, how to “press” the button.  The Button class in Silverlight
has a protected OnClick that would do the trick, if it wasn’t protected.  I could
derive my own control from Button and expose the OnClick method, but ewww.  If
I did that then every dialog that wanted this behavior would have to remember to use
the derived Button class.  I tried reflecting over the Button and Invoking OnClick
anyway, but turns out you get a security exception.  OK.  Then, thanks to
a presentation <a href="http://blogs.sftsrc.com/stuart/Default.aspx">Stuart</a> gave
us yesterday on Accessibility, I remembered the Automation framework in Silverlight. 
That turned out to be super easy, just create an instance of ButtonAutmationPeer from
the Button, then Invoke it.  Cool.
</p>
        <div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:77a2e41a-7d86-4263-9298-977c8aeb4971" class="wlWriterEditableSmartContent">
          <pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">public static class DefaultButtonService
{
   public static readonly DependencyProperty DefaultButtonProperty =
       DependencyProperty.RegisterAttached("DefaultButton", typeof(string), typeof(DefaultButtonService), new PropertyMetadata(OnDefaultButtonChanged));


   public static string GetDefaultButton(DependencyObject d)
   {
       return (string)d.GetValue(DefaultButtonProperty);
   }

   /// &lt;summary&gt;
   /// Sets the CommandParameter property.
   /// &lt;/summary&gt;
   public static void SetDefaultButton(DependencyObject d, string value)
   {
       d.SetValue(DefaultButtonProperty, value);
   }

   private static void OnDefaultButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   {
       TextBox tb = d as TextBox;
       if (tb != null)
       {
           tb.KeyUp += new KeyEventHandler(tb_KeyUp);
       }
   }

   static void tb_KeyUp(object sender, KeyEventArgs e)
   {
       switch (e.Key)
       {
           case Key.Enter:
               string name = (string)((DependencyObject)sender).GetValue(DefaultButtonProperty);
               object root = App.Current.RootVisual;
               object button = ((FrameworkElement)root).FindName(name);
               if (button is Button)
               {
                   ButtonAutomationPeer peer = new ButtonAutomationPeer((Button)button);

                   IInvokeProvider ip = (IInvokeProvider)peer;
                   ip.Invoke();
               }
               break;
       }
   }
}
</pre>
          <!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com -->
        </div>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>A &amp;ldquo;default button&amp;rdquo; in Silverlight</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,94fb91a2-2c6c-422f-a48e-3f46aabcd8a2.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/ALdquodefaultButtonrdquoInSilverlight.aspx</link>
      <pubDate>Thu, 07 May 2009 20:27:54 GMT</pubDate>
      <description>&lt;p&gt;
Let’s say I’ve got to the effort of creating a modal dialog or it’s equivalent in
a Silverlight application.&amp;nbsp; What I would like to complete the picture is a “default”
button, so that if I hit the Enter key while in a text box, the dialog will be “submitted”.&amp;nbsp;
There are probably several ways of achieving this end, but I wanted something that
was simple, and encapsulated in an attached property so the consumer wouldn’t have
to deal with much code.&amp;nbsp; I wrote the attached property so that I could use it
on text boxes like this
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:53e11dba-4d3e-4301-8129-6611a235d4fe" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: xml; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;&amp;lt;TextBox x:Name="theText" VerticalAlignment="Center" Margin="10,0,10,0" 
	Grid.Row="0" my:DefaultButtonService.DefaultButton="theButton"/&amp;gt;&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;p&gt;
where “theButton” here is the default button I want to be pressed when the Enter key
happens inside my text box.&amp;nbsp; The downside is that I have to apply this property
to every text box on the page, but so be it, that seems like a relatively small price
to pay.&amp;nbsp; So I got as far as finding the named button in the visual tree, but
the the question was, how to “press” the button.&amp;nbsp; The Button class in Silverlight
has a protected OnClick that would do the trick, if it wasn’t protected.&amp;nbsp; I could
derive my own control from Button and expose the OnClick method, but ewww.&amp;nbsp; If
I did that then every dialog that wanted this behavior would have to remember to use
the derived Button class.&amp;nbsp; I tried reflecting over the Button and Invoking OnClick
anyway, but turns out you get a security exception.&amp;nbsp; OK.&amp;nbsp; Then, thanks to
a presentation &lt;a href="http://blogs.sftsrc.com/stuart/Default.aspx"&gt;Stuart&lt;/a&gt; gave
us yesterday on Accessibility, I remembered the Automation framework in Silverlight.&amp;nbsp;
That turned out to be super easy, just create an instance of ButtonAutmationPeer from
the Button, then Invoke it.&amp;nbsp; Cool.
&lt;/p&gt;
&lt;div style="margin: 0px; padding: 0px; display: inline; float: none;" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:77a2e41a-7d86-4263-9298-977c8aeb4971" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"&gt;public static class DefaultButtonService
{
   public static readonly DependencyProperty DefaultButtonProperty =
       DependencyProperty.RegisterAttached("DefaultButton", typeof(string), typeof(DefaultButtonService), new PropertyMetadata(OnDefaultButtonChanged));


   public static string GetDefaultButton(DependencyObject d)
   {
       return (string)d.GetValue(DefaultButtonProperty);
   }

   /// &amp;lt;summary&amp;gt;
   /// Sets the CommandParameter property.
   /// &amp;lt;/summary&amp;gt;
   public static void SetDefaultButton(DependencyObject d, string value)
   {
       d.SetValue(DefaultButtonProperty, value);
   }

   private static void OnDefaultButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   {
       TextBox tb = d as TextBox;
       if (tb != null)
       {
           tb.KeyUp += new KeyEventHandler(tb_KeyUp);
       }
   }

   static void tb_KeyUp(object sender, KeyEventArgs e)
   {
       switch (e.Key)
       {
           case Key.Enter:
               string name = (string)((DependencyObject)sender).GetValue(DefaultButtonProperty);
               object root = App.Current.RootVisual;
               object button = ((FrameworkElement)root).FindName(name);
               if (button is Button)
               {
                   ButtonAutomationPeer peer = new ButtonAutomationPeer((Button)button);

                   IInvokeProvider ip = (IInvokeProvider)peer;
                   ip.Invoke();
               }
               break;
       }
   }
}
&lt;/pre&gt;
&lt;!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,94fb91a2-2c6c-422f-a48e-3f46aabcd8a2.aspx</comments>
      <category>Silverlight</category>
      <category>Work</category>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=32617f89-fb84-46d3-a0de-cf028ba56521</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,32617f89-fb84-46d3-a0de-cf028ba56521.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,32617f89-fb84-46d3-a0de-cf028ba56521.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=32617f89-fb84-46d3-a0de-cf028ba56521</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
We just added a set of new one day classes starting in May, including “Agile in day”,
Silverlight 3, and UI design patterns for WPF and Silverlight.  These are lecture-style
classes that will give you an in depth look at each subject.  Like our previous
Silverlight event, these are 300-400 level, technical sessions that will give you
a leg up on each subject in a day.  Because they are presented lecture style,
we can offer them for only $125 each, so feel free to collect the whole set. :-) 
Details and registration <a href="http://events.sftsrc.com/">here</a>.  We may
be adding some additional topics soon, so check back often.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>New one-day classes at SoftSource</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,32617f89-fb84-46d3-a0de-cf028ba56521.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/NewOnedayClassesAtSoftSource.aspx</link>
      <pubDate>Tue, 07 Apr 2009 17:41:19 GMT</pubDate>
      <description>&lt;p&gt;
We just added a set of new one day classes starting in May, including “Agile in day”,
Silverlight 3, and UI design patterns for WPF and Silverlight.&amp;nbsp; These are lecture-style
classes that will give you an in depth look at each subject.&amp;nbsp; Like our previous
Silverlight event, these are 300-400 level, technical sessions that will give you
a leg up on each subject in a day.&amp;nbsp; Because they are presented lecture style,
we can offer them for only $125 each, so feel free to collect the whole set. :-)&amp;nbsp;
Details and registration &lt;a href="http://events.sftsrc.com/"&gt;here&lt;/a&gt;.&amp;nbsp; We may
be adding some additional topics soon, so check back often.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,32617f89-fb84-46d3-a0de-cf028ba56521.aspx</comments>
      <category>Silverlight</category>
      <category>training</category>
      <category>Work</category>
      <category>Agile</category>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=7d4b00dc-ce68-44f3-a493-9d7073d3bcdd</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,7d4b00dc-ce68-44f3-a493-9d7073d3bcdd.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,7d4b00dc-ce68-44f3-a493-9d7073d3bcdd.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=7d4b00dc-ce68-44f3-a493-9d7073d3bcdd</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">I'll probably have some more cogent things
to say about it all in a few days, but my first set of takeaways as of mid-day Thursday: 
<ul><li>
Silverlight 3 solves many if not most of the downsides of working in Silverlight vs.
WPF</li><li>
Silverlight 3 + .NET RIA services totally removes any and all barriers to building
business apps in Silverlight</li><li>
.NET RIA services is the killer app we’ve been waiting for as far as building RIA
apps is concerned.  it’s like Astoria, only better, and doesn’t require Entities
(long live LINQ to SQL!).  
</li><li>
Blend 3 will revolutionize the way designers and developers work together, and make
the design process much faster</li><li>
Free martinis are both a blessing and a curse</li><li>
Having a DJ at your keynotes is a fantastic idea</li><li>
Not only would downtown Hillsboro (where I live) fit inside the Venetian, but you
probably wouldn’t actually notice it.</li></ul><br /><hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>MIX 09 - Thursday</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,7d4b00dc-ce68-44f3-a493-9d7073d3bcdd.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/MIX09Thursday.aspx</link>
      <pubDate>Thu, 19 Mar 2009 20:45:58 GMT</pubDate>
      <description>I'll probably have some more cogent things to say about it all in a few days, but my first set of takeaways as of mid-day Thursday:   &lt;ul&gt;
&lt;li&gt;
Silverlight 3 solves many if not most of the downsides of working in Silverlight vs.
WPF&lt;/li&gt;
&lt;li&gt;
Silverlight 3 + .NET RIA services totally removes any and all barriers to building
business apps in Silverlight&lt;/li&gt;
&lt;li&gt;
.NET RIA services is the killer app we’ve been waiting for as far as building RIA
apps is concerned.&amp;#160; it’s like Astoria, only better, and doesn’t require Entities
(long live LINQ to SQL!).&amp;#160; 
&lt;/li&gt;
&lt;li&gt;
Blend 3 will revolutionize the way designers and developers work together, and make
the design process much faster&lt;/li&gt;
&lt;li&gt;
Free martinis are both a blessing and a curse&lt;/li&gt;
&lt;li&gt;
Having a DJ at your keynotes is a fantastic idea&lt;/li&gt;
&lt;li&gt;
Not only would downtown Hillsboro (where I live) fit inside the Venetian, but you
probably wouldn’t actually notice it.&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,7d4b00dc-ce68-44f3-a493-9d7073d3bcdd.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=b705c37b-b47f-4e8d-8f8b-091efc4cb684</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,b705c37b-b47f-4e8d-8f8b-091efc4cb684.aspx</pingback:target>
      <dc:creator />
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,b705c37b-b47f-4e8d-8f8b-091efc4cb684.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=b705c37b-b47f-4e8d-8f8b-091efc4cb684</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
After <a href="Login.aspx">logging in</a>, be sure to visit all the options under <a href="EditConfig.aspx">Configuration</a> in
the Admin Menu Bar above. There are <a href="http://dasblog.info/ThemeScreenShots.aspx">26
themes to choose from</a>, and you can also <a href="http://dasblog.info/ThemesAndMacros.aspx">create
your own</a>.
</p>
        <p>
        </p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Congratulations, you've installed dasBlog with Web Deploy!</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,b705c37b-b47f-4e8d-8f8b-091efc4cb684.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/CongratulationsYouveInstalledDasBlogWithWebDeploy.aspx</link>
      <pubDate>Wed, 11 Mar 2009 07:00:00 GMT</pubDate>
      <description>
		&lt;p&gt;
After &lt;a href="Login.aspx"&gt;logging in&lt;/a&gt;, be sure to visit all the options under &lt;a href="EditConfig.aspx"&gt;Configuration&lt;/a&gt; in
the Admin Menu Bar above. There are &lt;a href="http://dasblog.info/ThemeScreenShots.aspx"&gt;26
themes to choose from&lt;/a&gt;, and you can also &lt;a href="http://dasblog.info/ThemesAndMacros.aspx"&gt;create
your own&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,b705c37b-b47f-4e8d-8f8b-091efc4cb684.aspx</comments>
      <category>dasBlog</category>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=1b71604e-3348-423e-a127-8808e61db198</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,1b71604e-3348-423e-a127-8808e61db198.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,1b71604e-3348-423e-a127-8808e61db198.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=1b71604e-3348-423e-a127-8808e61db198</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I’m building a MVVM app in WPF, and needed to show a modal dialog, but I couldn’t
figure out how to make it work and still maintain the separation between ViewModels
and Views.  I have been mapping Views to ViewModels using DataTemplates, so that
the relationship is declarative in XAML rather than in code someplace.  What
I ended up with was a new Window called Dialog that takes a type in its constructor
that corresponds to a ViewModelBase-derived type.  (See <a href="http://joshsmithonwpf.wordpress.com/">Josh
Smith’s</a><a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">WPF Apps
With The Model-View-ViewModel Design Pattern</a> article for background on how the
pieces fit together…)  
</p>
        <pre class="brush: csharp">public partial class Dialog : Window
{
    public Dialog(Type vmType)
    {
        InitializeComponent();

        ViewModelBase vmb = Activator.CreateInstance(vmType) as ViewModelBase;
        
        item.Content = vmb;

        this.Title = vmb.DisplayName;
    }
}</pre>
        <p>
In the XAML for Dialog, there’s just a Grid that contains a ContentPresenter called
“item”.  The constructor sets item’s content to be the ViewModel, and the DataTemplate
takes care of associating the View (a UserControl) with the ViewModel.  Note
the use of <code>SizeToContent="WidthAndHeight"</code> on the Dialog window, which
causes the window to resize to how ever big the UserControl that represents the View
might be.
</p>
        <pre class="brush: xml">&lt;Window x:Class="SomeNamespace.Dialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Dialog" SizeToContent="WidthAndHeight"&gt;
    &lt;Grid&gt;
        &lt;ContentPresenter x:Name="item"&gt;
            
        &lt;/ContentPresenter&gt;
    &lt;/Grid&gt;
&lt;/Window&gt;</pre>
        <pre class="brush: xml">&lt;DataTemplate DataType="{x:Type vm:NewThingViewModel}"&gt;
    &lt;vw:NewThing/&gt;
&lt;/DataTemplate&gt;</pre>
        <p>
To create an instance of the new modal dialog, I just create a new instance of Dialog
and pass the type of ViewModel it’s supposed to host…
</p>
        <pre class="brush: csharp">new Dialog(typeof(NewThingViewModel)).ShowDialog();</pre>
        <p>
There are still some details to work out as far as getting results from said dialog,
but hey, progress…
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>MVVM and a modal dialog</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,1b71604e-3348-423e-a127-8808e61db198.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/MVVMAndAModalDialog.aspx</link>
      <pubDate>Tue, 10 Mar 2009 23:36:01 GMT</pubDate>
      <description>&lt;p&gt;
I’m building a MVVM app in WPF, and needed to show a modal dialog, but I couldn’t
figure out how to make it work and still maintain the separation between ViewModels
and Views.&amp;nbsp; I have been mapping Views to ViewModels using DataTemplates, so that
the relationship is declarative in XAML rather than in code someplace.&amp;nbsp; What
I ended up with was a new Window called Dialog that takes a type in its constructor
that corresponds to a ViewModelBase-derived type.&amp;nbsp; (See &lt;a href="http://joshsmithonwpf.wordpress.com/"&gt;Josh
Smith’s&lt;/a&gt; &lt;a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx"&gt;WPF Apps
With The Model-View-ViewModel Design Pattern&lt;/a&gt; article for background on how the
pieces fit together…)&amp;nbsp; 
&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;public partial class Dialog : Window
{
    public Dialog(Type vmType)
    {
        InitializeComponent();

        ViewModelBase vmb = Activator.CreateInstance(vmType) as ViewModelBase;
        
        item.Content = vmb;

        this.Title = vmb.DisplayName;
    }
}&lt;/pre&gt;
&lt;p&gt;
In the XAML for Dialog, there’s just a Grid that contains a ContentPresenter called
“item”.&amp;nbsp; The constructor sets item’s content to be the ViewModel, and the DataTemplate
takes care of associating the View (a UserControl) with the ViewModel.&amp;nbsp; Note
the use of &lt;code&gt;SizeToContent="WidthAndHeight"&lt;/code&gt; on the Dialog window, which
causes the window to resize to how ever big the UserControl that represents the View
might be.
&lt;/p&gt;
&lt;pre class="brush: xml"&gt;&amp;lt;Window x:Class="SomeNamespace.Dialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Dialog" SizeToContent="WidthAndHeight"&amp;gt;
    &amp;lt;Grid&amp;gt;
        &amp;lt;ContentPresenter x:Name="item"&amp;gt;
            
        &amp;lt;/ContentPresenter&amp;gt;
    &amp;lt;/Grid&amp;gt;
&amp;lt;/Window&amp;gt;&lt;/pre&gt;
&lt;pre class="brush: xml"&gt;&amp;lt;DataTemplate DataType="{x:Type vm:NewThingViewModel}"&amp;gt;
    &amp;lt;vw:NewThing/&amp;gt;
&amp;lt;/DataTemplate&amp;gt;&lt;/pre&gt;
&lt;p&gt;
To create an instance of the new modal dialog, I just create a new instance of Dialog
and pass the type of ViewModel it’s supposed to host…
&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;new Dialog(typeof(NewThingViewModel)).ShowDialog();&lt;/pre&gt;
&lt;p&gt;
There are still some details to work out as far as getting results from said dialog,
but hey, progress…
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,1b71604e-3348-423e-a127-8808e61db198.aspx</comments>
      <category>Work</category>
      <category>Design Patterns</category>
      <category>WPF</category>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=b1aa6fe5-fa05-4171-b565-25a4062e31f6</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,b1aa6fe5-fa05-4171-b565-25a4062e31f6.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,b1aa6fe5-fa05-4171-b565-25a4062e31f6.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=b1aa6fe5-fa05-4171-b565-25a4062e31f6</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
So yesterday I was reading <a href="http://joshsmithonwpf.wordpress.com/">Josh Smith’s</a><a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">WPF
Apps With The Model-View-ViewModel Design Pattern</a> article in last month’s MSDN
magazine, and I really liked the sample app that he built.  It totally cleared
up for me some rough edges (in my understanding) of MVVM.  Most specifically,
I had been conflicted about where to put things like button click handlers. 
Do you put a Click event handler in your codebehind, which just defers to the View
Model?  Do you create a generic CommandBinding handler to wire up commands to
your View Model’s methods?  (I’ve seen both in various examples…)  The former
seems like cheating a bit on MVVM (no code behind would be ideal, it seems to me)
and the latter overly complicated.  Josh’s solution is to bind the Command property
of the UIElement (button, menu item, whatever) to a property of type ICommand on the
View Model.  
</p>
        <p>
That totally made sense to me.  No more code behind (like at all, basically)
and I don’t have to build additional framework to make it happen, with the exception
of coming up with an ICommand implementation.  Josh solved that with a class
he calls RelayCommand, which just wraps an ICommand implementation around a delegate
(or lambda) of type Action&lt;object&gt;, with an optional Predicate&lt;object&gt;
to handle the CanExecute method of ICommand.  
</p>
        <p>
Groovy, now my XAML knows absolutely nothing about the View Model, and it’s only links
to said View Model are through data binding. 
</p>
        <p>
Then I got to wondering if something as easy could work in Silverlight…  The
answer turned out to be almost, but not quite.  Since Silverlight controls don’t
expose a Command property, you have to hook them up yourself, but otherwise it works
just the same way.
</p>
        <p>
So if I’ve got a page with a single button on it
</p>
        <p>
          <a href="http://www.cauldwell.net/patrick/blog/images/MVVMbindingtoCommandsinSilverlight_E1BC/CropperCapture10.png">
            <img style="border-width: 0px; display: inline;" title="CropperCapture[10]" alt="CropperCapture[10]" src="http://www.cauldwell.net/patrick/blog/images/MVVMbindingtoCommandsinSilverlight_E1BC/CropperCapture10_thumb.png" border="0" width="244" height="186" />
          </a>
        </p>
        <pre class="brush: xml">&lt;UserControl x:Class="SilverlightCommands.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:my="clr-namespace:SilverlightCommands"
    Width="400" Height="300"&gt;
    &lt;Grid x:Name="LayoutRoot" Background="White"&gt;
        &lt;Button Content="Say Hello..." VerticalAlignment="Center" 
                HorizontalAlignment="Center" 
                my:ButtonService.Command="{Binding Path=SayHello}"/&gt;
    &lt;/Grid&gt;
&lt;/UserControl&gt;</pre>
        <p>
I can add an attached property whose value is bound to the ICommand property on the
View Model.  The attached property grabs the ICommand and hooks up the button’s
click handler to the ICommand’s Execute method.
</p>
        <pre class="brush: csharp">#region Command

/// &lt;summary&gt;
/// Command Attached Dependency Property
/// &lt;/summary&gt;
public static readonly DependencyProperty CommandProperty =
    DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(ButtonService),
        new PropertyMetadata(OnCommandChanged));

/// &lt;summary&gt;
/// Gets the Command property.
/// &lt;/summary&gt;
public static ICommand GetCommand(DependencyObject d)
{
    return (ICommand)d.GetValue(CommandProperty);
}

/// &lt;summary&gt;
/// Sets the Command property.
/// &lt;/summary&gt;
public static void SetCommand(DependencyObject d, ICommand value)
{
    d.SetValue(CommandProperty, value);
}

/// &lt;summary&gt;
/// Handles changes to the Command property.
/// &lt;/summary&gt;
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is Button)
    {
        Button b = d as Button;
        ICommand c = e.NewValue as ICommand;
        b.Click += delegate(object sender, RoutedEventArgs arg) { c.Execute(null); };
    }
}

#endregion</pre>
        <p>
In the View Model, then, is the actual handler for the command
</p>
        <pre class="brush: csharp">public class PageViewModel
{
    public ICommand SayHello
    {
        get
        {
            return new RelayCommand(param =&gt; MessageBox.Show("HelloWorld"));
        }
    }
}</pre>
        <p>
Note that I’m using Josh’s RelayCommand helper to wrap the simple lambda.
</p>
        <p>
That feels like not too terribly much infrastructure, although I might have to create
separate attached properties to handle different control types (e.g. those that don’t
have a Click event).  It would be pretty straightforward to support command parameters
in the same way, by creating a CommandParameter attached property and picking up its
value in the OnCommandChanged handler…
</p>
        <pre class="brush: csharp">private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is Button)
    {
        string parameter = d.GetValue(CommandParameterProperty) as string;
        Button b = d as Button;
        ICommand c = e.NewValue as ICommand;
        b.Click += delegate(object sender, RoutedEventArgs arg) { c.Execute(parameter); };
    }
}</pre>
        <p>
The only thing that doesn’t really handle well is the CanExecute method, which in
WPF would automatically enable/disable the button based on the result of the ICommand’s
CanExecute method.  I tried a couple ways of wiring it up during the OnCommandChanged
handler, but couldn’t come up with anything that didn’t look to have nasty side-effect
(garbage collection, etc.) or be just ugly.  I’d probably just bind the IsEnable
property of the button to a separate boolean on the View Model and deal with it there.  
</p>
        <p>
          <strong>Update:</strong>
        </p>
        <p>
Code is <a href="http://www.cauldwell.net/patrick/work/SilverlightCommands.zip">here</a>.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>MVVM: binding to Commands in Silverlight</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,b1aa6fe5-fa05-4171-b565-25a4062e31f6.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/MVVMBindingToCommandsInSilverlight.aspx</link>
      <pubDate>Thu, 05 Mar 2009 00:06:59 GMT</pubDate>
      <description>&lt;p&gt;
So yesterday I was reading &lt;a href="http://joshsmithonwpf.wordpress.com/"&gt;Josh Smith’s&lt;/a&gt; &lt;a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx"&gt;WPF
Apps With The Model-View-ViewModel Design Pattern&lt;/a&gt; article in last month’s MSDN
magazine, and I really liked the sample app that he built.&amp;nbsp; It totally cleared
up for me some rough edges (in my understanding) of MVVM.&amp;nbsp; Most specifically,
I had been conflicted about where to put things like button click handlers.&amp;nbsp;
Do you put a Click event handler in your codebehind, which just defers to the View
Model?&amp;nbsp; Do you create a generic CommandBinding handler to wire up commands to
your View Model’s methods?&amp;nbsp; (I’ve seen both in various examples…)&amp;nbsp; The former
seems like cheating a bit on MVVM (no code behind would be ideal, it seems to me)
and the latter overly complicated.&amp;nbsp; Josh’s solution is to bind the Command property
of the UIElement (button, menu item, whatever) to a property of type ICommand on the
View Model.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
That totally made sense to me.&amp;nbsp; No more code behind (like at all, basically)
and I don’t have to build additional framework to make it happen, with the exception
of coming up with an ICommand implementation.&amp;nbsp; Josh solved that with a class
he calls RelayCommand, which just wraps an ICommand implementation around a delegate
(or lambda) of type Action&amp;lt;object&amp;gt;, with an optional Predicate&amp;lt;object&amp;gt;
to handle the CanExecute method of ICommand.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
Groovy, now my XAML knows absolutely nothing about the View Model, and it’s only links
to said View Model are through data binding. 
&lt;/p&gt;
&lt;p&gt;
Then I got to wondering if something as easy could work in Silverlight…&amp;nbsp; The
answer turned out to be almost, but not quite.&amp;nbsp; Since Silverlight controls don’t
expose a Command property, you have to hook them up yourself, but otherwise it works
just the same way.
&lt;/p&gt;
&lt;p&gt;
So if I’ve got a page with a single button on it
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.cauldwell.net/patrick/blog/images/MVVMbindingtoCommandsinSilverlight_E1BC/CropperCapture10.png"&gt;&lt;img style="border-width: 0px; display: inline;" title="CropperCapture[10]" alt="CropperCapture[10]" src="http://www.cauldwell.net/patrick/blog/images/MVVMbindingtoCommandsinSilverlight_E1BC/CropperCapture10_thumb.png" border="0" width="244" height="186"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;pre class="brush: xml"&gt;&amp;lt;UserControl x:Class="SilverlightCommands.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:my="clr-namespace:SilverlightCommands"
    Width="400" Height="300"&amp;gt;
    &amp;lt;Grid x:Name="LayoutRoot" Background="White"&amp;gt;
        &amp;lt;Button Content="Say Hello..." VerticalAlignment="Center" 
                HorizontalAlignment="Center" 
                my:ButtonService.Command="{Binding Path=SayHello}"/&amp;gt;
    &amp;lt;/Grid&amp;gt;
&amp;lt;/UserControl&amp;gt;&lt;/pre&gt;
&lt;p&gt;
I can add an attached property whose value is bound to the ICommand property on the
View Model.&amp;nbsp; The attached property grabs the ICommand and hooks up the button’s
click handler to the ICommand’s Execute method.
&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;#region Command

/// &amp;lt;summary&amp;gt;
/// Command Attached Dependency Property
/// &amp;lt;/summary&amp;gt;
public static readonly DependencyProperty CommandProperty =
    DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(ButtonService),
        new PropertyMetadata(OnCommandChanged));

/// &amp;lt;summary&amp;gt;
/// Gets the Command property.
/// &amp;lt;/summary&amp;gt;
public static ICommand GetCommand(DependencyObject d)
{
    return (ICommand)d.GetValue(CommandProperty);
}

/// &amp;lt;summary&amp;gt;
/// Sets the Command property.
/// &amp;lt;/summary&amp;gt;
public static void SetCommand(DependencyObject d, ICommand value)
{
    d.SetValue(CommandProperty, value);
}

/// &amp;lt;summary&amp;gt;
/// Handles changes to the Command property.
/// &amp;lt;/summary&amp;gt;
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is Button)
    {
        Button b = d as Button;
        ICommand c = e.NewValue as ICommand;
        b.Click += delegate(object sender, RoutedEventArgs arg) { c.Execute(null); };
    }
}

#endregion&lt;/pre&gt;
&lt;p&gt;
In the View Model, then, is the actual handler for the command
&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;public class PageViewModel
{
    public ICommand SayHello
    {
        get
        {
            return new RelayCommand(param =&amp;gt; MessageBox.Show("HelloWorld"));
        }
    }
}&lt;/pre&gt;
&lt;p&gt;
Note that I’m using Josh’s RelayCommand helper to wrap the simple lambda.
&lt;/p&gt;
&lt;p&gt;
That feels like not too terribly much infrastructure, although I might have to create
separate attached properties to handle different control types (e.g. those that don’t
have a Click event).&amp;nbsp; It would be pretty straightforward to support command parameters
in the same way, by creating a CommandParameter attached property and picking up its
value in the OnCommandChanged handler…
&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is Button)
    {
        string parameter = d.GetValue(CommandParameterProperty) as string;
        Button b = d as Button;
        ICommand c = e.NewValue as ICommand;
        b.Click += delegate(object sender, RoutedEventArgs arg) { c.Execute(parameter); };
    }
}&lt;/pre&gt;
&lt;p&gt;
The only thing that doesn’t really handle well is the CanExecute method, which in
WPF would automatically enable/disable the button based on the result of the ICommand’s
CanExecute method.&amp;nbsp; I tried a couple ways of wiring it up during the OnCommandChanged
handler, but couldn’t come up with anything that didn’t look to have nasty side-effect
(garbage collection, etc.) or be just ugly.&amp;nbsp; I’d probably just bind the IsEnable
property of the button to a separate boolean on the View Model and deal with it there.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Update:&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Code is &lt;a href="http://www.cauldwell.net/patrick/work/SilverlightCommands.zip"&gt;here&lt;/a&gt;.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,b1aa6fe5-fa05-4171-b565-25a4062e31f6.aspx</comments>
      <category>Design Patterns</category>
      <category>Silverlight</category>
      <category>Work</category>
    </item>
    <item>
      <trackback:ping>http://www.cauldwell.net/patrick/blog/Trackback.aspx?guid=2c0a4bfd-69ca-4e3a-8e6f-96abb31f954b</trackback:ping>
      <pingback:server>http://www.cauldwell.net/patrick/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.cauldwell.net/patrick/blog/PermaLink,guid,2c0a4bfd-69ca-4e3a-8e6f-96abb31f954b.aspx</pingback:target>
      <dc:creator>Patrick Cauldwell</dc:creator>
      <wfw:comment>http://www.cauldwell.net/patrick/blog/CommentView,guid,2c0a4bfd-69ca-4e3a-8e6f-96abb31f954b.aspx</wfw:comment>
      <wfw:commentRss>http://www.cauldwell.net/patrick/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=2c0a4bfd-69ca-4e3a-8e6f-96abb31f954b</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://blogs.sftsrc.com/shaun">Shaun</a> posted a nice concise <a href="http://blogs.sftsrc.com/shaun/archive/2009/02/23.aspx">example</a> of
replacing JavaScript code with similar compiled code in Silverlight.  If you
have any complex business logic currently written in JavaScript, this would be a great
way of turning that into compiled, type-safe C#.
</p>
        <br />
        <hr />
The posts on this weblog are provided AS IS with no warranties, and confer no rights.
The opinions expressed herein are my own personal opinions and do not represent my
employer's view in any way.</body>
      <title>Replacing JavaScript with Silverlight</title>
      <guid isPermaLink="false">http://www.cauldwell.net/patrick/blog/PermaLink,guid,2c0a4bfd-69ca-4e3a-8e6f-96abb31f954b.aspx</guid>
      <link>http://www.cauldwell.net/patrick/blog/ReplacingJavaScriptWithSilverlight.aspx</link>
      <pubDate>Mon, 02 Mar 2009 23:08:15 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://blogs.sftsrc.com/shaun"&gt;Shaun&lt;/a&gt; posted a nice concise &lt;a href="http://blogs.sftsrc.com/shaun/archive/2009/02/23.aspx"&gt;example&lt;/a&gt; of
replacing JavaScript code with similar compiled code in Silverlight.&amp;#160; If you
have any complex business logic currently written in JavaScript, this would be a great
way of turning that into compiled, type-safe C#.
&lt;/p&gt;
&lt;br /&gt;
&lt;hr /&gt;The posts on this weblog are provided AS IS with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.</description>
      <comments>http://www.cauldwell.net/patrick/blog/CommentView,guid,2c0a4bfd-69ca-4e3a-8e6f-96abb31f954b.aspx</comments>
    </item>
  </channel>
</rss>