<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>zdima.net &#187; Silverlight</title>
	<atom:link href="http://zdima.net/blog/archives/category/soft/dev/silverlight/feed" rel="self" type="application/rss+xml" />
	<link>http://zdima.net/blog</link>
	<description></description>
	<lastBuildDate>Fri, 18 May 2012 17:48:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Getting Started with the MVVM Pattern in Silverlight Applications</title>
		<link>http://zdima.net/blog/archives/10284</link>
		<comments>http://zdima.net/blog/archives/10284#comments</comments>
		<pubDate>Wed, 09 Dec 2009 07:30:06 +0000</pubDate>
		<dc:creator>dwahlin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[MVVM]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=10284</guid>
		<description><![CDATA[<p></p>  <p>With the increasing popularity of Silverlight as an application development framework the discussion of patterns has grown louder and louder. Fortunately the majority of developers building Silverlight applications have agreed on a pattern that fits well in the Silverlight world called Model-View-ViewModel (MVVM). The MVVM pattern allows applications to be divided up into separate layers that provide multiple benefits ranging from better code re-use to enhanced testing capabilities. This post will explain key concepts found in the MVVM pattern and attempt to present them in a way that is easy to understand. I’ll show some code along the way to demonstrate how the MVVM pattern can be used and provide a few alternatives when it comes to binding data. The code shown later in the post can be <a href="http://www.xmlforasp.net/CodeBank/Download/Blog/Silverlight3/ViewModelSample.zip">downloaded here</a>.</p>  <h3>Getting Started with the MVVM Pattern</h3>  <p>The MVVM pattern defines three key parts including the Model, the View and the ViewModel. The following image shows a slide from a Silverlight course <a href="http://www.thewahlingroup.com">we offer</a> that sums up the role of each part of the MVVM pattern in a concise way:    <br /></p>  <p><a href="http://weblogs.asp.net/blogs/dwahlin/clip_image002_5D087867.jpg"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="clip_image002" src="http://weblogs.asp.net/blogs/dwahlin/clip_image002_thumb_62E31C00.jpg" width="374" height="280"></a></p>  <p>   <br />Looking through the description of each part you can see that the Model represents the business domain which includes the model classes used (Customer, Order, etc.), data access code and business rules. In general you can think of the Model as representing the entities that live on the server as well as the objects that are responsible for interacting with the data store your application uses and filling entities with data. While some people feel that the Model represents only the model classes (classes like Customer, Order, etc.) used in the application I personally think of it more broadly and include data access code and business rules in the Model definition. Silverlight applications will call into the Model code through services written using WCF, ASMX, REST or even custom solutions.</p>  <p>The View in MVVM represents the Silverlight screens that you build. This includes the XAML files and the code-beside files that are responsible for showing data to end users. The View's responsibilities include displaying data and collecting data from end users. A given View isn't responsible for retrieving data, performing any business rules or validating data.</p>  <p>The ViewModel acts as the middle-man between the View and the Model. It&#39;s responsible for aggregating and storing data that will be bound to a View. For example, a ViewModel may contain a List&#60;State&#62; property and a List&#60;Person&#62; property that may be bound to two ComboBox controls in a View. The ViewModel will retrieve the values held by these two properties from the Model. By using a ViewModel the View doesn&#39;t have to worry about retrieving data and knows nothing about where data comes from. </p>  <p>Additional players may be added into the Model-View-ViewModel mix to help segregate code even further. For example, I normally create a service agent class that is responsible for making calls from Silverlight to remote services. The service agent is responsible for initiating the service call, capturing the data that's returned and forwarding the data back to the ViewModel. By doing this the ViewModel classes can delegate data gathering responsibilities to the service agent. A given service agent can also be re-used across multiple ViewModel classes as needed. The following image shows how the service agent can be integrated into the MVVM pattern:   <br /></p>  <p><a href="http://weblogs.asp.net/blogs/dwahlin/clip_image004_7A9A5366.jpg"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="clip_image004" src="http://weblogs.asp.net/blogs/dwahlin/clip_image004_thumb_12BDBDC2.jpg" width="393" height="298"></a></p>  <p> </p>  <p>When developers first start building Silverlight applications they typically add all of the code for the application into the XAML's code-beside file (MainPage.xaml.cs for example). Although this approach certainly works, by following the MVVM pattern you can take advantage of several inherent benefits including better code re-use, simplified maintenance, more modular code and enhanced testing support. I'll focus on the overall benefits achieved by building applications that are based on the MVVM pattern throughout the rest of this article.   <br /></p>  <h3>The Model</h3>  <p>There are many different ways that the Model can be created including using Microsoft&#39;s Entity Framework or LINQ to SQL technologies, nHibernate, PLINQO, SubSonic, custom solutions and more. The technology chosen is generally unique to a given company&#39;s development policies so I&#39;m not going to go into a discussion of the pros and cons of each technology here. What&#39;s important is that one or more classes used by a Silverlight application are &#34;modeled&#34; using tools or by writing code by hand. This involves defining all of the properties that each class will expose. A simple example of a Model class is shown next:   <br /></p>  <pre><span style="color:blue">public class </span><span style="color:#2b91af">Person
</span>{
    <span style="color:blue">public string </span>FirstName { <span style="color:blue">get</span>;<span style="color:blue">set</span>;}
    <span style="color:blue">public string </span>LastName { <span style="color:blue">get</span>;<span style="color:blue">set</span>; }
    <span style="color:blue">public int </span>Age { <span style="color:blue">get</span>; <span style="color:blue">set</span>; }
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p> </p>

<p>Once the Model classes are in place they'll need to be populated with data from a data store which can be done by writing custom code or using ORM frameworks that handle mapping query results to object instances. Services will also need to be written to expose one or more of the Model classes used in a Silverlight application which can be done using WCF, ASMX or even custom REST services.
  <br /></p>

<h3>The View and ViewModel Classes</h3>

<p>Once the Model is ready to go the View and ViewModel classes can be created. As mentioned earlier, a View represents a Silverlight screen that end users interact with which includes the XAML file and the associated code-beside file. Rather than adding all of the code to call the Model and retrieve data directly into the View's code-beside file, the View will rely on a ViewModel class to retrieve data and then bind to the properties of the ViewModel.</p>

<p>ViewModel classes should implement an interface that's available in Silverlight called INotifyPropertyChanged which defines a single event named PropertyChanged. This event is used to notify different Silverlight bindings that data has changed for one or more properties so that controls can be updated automatically. Although INotifyPropertyChanged can be implemented directly on a ViewModel class, your application may have multiple ViewModel classes in it and writing the same code over and over tends to get old. Creating a base ViewModel class that handles implementing INotifyPropertyChanged is useful to minimize code and allow more re-use to occur in applications. The following code shows a class named ViewModelBase that implements the INotifyPropertyChanged interface. The class also provides an OnNotifyPropertyChanged method that can be used to raise the PropertyChanged event.
  <br /></p>

<pre><span style="color:blue">public class </span><span style="color:#2b91af">ViewModelBase </span>: <span style="color:#2b91af">INotifyPropertyChanged
</span>{
    <span style="color:blue">protected void </span>OnNotifyPropertyChanged(<span style="color:blue">string </span>p)
    {
        <span style="color:blue">if </span>(PropertyChanged != <span style="color:blue">null</span>)
        {
            PropertyChanged(<span style="color:blue">this</span>, <span style="color:blue">new </span><span style="color:#2b91af">PropertyChangedEventArgs</span>(p));
        }
    }

    <span style="color:blue">public bool </span>IsDesignTime
    {
        <span style="color:blue">get
        </span>{
            <span style="color:blue">return </span>(<span style="color:#2b91af">Application</span>.Current == <span style="color:blue">null</span>) &#124;&#124; (<span style="color:#2b91af">Application</span>.Current.GetType() == <span style="color:blue">typeof</span>(<span style="color:#2b91af">Application</span>));
        }
    }

    <span style="color:blue">#region </span>INotifyPropertyChanged Members

    <span style="color:blue">public event </span><span style="color:#2b91af">PropertyChangedEventHandler </span>PropertyChanged;

    <span style="color:blue">#endregion
</span>}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p> </p>

<p>A ViewModel class can derive from ViewModelBase and automatically take advantage of the INotifyPropertyChanged interface. An example of a ViewModel class named PeopleViewModel that derives from the ViewModelBase class and defines several properties and methods is shown next:
  <br /></p>

<pre><span style="color:blue">public class </span><span style="color:#2b91af">PeopleViewModel </span>: <span style="color:#2b91af">ViewModelBase
</span>{
    <span style="color:#2b91af">IServiceAgent </span>_ServiceAgent;
    <span style="color:#2b91af">Person </span>_Person;
    <span style="color:#2b91af">ObservableCollection</span>&#60;<span style="color:#2b91af">Person</span>&#62; _People;

    <span style="color:blue">public </span>PeopleViewModel() : <span style="color:blue">this</span>(<span style="color:blue">new </span><span style="color:#2b91af">ServiceAgent</span>()) {}

    <span style="color:blue">public </span>PeopleViewModel(<span style="color:#2b91af">IServiceAgent </span>serviceAgent)
    {
        <span style="color:blue">if </span>(!IsDesignTime)
        {
            _ServiceAgent = serviceAgent;
            GetPeople();
        }
    }

    <span style="color:blue">#region </span>Properties

    <span style="color:blue">public </span><span style="color:#2b91af">Person </span>Person
    {
        <span style="color:blue">get
        </span>{
            <span style="color:blue">return </span>_Person;
        }
        <span style="color:blue">set
        </span>{
            <span style="color:blue">if </span>(_Person != <span style="color:blue">value</span>)
            {
                _Person = <span style="color:blue">value</span>;
                OnNotifyPropertyChanged(<span style="color:#a31515">&#34;Person&#34;</span>);
            }
        }
    }

    <span style="color:blue">public </span><span style="color:#2b91af">ObservableCollection</span>&#60;<span style="color:#2b91af">Person</span>&#62; People {
        <span style="color:blue">get
        </span>{
            <span style="color:blue">return </span>_People;
        }
        <span style="color:blue">set
        </span>{
            <span style="color:blue">if </span>(_People != <span style="color:blue">value</span>)
            {
                _People = <span style="color:blue">value</span>;
                OnNotifyPropertyChanged(<span style="color:#a31515">&#34;People&#34;</span>);
            }
        }

    }

    <span style="color:blue">#endregion        
    
    public void </span>GetPeople()
    {
        _ServiceAgent.GetPeople((s,e) =&#62; <span style="color:blue">this</span>.People = e.Result);
    }

    <span style="color:blue">public void </span>UpdatePerson()
    {
        _ServiceAgent.UpdatePerson(<span style="color:blue">this</span>.Person, (s, e) =&#62;
        {
            <span style="color:#2b91af">PeopleEventBus</span>.OnOperationCompleted(<span style="color:blue">this</span>, <span style="color:blue">new </span><span style="color:#2b91af">OperationCompletedEventArgs </span>{ OperationStatus = e.Result });
        });
    }
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p>
  <br />Looking through the code you&#39;ll see that PeopleViewModel defines two fields, two properties and two methods. Each property raises the PropertyChanged event as the set block is called by calling the OnNotifyPropertyChanged method defined in ViewModelBase. This notifies any controls bound to the properties that the values have changed which allows them to update the data they display automatically.  </p>

<p>Looking at the first constructor in PeopleViewModel you'll see that it forwards the call to a secondary constructor that accepts a parameter of type IServiceAgent. Why have two constructors? This approach allows testing frameworks to pass in different types of service agents to the ViewModel when running tests. When the ViewModel is called at runtime the parameterless constructor will be called and an instance of a ServiceAgent class (shown next) will be passed as the IServiceAgent parameter. From there, once the service agent object is passed into the ViewModel's constructor a call to a method named GetPeople is made which invokes a method on the service agent and passes a callback delegate. The WCF service is then called by the service agent and the results are assigned to the People property. </p>

<p> </p>

<pre><span style="color:blue">public interface </span><span style="color:#2b91af">IServiceAgent
</span>{
    <span style="color:blue">void </span>GetPeople(<span style="color:#2b91af">EventHandler</span>&#60;<span style="color:#2b91af">GetPeopleCompletedEventArgs</span>&#62; callback);
    <span style="color:blue">void </span>UpdatePerson(<span style="color:#2b91af">Person </span>p, <span style="color:#2b91af">EventHandler</span>&#60;<span style="color:#2b91af">UpdatePersonCompletedEventArgs</span>&#62; callback);
}

<span style="color:blue">public class </span><span style="color:#2b91af">ServiceAgent </span>: <span style="color:#2b91af">IServiceAgent
</span>{
    <span style="color:blue">public void </span>GetPeople(<span style="color:#2b91af">EventHandler</span>&#60;<span style="color:#2b91af">GetPeopleCompletedEventArgs</span>&#62; callback)
    {
        <span style="color:#2b91af">PeopleServiceClient </span>proxy = <span style="color:blue">new </span><span style="color:#2b91af">PeopleServiceClient</span>();
        proxy.GetPeopleCompleted += callback;
        proxy.GetPeopleAsync();
    }

    <span style="color:blue">public void </span>UpdatePerson(<span style="color:#2b91af">Person </span>p, <span style="color:#2b91af">EventHandler</span>&#60;<span style="color:#2b91af">UpdatePersonCompletedEventArgs</span>&#62; callback)
    {
        <span style="color:#2b91af">PeopleServiceClient </span>proxy = <span style="color:blue">new </span><span style="color:#2b91af">PeopleServiceClient</span>();
        proxy.UpdatePersonCompleted += callback;
        proxy.UpdatePersonAsync(p);
    }
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p> </p>

<h3><strong>Binding a ViewModel to a View</strong></h3>

<p>Now that the ViewModel class is defined it can be bound to a View. This can be done declaratively in XAML or imperatively through code in the View's code-beside file. Imperative (or code-based) binding is typically accomplished by assigning a ViewModel instance to the layout root's DataContext property as shown next:
  <br /></p>

<p><font face="Courier New">this.LayoutRoot.DataContext = new PeopleViewModel();
    <br /></font></p>

<p>An example of declaratively binding a ViewModel (which is my personal preference) to a View is shown next:
  <br /></p>

<pre><span style="color:blue">&#60;</span><span style="color:#a31515">UserControl </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Class</span><span style="color:blue">=&#34;ViewModelExample.MainPage&#34;
    </span><span style="color:red">xmlns</span><span style="color:blue">=&#34;http://schemas.microsoft.com/winfx/2006/xaml/presentation&#34; 
    </span><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">x</span><span style="color:blue">=&#34;http://schemas.microsoft.com/winfx/2006/xaml&#34;
    </span><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">d</span><span style="color:blue">=&#34;http://schemas.microsoft.com/expression/blend/2008&#34; </span><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">mc</span><span style="color:blue">=&#34;http://schemas.openxmlformats.org/markup-compatibility/2006&#34; 
    </span><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">converter</span><span style="color:blue">=&#34;clr-namespace:ViewModelExample&#34;
    </span><strong><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">viewModel</span></strong><span style="color:blue"><strong>=&#34;clr-namespace:ViewModelExample.ViewModel&#34;</strong>
    </span><span style="color:red">mc</span><span style="color:blue">:</span><span style="color:red">Ignorable</span><span style="color:blue">=&#34;d&#34; </span><span style="color:red">d</span><span style="color:blue">:</span><span style="color:red">DesignWidth</span><span style="color:blue">=&#34;640&#34; </span><span style="color:red">d</span><span style="color:blue">:</span><span style="color:red">DesignHeight</span><span style="color:blue">=&#34;480&#34;&#62;
    &#60;</span><span style="color:#a31515">UserControl.Resources</span><span style="color:blue">&#62;
        <strong>&#60;</strong></span><strong><span style="color:#a31515">viewModel</span><span style="color:blue">:</span><span style="color:#a31515">PeopleViewModel </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Key</span></strong><span style="color:blue"><strong>=&#34;ViewModel&#34; /&#62;</strong>
    &#60;/</span><span style="color:#a31515">UserControl.Resources</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Grid </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Name</span><span style="color:blue">=&#34;LayoutRoot&#34; </span><strong><span style="color:red">DataContext</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">Source</span><span style="color:blue">={</span><span style="color:#a31515">StaticResource </span><span style="color:red">ViewModel</span></strong><span style="color:blue"><strong>}}&#34;</strong>&#62;
</span><span style="color:blue">    &#60;/</span><span style="color:#a31515">Grid</span><span style="color:blue">&#62;
&#60;/</span><span style="color:#a31515">UserControl</span><span style="color:blue">&#62;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p> </p>

<p>The ViewModel namespace is first referenced using an XML namespace prefix of &#34;viewModel&#34;. The ViewModel is then defined in the UserControl&#39;s Resources section and given a key of &#34;ViewModel&#34; (note that any name can be chosen for the key). The key is important since it&#39;s used to hook the ViewModel to the DataContext of the layout root using the {Binding Source={StaticResource ViewModel}} syntax. The declarative binding will cause a new PeopleViewModel instance to be created at runtime which is then bound to the layout root&#39;s DataContext. Child controls of the layout root can then bind to properties on the ViewModel. An example of binding a ListBox to the ViewModel&#39;s People property and a StackPanel to the Person property is shown next:
  <br /></p>

<pre><span style="color:blue">&#60;</span><span style="color:#a31515">StackPanel </span><span style="color:red">Margin</span><span style="color:blue">=&#34;20&#34;&#62;
    &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Text</span><span style="color:blue">=&#34;Binding Controls to a ViewModel&#34; </span><span style="color:red">Margin</span><span style="color:blue">=&#34;20,0,0,0&#34; </span><span style="color:red">FontWeight</span><span style="color:blue">=&#34;Bold&#34; </span><span style="color:red">FontSize</span><span style="color:blue">=&#34;12&#34; /&#62;
        &#60;</span><span style="color:#a31515">ListBox </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Name</span><span style="color:blue">=&#34;lbPeople&#34; </span><span style="color:red">Margin</span><span style="color:blue">=&#34;0,10,0,0&#34; </span><span style="color:red">Height</span><span style="color:blue">=&#34;250&#34; </span><span style="color:red">Width</span><span style="color:blue">=&#34;300&#34; </span><span style="color:red">HorizontalAlignment</span><span style="color:blue">=&#34;Left&#34;
                 </span><strong><span style="color:red">ItemsSource</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">People</span></strong><span style="color:blue"><strong>}&#34;</strong> </span><span style="color:red">ScrollViewer.HorizontalScrollBarVisibility</span><span style="color:blue">=&#34;Hidden&#34;
                 </span><strong><span style="color:red">SelectedItem</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">Person</span><span style="color:blue">, </span><span style="color:red">Mode</span></strong><span style="color:blue"><strong>=TwoWay}&#34;</strong>&#62;
            &#60;</span><span style="color:#a31515">ListBox.ItemTemplate</span><span style="color:blue">&#62;
                &#60;</span><span style="color:#a31515">DataTemplate</span><span style="color:blue">&#62;
                    &#60;</span><span style="color:#a31515">Grid</span><span style="color:blue">&#62;
                        &#60;</span><span style="color:#a31515">Grid.ColumnDefinitions</span><span style="color:blue">&#62;
                            &#60;</span><span style="color:#a31515">ColumnDefinition </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; /&#62;
                            &#60;</span><span style="color:#a31515">ColumnDefinition </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; /&#62;
                            &#60;</span><span style="color:#a31515">ColumnDefinition </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; /&#62;
                        &#60;/</span><span style="color:#a31515">Grid.ColumnDefinitions</span><span style="color:blue">&#62;
                        &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Grid.Column</span><span style="color:blue">=&#34;0&#34; </span><span style="color:red">Margin</span><span style="color:blue">=&#34;10&#34; </span><span style="color:red">Text</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">FirstName</span><span style="color:blue">}&#34; /&#62;
                        &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Grid.Column</span><span style="color:blue">=&#34;1&#34; </span><span style="color:red">Margin</span><span style="color:blue">=&#34;10&#34; </span><span style="color:red">Text</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">LastName</span><span style="color:blue">}&#34; /&#62;
                        &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Grid.Column</span><span style="color:blue">=&#34;2&#34; </span><span style="color:red">Margin</span><span style="color:blue">=&#34;10&#34; </span><span style="color:red">Text</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">Age</span><span style="color:blue">}&#34; /&#62;
                    &#60;/</span><span style="color:#a31515">Grid</span><span style="color:blue">&#62;
                &#60;/</span><span style="color:#a31515">DataTemplate</span><span style="color:blue">&#62;
            &#60;/</span><span style="color:#a31515">ListBox.ItemTemplate</span><span style="color:blue">&#62;
        &#60;/</span><span style="color:#a31515">ListBox</span><span style="color:blue">&#62;
        &#60;</span><span style="color:#a31515">StackPanel </span><strong><span style="color:red">DataContext</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">Person</span></strong><span style="color:blue"><strong>}&#34;</strong>&#62;
            &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Text</span><span style="color:blue">=&#34;First Name&#34; </span><span style="color:red">Margin</span><span style="color:blue">=&#34;0,10,0,0&#34; /&#62;
            &#60;</span><span style="color:#a31515">TextBox </span><span style="color:red">Text</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">FirstName</span><span style="color:blue">,</span><span style="color:red">Mode</span><span style="color:blue">=TwoWay}&#34; </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; </span><span style="color:red">Height</span><span style="color:blue">=&#34;25&#34; </span><span style="color:red">HorizontalAlignment</span><span style="color:blue">=&#34;Left&#34;/&#62;
            &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Text</span><span style="color:blue">=&#34;Last Name&#34; /&#62;
            &#60;</span><span style="color:#a31515">TextBox </span><span style="color:red">Text</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">LastName</span><span style="color:blue">,</span><span style="color:red">Mode</span><span style="color:blue">=TwoWay}&#34; </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; </span><span style="color:red">Height</span><span style="color:blue">=&#34;25&#34; </span><span style="color:red">HorizontalAlignment</span><span style="color:blue">=&#34;Left&#34;/&#62;
            &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Text</span><span style="color:blue">=&#34;Age&#34; /&#62;
            &#60;</span><span style="color:#a31515">TextBox </span><span style="color:red">Text</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">Age</span><span style="color:blue">,</span><span style="color:red">Mode</span><span style="color:blue">=TwoWay}&#34; </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; </span><span style="color:red">Height</span><span style="color:blue">=&#34;25&#34; </span><span style="color:red">HorizontalAlignment</span><span style="color:blue">=&#34;Left&#34;/&#62;
        &#60;/</span><span style="color:#a31515">StackPanel</span><span style="color:blue">&#62;
        &#60;</span><span style="color:#a31515">Button </span><span style="color:red">Margin</span><span style="color:blue">=&#34;0,10,0,0&#34; </span><span style="color:red">Click</span><span style="color:blue">=&#34;Button_Click&#34; </span><span style="color:red">Content</span><span style="color:blue">=&#34;Submit&#34; </span><span style="color:red">Height</span><span style="color:blue">=&#34;20&#34; </span><span style="color:red">Width</span><span style="color:blue">=&#34;100&#34; </span><span style="color:red">HorizontalAlignment</span><span style="color:blue">=&#34;Left&#34; /&#62;
&#60;/</span><span style="color:#a31515">StackPanel</span><span style="color:blue">&#62;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p> </p>

<p>The MVVM pattern provides a flexible way to work with data that encourages code re-use and simplifies maintenance. There's much more that can be discussed with regard to the MVVM pattern in Silverlight such as event buses, commanding and dependency injection but I hope this post helps jumpstart the process of architecting and developing Silverlight applications. If you have specific Silverlight development concepts you'd like to see covered in future posts tweet me at <a href="http://www.twitter.com/danwahlin">@DanWahlin</a> or add a comment below.</p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7274398" width="1" height="1"><p class="read-more"><a href="http://zdima.net/blog/archives/10284">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[</p>
<p>With the increasing popularity of Silverlight as an application development framework the discussion of patterns has grown louder and louder. Fortunately the majority of developers building Silverlight applications have agreed on a pattern that fits well in the Silverlight world called Model-View-ViewModel (MVVM). The MVVM pattern allows applications to be divided up into separate layers that provide multiple benefits ranging from better code re-use to enhanced testing capabilities. This post will explain key concepts found in the MVVM pattern and attempt to present them in a way that is easy to understand. I’ll show some code along the way to demonstrate how the MVVM pattern can be used and provide a few alternatives when it comes to binding data. The code shown later in the post can be <a href="http://www.xmlforasp.net/CodeBank/Download/Blog/Silverlight3/ViewModelSample.zip">downloaded here</a>.</p>
<h3>Getting Started with the MVVM Pattern</h3>
<p>The MVVM pattern defines three key parts including the Model, the View and the ViewModel. The following image shows a slide from a Silverlight course <a href="http://www.thewahlingroup.com">we offer</a> that sums up the role of each part of the MVVM pattern in a concise way:    </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/clip_image002_5D087867.jpg"><img  title="clip_image002" border="0" alt="clip_image002" src="http://weblogs.asp.net/blogs/dwahlin/clip_image002_thumb_62E31C00.jpg" width="374" height="280"></a></p>
<p>Looking through the description of each part you can see that the Model represents the business domain which includes the model classes used (Customer, Order, etc.), data access code and business rules. In general you can think of the Model as representing the entities that live on the server as well as the objects that are responsible for interacting with the data store your application uses and filling entities with data. While some people feel that the Model represents only the model classes (classes like Customer, Order, etc.) used in the application I personally think of it more broadly and include data access code and business rules in the Model definition. Silverlight applications will call into the Model code through services written using WCF, ASMX, REST or even custom solutions.</p>
<p>The View in MVVM represents the Silverlight screens that you build. This includes the XAML files and the code-beside files that are responsible for showing data to end users. The View&#8217;s responsibilities include displaying data and collecting data from end users. A given View isn&#8217;t responsible for retrieving data, performing any business rules or validating data.</p>
<p>The ViewModel acts as the middle-man between the View and the Model. It&#39;s responsible for aggregating and storing data that will be bound to a View. For example, a ViewModel may contain a List&lt;State&gt; property and a List&lt;Person&gt; property that may be bound to two ComboBox controls in a View. The ViewModel will retrieve the values held by these two properties from the Model. By using a ViewModel the View doesn&#39;t have to worry about retrieving data and knows nothing about where data comes from. </p>
<p>Additional players may be added into the Model-View-ViewModel mix to help segregate code even further. For example, I normally create a service agent class that is responsible for making calls from Silverlight to remote services. The service agent is responsible for initiating the service call, capturing the data that&#8217;s returned and forwarding the data back to the ViewModel. By doing this the ViewModel classes can delegate data gathering responsibilities to the service agent. A given service agent can also be re-used across multiple ViewModel classes as needed. The following image shows how the service agent can be integrated into the MVVM pattern:   </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/clip_image004_7A9A5366.jpg"><img  title="clip_image004" border="0" alt="clip_image004" src="http://weblogs.asp.net/blogs/dwahlin/clip_image004_thumb_12BDBDC2.jpg" width="393" height="298"></a></p>
<p> </p>
<p>When developers first start building Silverlight applications they typically add all of the code for the application into the XAML&#8217;s code-beside file (MainPage.xaml.cs for example). Although this approach certainly works, by following the MVVM pattern you can take advantage of several inherent benefits including better code re-use, simplified maintenance, more modular code and enhanced testing support. I&#8217;ll focus on the overall benefits achieved by building applications that are based on the MVVM pattern throughout the rest of this article.   </p>
<h3>The Model</h3>
<p>There are many different ways that the Model can be created including using Microsoft&#39;s Entity Framework or LINQ to SQL technologies, nHibernate, PLINQO, SubSonic, custom solutions and more. The technology chosen is generally unique to a given company&#39;s development policies so I&#39;m not going to go into a discussion of the pros and cons of each technology here. What&#39;s important is that one or more classes used by a Silverlight application are &quot;modeled&quot; using tools or by writing code by hand. This involves defining all of the properties that each class will expose. A simple example of a Model class is shown next:   </p>
<pre><span >public class </span><span >Person
</span>{
    <span >public string </span>FirstName { <span >get</span>;<span >set</span>;}
    <span >public string </span>LastName { <span >get</span>;<span >set</span>; }
    <span >public int </span>Age { <span >get</span>; <span >set</span>; }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<p>Once the Model classes are in place they&#8217;ll need to be populated with data from a data store which can be done by writing custom code or using ORM frameworks that handle mapping query results to object instances. Services will also need to be written to expose one or more of the Model classes used in a Silverlight application which can be done using WCF, ASMX or even custom REST services.<br />
  </p>
<h3>The View and ViewModel Classes</h3>
<p>Once the Model is ready to go the View and ViewModel classes can be created. As mentioned earlier, a View represents a Silverlight screen that end users interact with which includes the XAML file and the associated code-beside file. Rather than adding all of the code to call the Model and retrieve data directly into the View&#8217;s code-beside file, the View will rely on a ViewModel class to retrieve data and then bind to the properties of the ViewModel.</p>
<p>ViewModel classes should implement an interface that&#8217;s available in Silverlight called INotifyPropertyChanged which defines a single event named PropertyChanged. This event is used to notify different Silverlight bindings that data has changed for one or more properties so that controls can be updated automatically. Although INotifyPropertyChanged can be implemented directly on a ViewModel class, your application may have multiple ViewModel classes in it and writing the same code over and over tends to get old. Creating a base ViewModel class that handles implementing INotifyPropertyChanged is useful to minimize code and allow more re-use to occur in applications. The following code shows a class named ViewModelBase that implements the INotifyPropertyChanged interface. The class also provides an OnNotifyPropertyChanged method that can be used to raise the PropertyChanged event.<br />
  </p>
<pre><span >public class </span><span >ViewModelBase </span>: <span >INotifyPropertyChanged
</span>{
    <span >protected void </span>OnNotifyPropertyChanged(<span >string </span>p)
    {
        <span >if </span>(PropertyChanged != <span >null</span>)
        {
            PropertyChanged(<span >this</span>, <span >new </span><span >PropertyChangedEventArgs</span>(p));
        }
    }

    <span >public bool </span>IsDesignTime
    {
        <span >get
        </span>{
            <span >return </span>(<span >Application</span>.Current == <span >null</span>) || (<span >Application</span>.Current.GetType() == <span >typeof</span>(<span >Application</span>));
        }
    }

    <span >#region </span>INotifyPropertyChanged Members

    <span >public event </span><span >PropertyChangedEventHandler </span>PropertyChanged;

    <span >#endregion
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<p>A ViewModel class can derive from ViewModelBase and automatically take advantage of the INotifyPropertyChanged interface. An example of a ViewModel class named PeopleViewModel that derives from the ViewModelBase class and defines several properties and methods is shown next:<br />
  </p>
<pre><span >public class </span><span >PeopleViewModel </span>: <span >ViewModelBase
</span>{
    <span >IServiceAgent </span>_ServiceAgent;
    <span >Person </span>_Person;
    <span >ObservableCollection</span>&lt;<span >Person</span>&gt; _People;

    <span >public </span>PeopleViewModel() : <span >this</span>(<span >new </span><span >ServiceAgent</span>()) {}

    <span >public </span>PeopleViewModel(<span >IServiceAgent </span>serviceAgent)
    {
        <span >if </span>(!IsDesignTime)
        {
            _ServiceAgent = serviceAgent;
            GetPeople();
        }
    }

    <span >#region </span>Properties

    <span >public </span><span >Person </span>Person
    {
        <span >get
        </span>{
            <span >return </span>_Person;
        }
        <span >set
        </span>{
            <span >if </span>(_Person != <span >value</span>)
            {
                _Person = <span >value</span>;
                OnNotifyPropertyChanged(<span >&quot;Person&quot;</span>);
            }
        }
    }

    <span >public </span><span >ObservableCollection</span>&lt;<span >Person</span>&gt; People {
        <span >get
        </span>{
            <span >return </span>_People;
        }
        <span >set
        </span>{
            <span >if </span>(_People != <span >value</span>)
            {
                _People = <span >value</span>;
                OnNotifyPropertyChanged(<span >&quot;People&quot;</span>);
            }
        }

    }

    <span >#endregion        

    public void </span>GetPeople()
    {
        _ServiceAgent.GetPeople((s,e) =&gt; <span >this</span>.People = e.Result);
    }

    <span >public void </span>UpdatePerson()
    {
        _ServiceAgent.UpdatePerson(<span >this</span>.Person, (s, e) =&gt;
        {
            <span >PeopleEventBus</span>.OnOperationCompleted(<span >this</span>, <span >new </span><span >OperationCompletedEventArgs </span>{ OperationStatus = e.Result });
        });
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>
  <br />Looking through the code you&#39;ll see that PeopleViewModel defines two fields, two properties and two methods. Each property raises the PropertyChanged event as the set block is called by calling the OnNotifyPropertyChanged method defined in ViewModelBase. This notifies any controls bound to the properties that the values have changed which allows them to update the data they display automatically.  </p>
<p>Looking at the first constructor in PeopleViewModel you&#8217;ll see that it forwards the call to a secondary constructor that accepts a parameter of type IServiceAgent. Why have two constructors? This approach allows testing frameworks to pass in different types of service agents to the ViewModel when running tests. When the ViewModel is called at runtime the parameterless constructor will be called and an instance of a ServiceAgent class (shown next) will be passed as the IServiceAgent parameter. From there, once the service agent object is passed into the ViewModel&#8217;s constructor a call to a method named GetPeople is made which invokes a method on the service agent and passes a callback delegate. The WCF service is then called by the service agent and the results are assigned to the People property. </p>
<p> </p>
<pre><span >public interface </span><span >IServiceAgent
</span>{
    <span >void </span>GetPeople(<span >EventHandler</span>&lt;<span >GetPeopleCompletedEventArgs</span>&gt; callback);
    <span >void </span>UpdatePerson(<span >Person </span>p, <span >EventHandler</span>&lt;<span >UpdatePersonCompletedEventArgs</span>&gt; callback);
}

<span >public class </span><span >ServiceAgent </span>: <span >IServiceAgent
</span>{
    <span >public void </span>GetPeople(<span >EventHandler</span>&lt;<span >GetPeopleCompletedEventArgs</span>&gt; callback)
    {
        <span >PeopleServiceClient </span>proxy = <span >new </span><span >PeopleServiceClient</span>();
        proxy.GetPeopleCompleted += callback;
        proxy.GetPeopleAsync();
    }

    <span >public void </span>UpdatePerson(<span >Person </span>p, <span >EventHandler</span>&lt;<span >UpdatePersonCompletedEventArgs</span>&gt; callback)
    {
        <span >PeopleServiceClient </span>proxy = <span >new </span><span >PeopleServiceClient</span>();
        proxy.UpdatePersonCompleted += callback;
        proxy.UpdatePersonAsync(p);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<h3><strong>Binding a ViewModel to a View</strong></h3>
<p>Now that the ViewModel class is defined it can be bound to a View. This can be done declaratively in XAML or imperatively through code in the View&#8217;s code-beside file. Imperative (or code-based) binding is typically accomplished by assigning a ViewModel instance to the layout root&#8217;s DataContext property as shown next:<br />
  </p>
<p><font face="Courier New">this.LayoutRoot.DataContext = new PeopleViewModel();<br />
    <br /></font></p>
<p>An example of declaratively binding a ViewModel (which is my personal preference) to a View is shown next:<br />
  </p>
<pre><span >&lt;</span><span >UserControl </span><span >x</span><span >:</span><span >Class</span><span >=&quot;ViewModelExample.MainPage&quot;
    </span><span >xmlns</span><span >=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    </span><span >xmlns</span><span >:</span><span >x</span><span >=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    </span><span >xmlns</span><span >:</span><span >d</span><span >=&quot;http://schemas.microsoft.com/expression/blend/2008&quot; </span><span >xmlns</span><span >:</span><span >mc</span><span >=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    </span><span >xmlns</span><span >:</span><span >converter</span><span >=&quot;clr-namespace:ViewModelExample&quot;
    </span><strong><span >xmlns</span><span >:</span><span >viewModel</span></strong><span ><strong>=&quot;clr-namespace:ViewModelExample.ViewModel&quot;</strong>
    </span><span >mc</span><span >:</span><span >Ignorable</span><span >=&quot;d&quot; </span><span >d</span><span >:</span><span >DesignWidth</span><span >=&quot;640&quot; </span><span >d</span><span >:</span><span >DesignHeight</span><span >=&quot;480&quot;&gt;
    &lt;</span><span >UserControl.Resources</span><span >&gt;
        <strong>&lt;</strong></span><strong><span >viewModel</span><span >:</span><span >PeopleViewModel </span><span >x</span><span >:</span><span >Key</span></strong><span ><strong>=&quot;ViewModel&quot; /&gt;</strong>
    &lt;/</span><span >UserControl.Resources</span><span >&gt;
    &lt;</span><span >Grid </span><span >x</span><span >:</span><span >Name</span><span >=&quot;LayoutRoot&quot; </span><strong><span >DataContext</span><span >=&quot;{</span><span >Binding </span><span >Source</span><span >={</span><span >StaticResource </span><span >ViewModel</span></strong><span ><strong>}}&quot;</strong>&gt;
</span><span >    &lt;/</span><span >Grid</span><span >&gt;
&lt;/</span><span >UserControl</span><span >&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<p>The ViewModel namespace is first referenced using an XML namespace prefix of &quot;viewModel&quot;. The ViewModel is then defined in the UserControl&#39;s Resources section and given a key of &quot;ViewModel&quot; (note that any name can be chosen for the key). The key is important since it&#39;s used to hook the ViewModel to the DataContext of the layout root using the {Binding Source={StaticResource ViewModel}} syntax. The declarative binding will cause a new PeopleViewModel instance to be created at runtime which is then bound to the layout root&#39;s DataContext. Child controls of the layout root can then bind to properties on the ViewModel. An example of binding a ListBox to the ViewModel&#39;s People property and a StackPanel to the Person property is shown next:<br />
  </p>
<pre><span >&lt;</span><span >StackPanel </span><span >Margin</span><span >=&quot;20&quot;&gt;
    &lt;</span><span >TextBlock </span><span >Text</span><span >=&quot;Binding Controls to a ViewModel&quot; </span><span >Margin</span><span >=&quot;20,0,0,0&quot; </span><span >FontWeight</span><span >=&quot;Bold&quot; </span><span >FontSize</span><span >=&quot;12&quot; /&gt;
        &lt;</span><span >ListBox </span><span >x</span><span >:</span><span >Name</span><span >=&quot;lbPeople&quot; </span><span >Margin</span><span >=&quot;0,10,0,0&quot; </span><span >Height</span><span >=&quot;250&quot; </span><span >Width</span><span >=&quot;300&quot; </span><span >HorizontalAlignment</span><span >=&quot;Left&quot;
                 </span><strong><span >ItemsSource</span><span >=&quot;{</span><span >Binding </span><span >People</span></strong><span ><strong>}&quot;</strong> </span><span >ScrollViewer.HorizontalScrollBarVisibility</span><span >=&quot;Hidden&quot;
                 </span><strong><span >SelectedItem</span><span >=&quot;{</span><span >Binding </span><span >Person</span><span >, </span><span >Mode</span></strong><span ><strong>=TwoWay}&quot;</strong>&gt;
            &lt;</span><span >ListBox.ItemTemplate</span><span >&gt;
                &lt;</span><span >DataTemplate</span><span >&gt;
                    &lt;</span><span >Grid</span><span >&gt;
                        &lt;</span><span >Grid.ColumnDefinitions</span><span >&gt;
                            &lt;</span><span >ColumnDefinition </span><span >Width</span><span >=&quot;100&quot; /&gt;
                            &lt;</span><span >ColumnDefinition </span><span >Width</span><span >=&quot;100&quot; /&gt;
                            &lt;</span><span >ColumnDefinition </span><span >Width</span><span >=&quot;100&quot; /&gt;
                        &lt;/</span><span >Grid.ColumnDefinitions</span><span >&gt;
                        &lt;</span><span >TextBlock </span><span >Grid.Column</span><span >=&quot;0&quot; </span><span >Margin</span><span >=&quot;10&quot; </span><span >Text</span><span >=&quot;{</span><span >Binding </span><span >FirstName</span><span >}&quot; /&gt;
                        &lt;</span><span >TextBlock </span><span >Grid.Column</span><span >=&quot;1&quot; </span><span >Margin</span><span >=&quot;10&quot; </span><span >Text</span><span >=&quot;{</span><span >Binding </span><span >LastName</span><span >}&quot; /&gt;
                        &lt;</span><span >TextBlock </span><span >Grid.Column</span><span >=&quot;2&quot; </span><span >Margin</span><span >=&quot;10&quot; </span><span >Text</span><span >=&quot;{</span><span >Binding </span><span >Age</span><span >}&quot; /&gt;
                    &lt;/</span><span >Grid</span><span >&gt;
                &lt;/</span><span >DataTemplate</span><span >&gt;
            &lt;/</span><span >ListBox.ItemTemplate</span><span >&gt;
        &lt;/</span><span >ListBox</span><span >&gt;
        &lt;</span><span >StackPanel </span><strong><span >DataContext</span><span >=&quot;{</span><span >Binding </span><span >Person</span></strong><span ><strong>}&quot;</strong>&gt;
            &lt;</span><span >TextBlock </span><span >Text</span><span >=&quot;First Name&quot; </span><span >Margin</span><span >=&quot;0,10,0,0&quot; /&gt;
            &lt;</span><span >TextBox </span><span >Text</span><span >=&quot;{</span><span >Binding </span><span >FirstName</span><span >,</span><span >Mode</span><span >=TwoWay}&quot; </span><span >Width</span><span >=&quot;100&quot; </span><span >Height</span><span >=&quot;25&quot; </span><span >HorizontalAlignment</span><span >=&quot;Left&quot;/&gt;
            &lt;</span><span >TextBlock </span><span >Text</span><span >=&quot;Last Name&quot; /&gt;
            &lt;</span><span >TextBox </span><span >Text</span><span >=&quot;{</span><span >Binding </span><span >LastName</span><span >,</span><span >Mode</span><span >=TwoWay}&quot; </span><span >Width</span><span >=&quot;100&quot; </span><span >Height</span><span >=&quot;25&quot; </span><span >HorizontalAlignment</span><span >=&quot;Left&quot;/&gt;
            &lt;</span><span >TextBlock </span><span >Text</span><span >=&quot;Age&quot; /&gt;
            &lt;</span><span >TextBox </span><span >Text</span><span >=&quot;{</span><span >Binding </span><span >Age</span><span >,</span><span >Mode</span><span >=TwoWay}&quot; </span><span >Width</span><span >=&quot;100&quot; </span><span >Height</span><span >=&quot;25&quot; </span><span >HorizontalAlignment</span><span >=&quot;Left&quot;/&gt;
        &lt;/</span><span >StackPanel</span><span >&gt;
        &lt;</span><span >Button </span><span >Margin</span><span >=&quot;0,10,0,0&quot; </span><span >Click</span><span >=&quot;Button_Click&quot; </span><span >Content</span><span >=&quot;Submit&quot; </span><span >Height</span><span >=&quot;20&quot; </span><span >Width</span><span >=&quot;100&quot; </span><span >HorizontalAlignment</span><span >=&quot;Left&quot; /&gt;
&lt;/</span><span >StackPanel</span><span >&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<p>The MVVM pattern provides a flexible way to work with data that encourages code re-use and simplifies maintenance. There&#8217;s much more that can be discussed with regard to the MVVM pattern in Silverlight such as event buses, commanding and dependency injection but I hope this post helps jumpstart the process of architecting and developing Silverlight applications. If you have specific Silverlight development concepts you&#8217;d like to see covered in future posts tweet me at <a href="http://www.twitter.com/danwahlin">@DanWahlin</a> or add a comment below.</p>
<p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7274398" width="1" height="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/10284/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>BugCamSmash – Motion Detection with Silverlight 4 Beta</title>
		<link>http://zdima.net/blog/archives/11154</link>
		<comments>http://zdima.net/blog/archives/11154#comments</comments>
		<pubDate>Thu, 03 Dec 2009 18:07:02 +0000</pubDate>
		<dc:creator>Adam Kinney</dc:creator>
				<category><![CDATA[Contributors]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Client Technologies]]></category>
		<category><![CDATA[Labs]]></category>
		<category><![CDATA[Motion Detection]]></category>
		<category><![CDATA[WebCam]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=11154</guid>
		<description><![CDATA[At PDC09, we released Silverlight 4 Beta and announced one of the availability of, one of the most requested features, Web Cam Support.
 
Wanting to have fun with the new feature, I thought of a fun sample to create – smashing bugs with motion detect...<p class="read-more"><a href="http://zdima.net/blog/archives/11154">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<div>
<p>At PDC09, we released <a href="http://silverlight.net/getstarted/silverlight-4-beta/">Silverlight 4 Beta</a> and announced one of the availability of, one of the most requested features, Web Cam Support.</p>
<p ><a href="http://channel9.msdn.com/posts/AdamKinney/BugCamSmash-in-Action/"><img src="http://adamkinney.com/images/blog/bugcamsmash_video.jpg"></a> </p>
<p>Wanting to have fun with the new feature, I thought of a fun sample to create – smashing bugs with motion detection. First step was to get bugs to crawl across the screen. Next I added the WebCam with frame diff calculation, which was intensive so took advantage of the multiple thread support. And finally I added a little Mantis Boy avatar to visualize the smashing of the bugs.</p>
<p><a href="http://adamkinney.com/labs/bugcamsmash/source.zip"></a></p>
<p> Over the next few days I will post about how the code works and improvements made for performance. You can check out a video to see Mantis Boy in action, run the demo or download the source.</p>
<p> </p>
<ul>
<li><a href="http://channel9.msdn.com/posts/AdamKinney/BugCamSmash-in-Action/">Watch the video</a> </li>
<li><a href="http://adamkinney.com/labs/bugcamsmash/">Run the Demo</a>* </li>
<li><a href="http://adamkinney.com/labs/bugcamsmash/source.zip">Download the Source</a> </li>
<li><a href="http://channel9.msdn.com/learn/courses/Silverlight4/Overview/">Learn about more new features in Silverlight 4 Beta</a></li>
<li><a href="http://www.flickr.com/photos/adamkinney/sets/72157622927353336/">View a few Screenshots</a> </li>
</ul>
<p>Learn how it was written: </p>
<ul>
<li><a href="http://adamkinney.wordpress.com/2009/12/04/bugcamsmash-dissected-part-1-smash-a-bug/">Dissected part 1 – Smash a Bug</a></li>
<li><a href="http://adamkinney.wordpress.com/2009/12/05/bugcamsmash-dissected-part-2-make-the-bugs-crawl/">Dissected part 2 – Make the Bugs Crawl</a></li>
<li><a href="http://adamkinney.wordpress.com/2009/12/07/bugcamsmash-dissected-part-3-give-the-bugs-brains/">Dissected part 3 – Give the Bugs Brains</a></li>
<li>Dissected part 4 – WebCam and HitTest on a different thread</li>
</ul>
<p> </p>
<p>*<em>(warning this is Silverlight 4 Beta code, if you’re not currently setup to run the beta stick with the video)</em></p>
<p>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/adamkinney.wordpress.com/487/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/adamkinney.wordpress.com/487/"></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/adamkinney.wordpress.com/487/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/adamkinney.wordpress.com/487/"></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/adamkinney.wordpress.com/487/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/adamkinney.wordpress.com/487/"></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/adamkinney.wordpress.com/487/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/adamkinney.wordpress.com/487/"></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/adamkinney.wordpress.com/487/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/adamkinney.wordpress.com/487/"></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=adamkinney.wordpress.com&amp;blog=135089&amp;post=487&amp;subd=adamkinney&amp;ref=&amp;feed=1"></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/11154/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Passing Multiple Records to a Stored Procedure in SQL Server</title>
		<link>http://zdima.net/blog/archives/7203</link>
		<comments>http://zdima.net/blog/archives/7203#comments</comments>
		<pubDate>Wed, 30 Sep 2009 18:51:12 +0000</pubDate>
		<dc:creator>dwahlin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=7203</guid>
		<description><![CDATA[<p>There are so many different ways to work with data that it can make your head spin.  Regardless of the technology, one thing I always try to do when working with databases is minimize the number of calls that are made.  I use ORM frameworks a lot so I have to make sure that my code doesn’t end up calling the database a ton and being overly “chatty”.  </p>  <p>My company is currently working on a large Silverlight 3 application for a customer and have a requirement to allow CSV file uploads through the application.  That’s pretty straightforward to do with Silverlight but in looking through the CSV file there can be 1000s of records and there is a lot of custom functionality around each record.  Initially I was going to handle the business rules and insertion for each row individually.  However, once I saw how many rows were involved I backed off my initial approach since that would mean a single file upload could trigger thousands and thousands of calls to the database which certainly isn’t efficient.  Instead of going that route I decided it would be better to pass all of the rows into a stored procedure and let it handle everything.  That way I can make a single database connection yet handle inserting (and updating and deleting based upon the business rules) many records.  </p>  <p>So how can you pass multiple records into a stored procedure?  Back in “the day” I’d pass in delimited strings and then parse them.  Although that technique probably wasn’t the most efficient, it got the job done.  With SQL Server 2005 and higher we have access to a much more efficient technique due to the availability of XQuery.  The current project I’m working on relies on SQL Server 2005 behind the scenes so that’s what I’ll focus on here.  Note that SQL Server 2008 allows .NET DataTable objects to be passed when using table value parameters as well in a stored procedure.  See <a title="http://www.codeproject.com/KB/database/sqlserver2008.aspx" href="http://www.codeproject.com/KB/database/sqlserver2008.aspx">http://www.codeproject.com/KB/database/sqlserver2008.aspx</a> for an overview of the table value parameter functionality.</p>  <p>For the import I can serialize the list of records to XML and then pass them into a stored procedure.  It appears that you can pass an XmlDocument object from .NET if the stored procedure takes an XML input parameter type.  However, I never got it to work properly doing that so I pass a string containing serialized XML data and then load it into the XML data type.  The stored procedure can then use XQuery to convert the XML into actual rows.  Here’s some code that handles parsing a flat file, converting the data into a List&#60;JobMaterialImport&#62;, serializing the list into XML and then passing the serialized XML data to a stored procedure named ImportJobMaterials.   <br /></p>  <p></p>  <p></p>  <pre><span style="color:blue">public </span><span style="color:#2b91af">List</span>&#60;<span style="color:#2b91af">ImportJobMaterialsResult</span>&#62; ImportJobMaterials(<span style="color:blue">int </span>jobID, <span style="color:#2b91af">Stream </span>stream, <span style="color:blue">string </span>coNumber, <span style="color:blue">string </span>coDesc, <span style="color:blue">string </span>xmlMapFile)
{
    <span style="color:green">//Convert flat file to List&#60;JobMaterialImport&#62; using converter and XML mapping file
    //Mapping file passed from FlatFileHandler.ashx in web project
    </span><span style="color:#2b91af">FlatFileToObjectConverter</span>&#60;<span style="color:#2b91af">JobMaterialImport</span>&#62; converter = <span style="color:blue">new </span><span style="color:#2b91af">FlatFileToObjectConverter</span>&#60;<span style="color:#2b91af">JobMaterialImport</span>&#62;(stream, xmlMapFile);
    <span style="color:#2b91af">List</span>&#60;<span style="color:#2b91af">JobMaterialImport</span>&#62; imports = converter.ConvertToList();
    imports = imports.Take(imports.Count - 2).ToList(); <span style="color:green">//last rows are bogus in flat-file

    //Generate XML and pass to sproc
    </span><span style="color:blue">using </span>(<span style="color:#2b91af">StringWriter </span>sw = <span style="color:blue">new </span><span style="color:#2b91af">StringWriter</span>())
    {
        <span style="color:#2b91af">XmlSerializer </span>xs = <span style="color:blue">new </span><span style="color:#2b91af">XmlSerializer</span>(<span style="color:blue">typeof</span>(<span style="color:#2b91af">List</span>&#60;<span style="color:#2b91af">JobMaterialImport</span>&#62;));
        xs.Serialize(sw, imports);
        <span style="color:blue">try
        </span>{
            <span style="color:green">//Pass materials into sproc
            </span><span style="color:blue">string </span>xml = sw.ToString().Replace(<span style="color:#a31515">&#34;utf-16&#34;</span>, <span style="color:#a31515">&#34;utf-8&#34;</span>);
            <span style="color:blue">return this</span>.DataContext.ImportJobMaterials(xml, jobID, coNumber, coDesc).ToList();            
        }
        <span style="color:blue">catch </span>(<span style="color:#2b91af">Exception </span>exp)
        {
            <span style="color:#2b91af">Logger</span>.Log(<span style="color:#a31515">&#34;Error in JobManagementRepository.ImportJobMaterials&#34;</span>, exp);
        }
    }
    <span style="color:blue">return null</span>;
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p> </p>

<p>The XML that’s generated from the code above looks like the following.  Security Note: We’ll assume that appropriate measures have been taken to clean the data and ensure it doesn’t contain any bad stuff related to injection attacks. That’s especially important if you’ll be running any dynamic SQL in your stored procedure.  I’m not, but I thought I’d be a good citizen and point it out…always sanitize your data with some Clorox before using it. :-)
  <br /></p>

<pre><span style="color:blue">&#60;</span><span style="color:#a31515">ArrayOfJobMaterialImport </span><span style="color:red">xmlns:xsi</span><span style="color:blue">=</span>&#34;<span style="color:blue">http://www.w3.org/2001/XMLSchema-instance</span>&#34; <span style="color:red">xmlns:xsd</span><span style="color:blue">=</span>&#34;<span style="color:blue">http://www.w3.org/2001/XMLSchema</span>&#34;<span style="color:blue">&#62;
  &#60;</span><span style="color:#a31515">JobMaterialImport</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Area</span><span style="color:blue">&#62;</span>BUILDING A<span style="color:blue">&#60;/</span><span style="color:#a31515">Area</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Phase</span><span style="color:blue">&#62;</span>LIGHTING<span style="color:blue">&#60;/</span><span style="color:#a31515">Phase</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">WorkCode</span><span style="color:blue">&#62;</span>0<span style="color:blue">&#60;/</span><span style="color:#a31515">WorkCode</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">WorkCodeTitle</span><span style="color:blue">&#62;</span>Manually Assigned<span style="color:blue">&#60;/</span><span style="color:#a31515">WorkCodeTitle</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Description</span><span style="color:blue">&#62;</span>4x1 1/2in. SQ BOX COMB KO<span style="color:blue">&#60;/</span><span style="color:#a31515">Description</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Quantity</span><span style="color:blue">&#62;</span>2<span style="color:blue">&#60;/</span><span style="color:#a31515">Quantity</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">TotalHours</span><span style="color:blue">&#62;</span>10.46<span style="color:blue">&#60;/</span><span style="color:#a31515">TotalHours</span><span style="color:blue">&#62;
  &#60;/<span style="color:#a31515">Job</span></span><span style="color:#a31515">MaterialImport</span><span style="color:blue">&#62;
  &#60;<span style="color:#a31515">Job</span></span><span style="color:#a31515">MaterialImport</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Area</span><span style="color:blue">&#62;</span>BUILDING A<span style="color:blue">&#60;/</span><span style="color:#a31515">Area</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Phase</span><span style="color:blue">&#62;</span>LIGHTING<span style="color:blue">&#60;/</span><span style="color:#a31515">Phase</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">WorkCode</span><span style="color:blue">&#62;</span>0<span style="color:blue">&#60;/</span><span style="color:#a31515">WorkCode</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">WorkCodeTitle</span><span style="color:blue">&#62;</span>Manually Assigned<span style="color:blue">&#60;/</span><span style="color:#a31515">WorkCodeTitle</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Description</span><span style="color:blue">&#62;</span>#8x   3/4 P/H SELF-TAP SCREW<span style="color:blue">&#60;/</span><span style="color:#a31515">Description</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Quantity</span><span style="color:blue">&#62;</span>4<span style="color:blue">&#60;/</span><span style="color:#a31515">Quantity</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">TotalHours</span><span style="color:blue">&#62;</span>0.28<span style="color:blue">&#60;/</span><span style="color:#a31515">TotalHours</span><span style="color:blue">&#62;
  &#60;/<span style="color:#a31515">Job</span></span><span style="color:#a31515">MaterialImport</span><span style="color:blue">&#62;
  &#60;<span style="color:#a31515">Job</span></span><span style="color:#a31515">MaterialImport</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Area</span><span style="color:blue">&#62;</span>BUILDING A<span style="color:blue">&#60;/</span><span style="color:#a31515">Area</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Phase</span><span style="color:blue">&#62;</span>LIGHTING<span style="color:blue">&#60;/</span><span style="color:#a31515">Phase</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">WorkCode</span><span style="color:blue">&#62;</span>605<span style="color:blue">&#60;/</span><span style="color:#a31515">WorkCode</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">WorkCodeTitle</span><span style="color:blue">&#62;</span>Wiring and System Devices<span style="color:blue">&#60;/</span><span style="color:#a31515">WorkCodeTitle</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Description</span><span style="color:blue">&#62;</span>1G TGL SWITCH PLATE - PLASTIC IVY<span style="color:blue">&#60;/</span><span style="color:#a31515">Description</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">Quantity</span><span style="color:blue">&#62;</span>2<span style="color:blue">&#60;/</span><span style="color:#a31515">Quantity</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">TotalHours</span><span style="color:blue">&#62;</span>0.89<span style="color:blue">&#60;/</span><span style="color:#a31515">TotalHours</span><span style="color:blue">&#62;
  &#60;/<span style="color:#a31515">Job</span></span><span style="color:#a31515">MaterialImport</span><span style="color:blue">&#62;
&#60;/</span><span style="color:#a31515">ArrayOfJobMaterialImport</span><span style="color:blue">&#62;</span></pre>
<a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a>

<p> </p>

<p>Here’s what the stored procedure looks like:</p>

<p> </p>

<pre><span style="color:blue">CREATE PROCEDURE </span>[ImportJobMaterials]
    @JobMaterialsXml <span style="color:blue">AS VARCHAR</span>(<span style="color:blue">MAX</span>),
    @JobID <span style="color:blue">AS INT</span>,
    @ChangeOrderNumber <span style="color:blue">AS VARCHAR</span>(10) = <span style="color:blue">NULL</span>,
    @ChangeOrderDescription <span style="color:blue">AS VARCHAR</span>(100) = <span style="color:blue">NULL
AS
    BEGIN
        DECLARE </span>@XML <span style="color:blue">AS XML
</span>        
<span style="color:blue">        DECLARE </span>@MaterialsTable <span style="color:blue">TABLE
        </span>(
            ID <span style="color:blue">INT IDENTITY</span>(1,1),
            Area <span style="color:blue">VARCHAR</span>(250),
            Phase <span style="color:blue">VARCHAR</span>(250),
            WorkCodeID <span style="color:blue">INT</span>,
            WorkCodeTitle <span style="color:blue">VARCHAR</span>(250),
            MaterialTitle <span style="color:blue">VARCHAR</span>(250),
            Quantity <span style="color:blue">DECIMAL</span>(18,2),
            TotalHours <span style="color:blue">DECIMAL</span>(18,2)
        )
        
        <span style="color:blue">SELECT </span>@XML = @JobMaterialsXml
        
        <span style="color:blue">INSERT INTO </span>@MaterialsTable (Area, Phase, WorkCodeID, WorkCodeTitle, MaterialTitle, Quantity, TotalHours)
        <span style="color:blue">SELECT </span>M.Item.query(<span style="color:#a31515">'./Area'</span>).value(<span style="color:#a31515">'.'</span>,<span style="color:#a31515">'VARCHAR(250)'</span>) Area,
               M.Item.query(<span style="color:#a31515">'./Phase'</span>).value(<span style="color:#a31515">'.'</span>,<span style="color:#a31515">'VARCHAR(250)'</span>) WorkCode,
               M.Item.query(<span style="color:#a31515">'./WorkCodeID'</span>).value(<span style="color:#a31515">'.'</span>,<span style="color:#a31515">'INT'</span>) WorkCodeID,
               M.Item.query(<span style="color:#a31515">'./WorkCodeTitle'</span>).value(<span style="color:#a31515">'.'</span>,<span style="color:#a31515">'VARCHAR(250)'</span>) WorkCodeTitle,
               M.Item.query(<span style="color:#a31515">'./MaterialTitle'</span>).value(<span style="color:#a31515">'.'</span>,<span style="color:#a31515">'VARCHAR(250)'</span>) MaterialTitle,    
               M.Item.query(<span style="color:#a31515">'./Quantity'</span>).value(<span style="color:#a31515">'.'</span>,<span style="color:#a31515">'DECIMAL(18,2)'</span>) Quantity,    
               M.Item.query(<span style="color:#a31515">'./TotalHours'</span>).value(<span style="color:#a31515">'.'</span>,<span style="color:#a31515">'DECIMAL(18,2)'</span>) TotalHours
        <span style="color:blue">FROM </span>@XML.nodes(<span style="color:#a31515">'/ArrayOfJobMaterialImport/JobMaterialImport'</span>) <span style="color:blue">AS </span>M(Item)
        
        <span style="color:green">--Process the data        </span>            
    <span style="color:blue">END
</span></pre>

<p>Once the XML data comes in it’s converted into an XML data type using SELECT @XML = @JobMaterialsXml syntax.  The key part of the T-SQL code is the SELECT statement that grabs each value from the XML data type and looks for specific child nodes.  If the child nodes were attributes instead then you would do something like M.Item.value(‘@attributeName’,’DBType’).  Each JobMaterialImport node in the XML is located by the @XML.nodes(‘/ArrayOfJobMaterialImport/JobMaterialImport’) AS M(Item) code.  What’s nice about this approach is that a single call can be made to the database yet 1000s of records can be processed.  Not optimal for every situation, but exactly what I needed and fairly straightforward to use.</p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7220575" width="1" height="1"><p class="read-more"><a href="http://zdima.net/blog/archives/7203">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<p>There are so many different ways to work with data that it can make your head spin.  Regardless of the technology, one thing I always try to do when working with databases is minimize the number of calls that are made.  I use ORM frameworks a lot so I have to make sure that my code doesn’t end up calling the database a ton and being overly “chatty”.  </p>
<p>My company is currently working on a large Silverlight 3 application for a customer and have a requirement to allow CSV file uploads through the application.  That’s pretty straightforward to do with Silverlight but in looking through the CSV file there can be 1000s of records and there is a lot of custom functionality around each record.  Initially I was going to handle the business rules and insertion for each row individually.  However, once I saw how many rows were involved I backed off my initial approach since that would mean a single file upload could trigger thousands and thousands of calls to the database which certainly isn’t efficient.  Instead of going that route I decided it would be better to pass all of the rows into a stored procedure and let it handle everything.  That way I can make a single database connection yet handle inserting (and updating and deleting based upon the business rules) many records.  </p>
<p>So how can you pass multiple records into a stored procedure?  Back in “the day” I’d pass in delimited strings and then parse them.  Although that technique probably wasn’t the most efficient, it got the job done.  With SQL Server 2005 and higher we have access to a much more efficient technique due to the availability of XQuery.  The current project I’m working on relies on SQL Server 2005 behind the scenes so that’s what I’ll focus on here.  Note that SQL Server 2008 allows .NET DataTable objects to be passed when using table value parameters as well in a stored procedure.  See <a title="http://www.codeproject.com/KB/database/sqlserver2008.aspx" href="http://www.codeproject.com/KB/database/sqlserver2008.aspx">www.codeproject.com/KB/database/sqlserver2008.aspx</a> for an overview of the table value parameter functionality.</p>
<p>For the import I can serialize the list of records to XML and then pass them into a stored procedure.  It appears that you can pass an XmlDocument object from .NET if the stored procedure takes an XML input parameter type.  However, I never got it to work properly doing that so I pass a string containing serialized XML data and then load it into the XML data type.  The stored procedure can then use XQuery to convert the XML into actual rows.  Here’s some code that handles parsing a flat file, converting the data into a List&lt;JobMaterialImport&gt;, serializing the list into XML and then passing the serialized XML data to a stored procedure named ImportJobMaterials.   </p>
</p>
<pre><span >public </span><span >List</span>&lt;<span >ImportJobMaterialsResult</span>&gt; ImportJobMaterials(<span >int </span>jobID, <span >Stream </span>stream, <span >string </span>coNumber, <span >string </span>coDesc, <span >string </span>xmlMapFile)
{
    <span >//Convert flat file to List&lt;JobMaterialImport&gt; using converter and XML mapping file
    //Mapping file passed from FlatFileHandler.ashx in web project
    </span><span >FlatFileToObjectConverter</span>&lt;<span >JobMaterialImport</span>&gt; converter = <span >new </span><span >FlatFileToObjectConverter</span>&lt;<span >JobMaterialImport</span>&gt;(stream, xmlMapFile);
    <span >List</span>&lt;<span >JobMaterialImport</span>&gt; imports = converter.ConvertToList();
    imports = imports.Take(imports.Count - 2).ToList(); <span >//last rows are bogus in flat-file

    //Generate XML and pass to sproc
    </span><span >using </span>(<span >StringWriter </span>sw = <span >new </span><span >StringWriter</span>())
    {
        <span >XmlSerializer </span>xs = <span >new </span><span >XmlSerializer</span>(<span >typeof</span>(<span >List</span>&lt;<span >JobMaterialImport</span>&gt;));
        xs.Serialize(sw, imports);
        <span >try
        </span>{
            <span >//Pass materials into sproc
            </span><span >string </span>xml = sw.ToString().Replace(<span >&quot;utf-16&quot;</span>, <span >&quot;utf-8&quot;</span>);
            <span >return this</span>.DataContext.ImportJobMaterials(xml, jobID, coNumber, coDesc).ToList();
        }
        <span >catch </span>(<span >Exception </span>exp)
        {
            <span >Logger</span>.Log(<span >&quot;Error in JobManagementRepository.ImportJobMaterials&quot;</span>, exp);
        }
    }
    <span >return null</span>;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<p>The XML that’s generated from the code above looks like the following.  Security Note: We’ll assume that appropriate measures have been taken to clean the data and ensure it doesn’t contain any bad stuff related to injection attacks. That’s especially important if you’ll be running any dynamic SQL in your stored procedure.  I’m not, but I thought I’d be a good citizen and point it out…always sanitize your data with some Clorox before using it. <img src='http://zdima.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /><br />
  </p>
<pre><span >&lt;</span><span >ArrayOfJobMaterialImport </span><span >xmlns:xsi</span><span >=</span>&quot;<span ><a href="http://www.w3.org/2001/XMLSchema-instance" class="autohyperlink" title="http://www.w3.org/2001/XMLSchema-instance" target="_blank" rel="nofollow">www.w3.org/2001/XMLSchema-instance</a></span>&quot; <span >xmlns:xsd</span><span >=</span>&quot;<span ><a href="http://www.w3.org/2001/XMLSchema" class="autohyperlink" title="http://www.w3.org/2001/XMLSchema" target="_blank" rel="nofollow">www.w3.org/2001/XMLSchema</a></span>&quot;<span >&gt;
  &lt;</span><span >JobMaterialImport</span><span >&gt;
    &lt;</span><span >Area</span><span >&gt;</span>BUILDING A<span >&lt;/</span><span >Area</span><span >&gt;
    &lt;</span><span >Phase</span><span >&gt;</span>LIGHTING<span >&lt;/</span><span >Phase</span><span >&gt;
    &lt;</span><span >WorkCode</span><span >&gt;</span>0<span >&lt;/</span><span >WorkCode</span><span >&gt;
    &lt;</span><span >WorkCodeTitle</span><span >&gt;</span>Manually Assigned<span >&lt;/</span><span >WorkCodeTitle</span><span >&gt;
    &lt;</span><span >Description</span><span >&gt;</span>4x1 1/2in. SQ BOX COMB KO<span >&lt;/</span><span >Description</span><span >&gt;
    &lt;</span><span >Quantity</span><span >&gt;</span>2<span >&lt;/</span><span >Quantity</span><span >&gt;
    &lt;</span><span >TotalHours</span><span >&gt;</span>10.46<span >&lt;/</span><span >TotalHours</span><span >&gt;
  &lt;/<span >Job</span></span><span >MaterialImport</span><span >&gt;
  &lt;<span >Job</span></span><span >MaterialImport</span><span >&gt;
    &lt;</span><span >Area</span><span >&gt;</span>BUILDING A<span >&lt;/</span><span >Area</span><span >&gt;
    &lt;</span><span >Phase</span><span >&gt;</span>LIGHTING<span >&lt;/</span><span >Phase</span><span >&gt;
    &lt;</span><span >WorkCode</span><span >&gt;</span>0<span >&lt;/</span><span >WorkCode</span><span >&gt;
    &lt;</span><span >WorkCodeTitle</span><span >&gt;</span>Manually Assigned<span >&lt;/</span><span >WorkCodeTitle</span><span >&gt;
    &lt;</span><span >Description</span><span >&gt;</span>#8x   3/4 P/H SELF-TAP SCREW<span >&lt;/</span><span >Description</span><span >&gt;
    &lt;</span><span >Quantity</span><span >&gt;</span>4<span >&lt;/</span><span >Quantity</span><span >&gt;
    &lt;</span><span >TotalHours</span><span >&gt;</span>0.28<span >&lt;/</span><span >TotalHours</span><span >&gt;
  &lt;/<span >Job</span></span><span >MaterialImport</span><span >&gt;
  &lt;<span >Job</span></span><span >MaterialImport</span><span >&gt;
    &lt;</span><span >Area</span><span >&gt;</span>BUILDING A<span >&lt;/</span><span >Area</span><span >&gt;
    &lt;</span><span >Phase</span><span >&gt;</span>LIGHTING<span >&lt;/</span><span >Phase</span><span >&gt;
    &lt;</span><span >WorkCode</span><span >&gt;</span>605<span >&lt;/</span><span >WorkCode</span><span >&gt;
    &lt;</span><span >WorkCodeTitle</span><span >&gt;</span>Wiring and System Devices<span >&lt;/</span><span >WorkCodeTitle</span><span >&gt;
    &lt;</span><span >Description</span><span >&gt;</span>1G TGL SWITCH PLATE - PLASTIC IVY<span >&lt;/</span><span >Description</span><span >&gt;
    &lt;</span><span >Quantity</span><span >&gt;</span>2<span >&lt;/</span><span >Quantity</span><span >&gt;
    &lt;</span><span >TotalHours</span><span >&gt;</span>0.89<span >&lt;/</span><span >TotalHours</span><span >&gt;
  &lt;/<span >Job</span></span><span >MaterialImport</span><span >&gt;
&lt;/</span><span >ArrayOfJobMaterialImport</span><span >&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<p>Here’s what the stored procedure looks like:</p>
<p> </p>
<pre><span >CREATE PROCEDURE </span>[ImportJobMaterials]
    @JobMaterialsXml <span >AS VARCHAR</span>(<span >MAX</span>),
    @JobID <span >AS INT</span>,
    @ChangeOrderNumber <span >AS VARCHAR</span>(10) = <span >NULL</span>,
    @ChangeOrderDescription <span >AS VARCHAR</span>(100) = <span >NULL
AS
    BEGIN
        DECLARE </span>@XML <span >AS XML
</span>
<span >        DECLARE </span>@MaterialsTable <span >TABLE
        </span>(
            ID <span >INT IDENTITY</span>(1,1),
            Area <span >VARCHAR</span>(250),
            Phase <span >VARCHAR</span>(250),
            WorkCodeID <span >INT</span>,
            WorkCodeTitle <span >VARCHAR</span>(250),
            MaterialTitle <span >VARCHAR</span>(250),
            Quantity <span >DECIMAL</span>(18,2),
            TotalHours <span >DECIMAL</span>(18,2)
        )

        <span >SELECT </span>@XML = @JobMaterialsXml

        <span >INSERT INTO </span>@MaterialsTable (Area, Phase, WorkCodeID, WorkCodeTitle, MaterialTitle, Quantity, TotalHours)
        <span >SELECT </span>M.Item.query(<span >'./Area'</span>).value(<span >'.'</span>,<span >'VARCHAR(250)'</span>) Area,
               M.Item.query(<span >'./Phase'</span>).value(<span >'.'</span>,<span >'VARCHAR(250)'</span>) WorkCode,
               M.Item.query(<span >'./WorkCodeID'</span>).value(<span >'.'</span>,<span >'INT'</span>) WorkCodeID,
               M.Item.query(<span >'./WorkCodeTitle'</span>).value(<span >'.'</span>,<span >'VARCHAR(250)'</span>) WorkCodeTitle,
               M.Item.query(<span >'./MaterialTitle'</span>).value(<span >'.'</span>,<span >'VARCHAR(250)'</span>) MaterialTitle,
               M.Item.query(<span >'./Quantity'</span>).value(<span >'.'</span>,<span >'DECIMAL(18,2)'</span>) Quantity,
               M.Item.query(<span >'./TotalHours'</span>).value(<span >'.'</span>,<span >'DECIMAL(18,2)'</span>) TotalHours
        <span >FROM </span>@XML.nodes(<span >'/ArrayOfJobMaterialImport/JobMaterialImport'</span>) <span >AS </span>M(Item)

        <span >--Process the data        </span>
    <span >END
</span></pre>
<p>Once the XML data comes in it’s converted into an XML data type using SELECT @XML = @JobMaterialsXml syntax.  The key part of the T-SQL code is the SELECT statement that grabs each value from the XML data type and looks for specific child nodes.  If the child nodes were attributes instead then you would do something like M.Item.value(‘@attributeName’,’DBType’).  Each JobMaterialImport node in the XML is located by the @XML.nodes(‘/ArrayOfJobMaterialImport/JobMaterialImport’) AS M(Item) code.  What’s nice about this approach is that a single call can be made to the database yet 1000s of records can be processed.  Not optimal for every situation, but exactly what I needed and fairly straightforward to use.</p>
<p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7220575" width="1" height="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/7203/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Use Bing Visual Search to Browse iPhone Applications [Search]</title>
		<link>http://zdima.net/blog/archives/6467</link>
		<comments>http://zdima.net/blog/archives/6467#comments</comments>
		<pubDate>Wed, 16 Sep 2009 14:00:00 +0000</pubDate>
		<dc:creator>Kevin Purdy</dc:creator>
				<category><![CDATA[Contributors]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[mobile apps]]></category>
		<category><![CDATA[Search]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[bing]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=6467</guid>
		<description><![CDATA[<p><a rel="lytebox" href="http://cache.gawker.com/assets/images/lifehacker/2009/09/visual_search_iphone.jpg"><img src="http://cache.gawker.com/assets/images/17/2009/09/500x_visual_search_iphone.jpg" width="500"></a>Microsoft's Visual Search tool, <a href="http://lifehacker.com/5359111/microsofts-bing-introduces-visual-search-feature">introduced earlier this week</a>, turns out to be a pretty helpful platform for browsing free and paid iPhone applications. It's a trade-off: you won't have to fire up iTunes, but you will have to install Silverlight.</p> <p>Reader Anunay writes in with the link to turn Bing into a robust search for iPhone apps. From left-hand links, you can narrow your search by broad categories, specific prices, publishers, or other criteria. Hovering over an app icon gives you ranking, category, and release date information, and clicking an icon brings you to a Bing search page for that app—which, in turn, generally leads you to a developer&#39;s page and iTunes link. For those who don&#39;t like to (or can&#39;t) fire up iTunes to browse and search apps, it&#39;s a decent alternative, even if it requires installing a third-party plug-in. <em>Thanks Anunay!</em></p> <div><a href="http://www.bing.com/visualsearch?q=Top+iPhone+apps&#38;g=iphone_apps&#38;FORM=Z9GE18">Bing Visual Search - Top iPhone Apps</a></div> <br />
<br />
<a href="http://ads.pheedo.com/click.phdo?s=1529fe47f1da7d07882a2e07352fad5c&#38;p=1"><img alt="" style="border:0" border="0" src="http://ads.pheedo.com/img.phdo?s=1529fe47f1da7d07882a2e07352fad5c&#38;p=1"></a>
<img alt="" height="0" width="0" border="0" src="http://a.rfihub.com/eus.gif?eui=2225"><div>
<a href="http://feeds.gawker.com/~ff/lifehacker/full?a=qvJS54Mxwpg:EPWYD_XGVKM:H0mrP-F8Qgo"><img src="http://feeds.feedburner.com/~ff/lifehacker/full?d=H0mrP-F8Qgo" border="0"></a> <a href="http://feeds.gawker.com/~ff/lifehacker/full?a=qvJS54Mxwpg:EPWYD_XGVKM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/lifehacker/full?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.gawker.com/~ff/lifehacker/full?a=qvJS54Mxwpg:EPWYD_XGVKM:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/lifehacker/full?i=qvJS54Mxwpg:EPWYD_XGVKM:D7DqB2pKExk" border="0"></a> <a href="http://feeds.gawker.com/~ff/lifehacker/full?a=qvJS54Mxwpg:EPWYD_XGVKM:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/lifehacker/full?i=qvJS54Mxwpg:EPWYD_XGVKM:V_sGLiPBpWU" border="0"></a>
</div><img src="http://feeds.feedburner.com/~r/lifehacker/full/~4/qvJS54Mxwpg" height="1" width="1"><p class="read-more"><a href="http://zdima.net/blog/archives/6467">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<p><a rel="lytebox" href="http://cache.gawker.com/assets/images/lifehacker/2009/09/visual_search_iphone.jpg"><img src="http://cache.gawker.com/assets/images/17/2009/09/500x_visual_search_iphone.jpg" width="500"></a>Microsoft&#8217;s Visual Search tool, <a href="http://lifehacker.com/5359111/microsofts-bing-introduces-visual-search-feature">introduced earlier this week</a>, turns out to be a pretty helpful platform for browsing free and paid iPhone applications. It&#8217;s a trade-off: you won&#8217;t have to fire up iTunes, but you will have to install Silverlight.</p>
<p>Reader Anunay writes in with the link to turn Bing into a robust search for iPhone apps. From left-hand links, you can narrow your search by broad categories, specific prices, publishers, or other criteria. Hovering over an app icon gives you ranking, category, and release date information, and clicking an icon brings you to a Bing search page for that app—which, in turn, generally leads you to a developer&#39;s page and iTunes link. For those who don&#39;t like to (or can&#39;t) fire up iTunes to browse and search apps, it&#39;s a decent alternative, even if it requires installing a third-party plug-in. <em>Thanks Anunay!</em></p>
<div><a href="http://www.bing.com/visualsearch?q=Top+iPhone+apps&amp;g=iphone_apps&amp;FORM=Z9GE18">Bing Visual Search &#8211; Top iPhone Apps</a></div>
<p> <br ><br />
<br ><br />
<a href="http://ads.pheedo.com/click.phdo?s=1529fe47f1da7d07882a2e07352fad5c&amp;p=1"><img alt=""  border="0" src="http://ads.pheedo.com/img.phdo?s=1529fe47f1da7d07882a2e07352fad5c&amp;p=1"></a><br />
<img alt="" height="0" width="0" border="0" src="http://a.rfihub.com/eus.gif?eui=2225">
<div>
<a href="http://feeds.gawker.com/~ff/lifehacker/full?a=qvJS54Mxwpg:EPWYD_XGVKM:H0mrP-F8Qgo"><img src="http://feeds.feedburner.com/~ff/lifehacker/full?d=H0mrP-F8Qgo" border="0"></a> <a href="http://feeds.gawker.com/~ff/lifehacker/full?a=qvJS54Mxwpg:EPWYD_XGVKM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/lifehacker/full?d=yIl2AUoC8zA" border="0"></a> <a href="http://feeds.gawker.com/~ff/lifehacker/full?a=qvJS54Mxwpg:EPWYD_XGVKM:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/lifehacker/full?i=qvJS54Mxwpg:EPWYD_XGVKM:D7DqB2pKExk" border="0"></a> <a href="http://feeds.gawker.com/~ff/lifehacker/full?a=qvJS54Mxwpg:EPWYD_XGVKM:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/lifehacker/full?i=qvJS54Mxwpg:EPWYD_XGVKM:V_sGLiPBpWU" border="0"></a>
</div>
<p><img src="http://feeds.feedburner.com/~r/lifehacker/full/~4/qvJS54Mxwpg" height="1" width="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/6467/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cleaning Up the Disabled State of a Silverlight Control using Expression Blend</title>
		<link>http://zdima.net/blog/archives/5151</link>
		<comments>http://zdima.net/blog/archives/5151#comments</comments>
		<pubDate>Thu, 27 Aug 2009 21:58:47 +0000</pubDate>
		<dc:creator>dwahlin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=5151</guid>
		<description><![CDATA[<p>Silverlight provides the ultimate in flexibility when it comes to styling controls.  If you don’t like how something looks you can tweak the template in a tool like Expression Blend quickly and easily and get something completely different.  This post is geared towards those of you who may just be getting into Silverlight.  My goal is to demonstrate how easy it is to change controls using a simple example that I just went through on a client application.</p>  <p>Being able to change a control’s template comes in handy when you don’t like the built-in style used by the framework.  I’m working on a menu used in a client application and the disabled state of the HyperlinkButton control wasn’t looking too good.  I thought the control looked butt ugly and was unreadable in the disabled state.…just sayin’.  :-)  I wasn’t looking to do anything fancy, but did want to make it obvious that the control was disabled while still making it easy for the end user to read the text.  Here’s what the menu looked like when two HyperLinkButton controls were disabled using the built-in control template:</p>  <p><a href="http://weblogs.asp.net/blogs/dwahlin/image_5805E7BE.png"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_377EA80C.png" width="630" height="66"></a> </p>  <p>   <br />I don’t know about you, but “Edit Job” and “Job Plan” look pretty bad in my opinion.  They’re definitely disabled (or possibly just plain dead), but they could both look better.  As mentioned earlier, Silverlight allows any control to be changed by simply modifying the control’s template.  The easiest way to do this is to use Expression Blend although you can do it in Visual Studio 2008 by hand as well.  When the control to tweak is placed on the Blend design surface you can right-click on it and select <strong>Edit Template –&#62; Edit a Copy</strong>:    <br /></p>  <p><a href="http://weblogs.asp.net/blogs/dwahlin/image_48EF08E4.png"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_3A445CFF.png" width="341" height="437"></a> </p>  <p>   <br />From there you can give the new style a name, specify where it should be stored and then click OK:    <br /></p>  <p><a href="http://weblogs.asp.net/blogs/dwahlin/image_165B85A5.png"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_55B93935.png" width="415" height="233"></a> </p>  <p>   <br />Once the style is created you’ll be able to see it in Blend and locate an element named DisabledOverlay.  In my case this was the culprit of the ugliness.  <br /></p>  <p><a href="http://weblogs.asp.net/blogs/dwahlin/image_54E0D34B.png"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_2930094F.png" width="300" height="193"></a> </p>  <p>   <br />I ended up adjusting the Foreground color of the DisabledOverlay to black and set the Opacity to .4 using the properties window.  However, doing that isn’t quite enough.  The HyperlinkButton template places the DisabledOverlay TextBlock over the actual link content when the control is disabled.  That’s why you get the semi blurry effect because two pieces of text are showing.  I decided I wanted to hide the contentPresenter element when the control was disabled and just show the DisabledOverlay instead since it looked a lot cleaner.  Fortunately that’s quite easy to do.  Internally the control template uses the VisualStateManager to show and hide the DisabledOverlay.  I went into the disabled state and changed it to hide the contentPresenter.  That’s done by clicking on the <strong>States</strong> tab followed by the <strong>Disabled</strong> state:    <br /></p>  <p><a href="http://weblogs.asp.net/blogs/dwahlin/image_136620F2.png"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_00B1273B.png" width="306" height="321"></a> </p>  <p>   <br />Any changes you make to the contentPresenter are now tracked for that state so I clicked on contentPresenter and then set is Visibility property to Collapsed for the Disabled state:    <br /></p>  <p><a href="http://weblogs.asp.net/blogs/dwahlin/image_6D8FFA8E.png"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_58324526.png" width="308" height="138"></a> </p>  <p>   <br />Doing that modifies the disabled state.  Here’s what the XAML looks like (I cleaned it up slightly).  You can see that it causes the contentPresenter’s Visibility to be set to Collapsed:    <br /></p>  <pre><span style="color:blue">&#60;</span><span style="color:#a31515">VisualState </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Name</span><span style="color:blue">=&#34;Disabled&#34;&#62;
    &#60;</span><span style="color:#a31515">Storyboard</span><span style="color:blue">&#62;
        &#60;</span><span style="color:#a31515">ObjectAnimationUsingKeyFrames </span><span style="color:red">Storyboard.TargetName</span><span style="color:blue">=&#34;DisabledOverlay&#34; </span><span style="color:red">Storyboard.TargetProperty</span><span style="color:blue">=&#34;Visibility&#34; </span><span style="color:red">Duration</span><span style="color:blue">=&#34;0&#34;&#62;
            &#60;</span><span style="color:#a31515">DiscreteObjectKeyFrame </span><span style="color:red">KeyTime</span><span style="color:blue">=&#34;0&#34;&#62;
                &#60;</span><span style="color:#a31515">DiscreteObjectKeyFrame.Value</span><span style="color:blue">&#62;
                    &#60;</span><span style="color:#a31515">Visibility</span><span style="color:blue">&#62;</span><span style="color:#a31515">Visible</span><span style="color:blue">&#60;/</span><span style="color:#a31515">Visibility</span><span style="color:blue">&#62;
                &#60;/</span><span style="color:#a31515">DiscreteObjectKeyFrame.Value</span><span style="color:blue">&#62;
            &#60;/</span><span style="color:#a31515">DiscreteObjectKeyFrame</span><span style="color:blue">&#62;
        &#60;/</span><span style="color:#a31515">ObjectAnimationUsingKeyFrames</span><span style="color:blue">&#62;
        &#60;</span><span style="color:#a31515">ObjectAnimationUsingKeyFrames </span><span style="color:red">Storyboard.TargetName</span><span style="color:blue">=&#34;contentPresenter&#34; </span><span style="color:red">Storyboard.TargetProperty</span><span style="color:blue">=&#34;Visibility&#34; </span><span style="color:red">Duration</span><span style="color:blue">=&#34;0&#34;&#62;
            &#60;</span><span style="color:#a31515">DiscreteObjectKeyFrame </span><span style="color:red">KeyTime</span><span style="color:blue">=&#34;0&#34;&#62;
                &#60;</span><span style="color:#a31515">DiscreteObjectKeyFrame.Value</span><span style="color:blue">&#62;
                    &#60;</span><span style="color:#a31515">Visibility</span><span style="color:blue">&#62;</span><span style="color:#a31515">Collapsed</span><span style="color:blue">&#60;/</span><span style="color:#a31515">Visibility</span><span style="color:blue">&#62;
                &#60;/</span><span style="color:#a31515">DiscreteObjectKeyFrame.Value</span><span style="color:blue">&#62;
            &#60;/</span><span style="color:#a31515">DiscreteObjectKeyFrame</span><span style="color:blue">&#62;
        &#60;/</span><span style="color:#a31515">ObjectAnimationUsingKeyFrames</span><span style="color:blue">&#62;
    &#60;/</span><span style="color:#a31515">Storyboard</span><span style="color:blue">&#62;
&#60;/</span><span style="color:#a31515">VisualState</span><span style="color:blue">&#62;
&#60;/</span><span style="color:#a31515">VisualStateGroup</span><span style="color:blue">&#62;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p> </p>

<p>From there I simply applied the style and newly created template to each HyperlinkButton control:
  <br /></p>

<pre><span style="color:blue">&#60;</span><span style="color:#a31515">HyperlinkButton </span><span style="color:red">Style</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">StaticResource </span><span style="color:red">MenuHyperlinkButtonStyle</span><span style="color:blue">}&#34; </span><span style="color:red">Content</span><span style="color:blue">=&#34;Job Plan&#34;</span><span style="color:blue"> /&#62;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p></p>

<p></p>

<p></p>

<p></p>

<p>
  <br />The end result is a menu that looks much better (in my opinion anyway) when the controls are disabled.  Here’s a before and after image:</p>

<p><strong>Before:</strong></p>

<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_25623EB2.png"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_7708B904.png" width="684" height="72"></a> </p>

<p><strong>
    <br />After:</strong>

  <br /><a href="http://weblogs.asp.net/blogs/dwahlin/image_4B57EF08.png"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_4AEBBC13.png" width="686" height="66"></a> </p>

<p></p>

<p>
  <br />This is a really simple example of modifying control templates but you can literally tweak any aspect of a control to get things looking just like you want them to look.</p>

<p> </p>

<p><a href="http://www.thewahlingroup.com/"><img border="0" alt="Logo" src="http://weblogs.asp.net/blogs/dwahlin/Logo_702D5F60.jpg" width="240" height="57"></a></p>

<p>For more information about <strong>onsite, online and video training, mentoring and consulting solutions</strong> for .NET, SharePoint or Silverlight please visit <a href="http://www.thewahlingroup.com/">http://www.thewahlingroup.com</a>.</p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7183394" width="1" height="1"><p class="read-more"><a href="http://zdima.net/blog/archives/5151">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<p>Silverlight provides the ultimate in flexibility when it comes to styling controls.  If you don’t like how something looks you can tweak the template in a tool like Expression Blend quickly and easily and get something completely different.  This post is geared towards those of you who may just be getting into Silverlight.  My goal is to demonstrate how easy it is to change controls using a simple example that I just went through on a client application.</p>
<p>Being able to change a control’s template comes in handy when you don’t like the built-in style used by the framework.  I’m working on a menu used in a client application and the disabled state of the HyperlinkButton control wasn’t looking too good.  I thought the control looked butt ugly and was unreadable in the disabled state.…just sayin’.  <img src='http://zdima.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />   I wasn’t looking to do anything fancy, but did want to make it obvious that the control was disabled while still making it easy for the end user to read the text.  Here’s what the menu looked like when two HyperLinkButton controls were disabled using the built-in control template:</p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_5805E7BE.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_377EA80C.png" width="630" height="66"></a> </p>
<p>I don’t know about you, but “Edit Job” and “Job Plan” look pretty bad in my opinion.  They’re definitely disabled (or possibly just plain dead), but they could both look better.  As mentioned earlier, Silverlight allows any control to be changed by simply modifying the control’s template.  The easiest way to do this is to use Expression Blend although you can do it in Visual Studio 2008 by hand as well.  When the control to tweak is placed on the Blend design surface you can right-click on it and select <strong>Edit Template –&gt; Edit a Copy</strong>:    </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_48EF08E4.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_3A445CFF.png" width="341" height="437"></a> </p>
<p>From there you can give the new style a name, specify where it should be stored and then click OK:    </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_165B85A5.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_55B93935.png" width="415" height="233"></a> </p>
<p>Once the style is created you’ll be able to see it in Blend and locate an element named DisabledOverlay.  In my case this was the culprit of the ugliness.  </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_54E0D34B.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_2930094F.png" width="300" height="193"></a> </p>
<p>I ended up adjusting the Foreground color of the DisabledOverlay to black and set the Opacity to .4 using the properties window.  However, doing that isn’t quite enough.  The HyperlinkButton template places the DisabledOverlay TextBlock over the actual link content when the control is disabled.  That’s why you get the semi blurry effect because two pieces of text are showing.  I decided I wanted to hide the contentPresenter element when the control was disabled and just show the DisabledOverlay instead since it looked a lot cleaner.  Fortunately that’s quite easy to do.  Internally the control template uses the VisualStateManager to show and hide the DisabledOverlay.  I went into the disabled state and changed it to hide the contentPresenter.  That’s done by clicking on the <strong>States</strong> tab followed by the <strong>Disabled</strong> state:    </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_136620F2.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_00B1273B.png" width="306" height="321"></a> </p>
<p>Any changes you make to the contentPresenter are now tracked for that state so I clicked on contentPresenter and then set is Visibility property to Collapsed for the Disabled state:    </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_6D8FFA8E.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_58324526.png" width="308" height="138"></a> </p>
<p>Doing that modifies the disabled state.  Here’s what the XAML looks like (I cleaned it up slightly).  You can see that it causes the contentPresenter’s Visibility to be set to Collapsed:    </p>
<pre><span >&lt;</span><span >VisualState </span><span >x</span><span >:</span><span >Name</span><span >=&quot;Disabled&quot;&gt;
    &lt;</span><span >Storyboard</span><span >&gt;
        &lt;</span><span >ObjectAnimationUsingKeyFrames </span><span >Storyboard.TargetName</span><span >=&quot;DisabledOverlay&quot; </span><span >Storyboard.TargetProperty</span><span >=&quot;Visibility&quot; </span><span >Duration</span><span >=&quot;0&quot;&gt;
            &lt;</span><span >DiscreteObjectKeyFrame </span><span >KeyTime</span><span >=&quot;0&quot;&gt;
                &lt;</span><span >DiscreteObjectKeyFrame.Value</span><span >&gt;
                    &lt;</span><span >Visibility</span><span >&gt;</span><span >Visible</span><span >&lt;/</span><span >Visibility</span><span >&gt;
                &lt;/</span><span >DiscreteObjectKeyFrame.Value</span><span >&gt;
            &lt;/</span><span >DiscreteObjectKeyFrame</span><span >&gt;
        &lt;/</span><span >ObjectAnimationUsingKeyFrames</span><span >&gt;
        &lt;</span><span >ObjectAnimationUsingKeyFrames </span><span >Storyboard.TargetName</span><span >=&quot;contentPresenter&quot; </span><span >Storyboard.TargetProperty</span><span >=&quot;Visibility&quot; </span><span >Duration</span><span >=&quot;0&quot;&gt;
            &lt;</span><span >DiscreteObjectKeyFrame </span><span >KeyTime</span><span >=&quot;0&quot;&gt;
                &lt;</span><span >DiscreteObjectKeyFrame.Value</span><span >&gt;
                    &lt;</span><span >Visibility</span><span >&gt;</span><span >Collapsed</span><span >&lt;/</span><span >Visibility</span><span >&gt;
                &lt;/</span><span >DiscreteObjectKeyFrame.Value</span><span >&gt;
            &lt;/</span><span >DiscreteObjectKeyFrame</span><span >&gt;
        &lt;/</span><span >ObjectAnimationUsingKeyFrames</span><span >&gt;
    &lt;/</span><span >Storyboard</span><span >&gt;
&lt;/</span><span >VisualState</span><span >&gt;
&lt;/</span><span >VisualStateGroup</span><span >&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p> </p>
<p>From there I simply applied the style and newly created template to each HyperlinkButton control:<br />
  </p>
<pre><span >&lt;</span><span >HyperlinkButton </span><span >Style</span><span >=&quot;{</span><span >StaticResource </span><span >MenuHyperlinkButtonStyle</span><span >}&quot; </span><span >Content</span><span >=&quot;Job Plan&quot;</span><span > /&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
</p>
</p>
<p>
  <br />The end result is a menu that looks much better (in my opinion anyway) when the controls are disabled.  Here’s a before and after image:</p>
<p><strong>Before:</strong></p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_25623EB2.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_7708B904.png" width="684" height="72"></a> </p>
<p><strong><br />
    <br />After:</strong></p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_4B57EF08.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_4AEBBC13.png" width="686" height="66"></a> </p>
</p>
<p>
  <br />This is a really simple example of modifying control templates but you can literally tweak any aspect of a control to get things looking just like you want them to look.</p>
<p> </p>
<p><a href="http://www.thewahlingroup.com/"><img title="Logo" border="0" alt="Logo" src="http://weblogs.asp.net/blogs/dwahlin/Logo_702D5F60.jpg" width="240" height="57"></a></p>
<p>For more information about <strong>onsite, online and video training, mentoring and consulting solutions</strong> for .NET, SharePoint or Silverlight please visit <a href="http://www.thewahlingroup.com/">www.thewahlingroup.com</a>.</p>
<p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7183394" width="1" height="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/5151/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Silverlight DataContext Proxy to Simplify Data Binding in Nested Controls</title>
		<link>http://zdima.net/blog/archives/4761</link>
		<comments>http://zdima.net/blog/archives/4761#comments</comments>
		<pubDate>Fri, 21 Aug 2009 06:37:53 +0000</pubDate>
		<dc:creator>dwahlin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=4761</guid>
		<description><![CDATA[<p>Data binding is one of my favorite features and something that I use a lot while building Silverlight applications.  Silverlight makes it really easy to bind data to different controls and move data from controls back into the original bound object without having to write any C# or VB code in many cases.  Here’s an example of binding a ComboBox control to an object that defines a property named Branches:    <br /></p>  <pre><span style="color:blue">&#60;</span><span style="color:#a31515">ComboBox 
    </span><span style="color:red">ItemsSource</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:blue">Branches}&#34; 
</span><span style="color:blue">    </span><span style="color:red">DisplayMemberPath</span><span style="color:blue">=&#34;Title&#34;/&#62;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>
  <br />This code binds the ItemsSource property to the DataContext object’s Branches property and displays the Branch object’s Title property in the ComboBox.  The DataContext could be assigned directly to the ComboBox through code or could be assigned to a parent object.  If it’s defined on a parent then all children have access to the object.  </p>

<p>This works great as long as the ComboBox has access to the Branches property as shown in Figure 1 below (note that the Page shown in the figure is a Silverlight Page class or User Control not a web page).  However, figure 2 demonstrates a problem that can occur as the ComboBox control’s DataContext is changed to something other than the ViewModel object that defines the Branches property.  In this example a DataGrid binds to the Jobs property of the ViewModel and each row’s DataContext is a Job type.  The Job type doesn’t have a Branches property (the ViewModel object does obviously) so the ComboBox no longer has access to it for data binding.  Or does it? 
  <br />

  <br /></p>

<table border="0" cellspacing="5" cellpadding="8" width="934"><tbody>
    <tr bgcolor="#efefef">
      <td valign="top" width="242" align="center"><strong>
          <h3><strong>Figure 1 – All Systems go for binding</strong></h3>
        </strong></td>

      <td valign="top" width="675" align="center">
        <h3><strong>Figure 2 – Houston, we have a problem</strong></h3>
      </td>
    </tr>

    <tr>
      <td valign="top" width="242" align="center"><a href="http://weblogs.asp.net/blogs/dwahlin/image_525928A2.png"><img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_5E7AA2C9.png" width="223" height="463"></a> </td>

      <td valign="top" width="675" align="center"><a href="http://weblogs.asp.net/blogs/dwahlin/image_4B59761D.png"><img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_74810E5B.png" width="656" height="501"></a> </td>
    </tr>
  </tbody></table>

<p> </p>

<h2>Using a Static Resource When Binding Nested Controls</h2>

<p>
  <br />While the ComboBox can’t bind to the Branches property using the standard {Binding Branches} syntax when it’s nested in something like a DataGrid (or ListBox or another items control) it can still get to the ViewModel object’s Branches property with a few minor changes.  The first way that this little dilemma can be solved is to write code that assigns the ViewModel object’s Branches collection to each ComboBox in the LoadingRow event of the DataGrid.  This works but who wants to write code when you don’t have to?  The second way is to create a mini ViewModel class that each row binds to that references the Branches collection.  That’s also an option, but there’s a “codeless” way to do it as well that’s quite easy.  If the ViewModel object is defined in the Resources section of the Page or UserControl you can get to it using its <strong>key</strong> name directly in XAML.  Here’s an example of defining a the ViewModel object declaratively in XAML: 

  <br />

  <br /></p>

<pre><span style="color:blue">&#60;</span><span style="color:#a31515">UserControl
    </span><span style="color:red">xmlns</span><span style="color:blue">=&#34;http://schemas.microsoft.com/winfx/2006/xaml/presentation&#34;
    </span><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">x</span><span style="color:blue">=&#34;http://schemas.microsoft.com/winfx/2006/xaml&#34;
    </span><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">vm</span><span style="color:blue">=&#34;clr-namespace:JobPlan.ViewModel;assembly=JobPlan.ViewModel&#34;
    </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Class</span><span style="color:blue">=&#34;JobPlan.View.UserControls.JobEdit&#34;&#62;
    &#60;</span><span style="color:#a31515">UserControl.Resources</span><span style="color:blue">&#62;
        <strong>&#60;</strong></span><strong><span style="color:#a31515">vm</span><span style="color:blue">:</span><span style="color:#a31515">ViewModel </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Key</span></strong><span style="color:blue"><strong>=&#34;ViewModel&#34; /&#62;</strong>
    &#60;/</span><span style="color:#a31515">UserControl.Resources</span><span style="color:blue">&#62;
    
    </span><span style="color:#a31515">...
    
</span><span style="color:blue">&#60;/</span><span style="color:#a31515">UserControl</span><span style="color:blue">&#62;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>
  <br />A ComboBox control within a DataGrid row (or nested in another type of control) can get to the ViewModel object’s Branches property using the following binding syntax:

  <br /></p>

<p></p>

<pre><span style="color:blue">&#60;</span><span style="color:#a31515">ComboBox 
    </span><span style="color:red">ItemsSource</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding Source={StaticResource ViewModel},Path=</span><span style="color:blue">Branches}&#34; 
</span><span style="color:blue">    </span><span style="color:red">DisplayMemberPath</span><span style="color:blue">=&#34;Title&#34;/&#62;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>
  <br />This XAML code tells the ComboBox control to access a statically defined resource with a key of “ViewModel” and then find a property of that resource object named Branches.  Pretty cool because you don’t have to write any C# or VB code at all by using this solution which is great if you’re dealing with a lot of nested ComboBox controls.  For developers that don’t like defining their ViewModel objects in XAML you can always use an intermediary ViewModel lookup object when things need to be as loosely coupled as possible.</p>

<p>Now that you see how nested objects can get to properties defined at higher levels I can cover the main point of this post.  Everything mentioned to this point works great out of the box especially if you want to avoid writing code as much as possible.  However, there’s one final problem where the StaticResource binding trick won’t work.  Take a look at the figure below to get an idea of the problem:
  <br /></p>

<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_47F7DE75.png"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_2AA286AB.png" width="758" height="550"></a> </p>

<p>
  <br />If the DataGrid and nested ComboBox controls are moved into a User Control you can’t use the StaticResource keyword to get to the ViewModel object.  Why?  Because the ViewModel object is defined in the Resources of the parent not in the actual User Control itself.  You could of course write code to get to it and then bind the data (writing code is always an option but can quickly get out of control in larger applications with a lot of controls), but what if you want to bind everything declaratively in XAML?  I don’t know of a built-in way to do that (and I’ve asked many people and have yet to hear an answer that didn’t involve mini ViewModels for each row or writing code) so I ended up creating a fairly simple solution to address the problem.  <br /></p>

<h2>The DataContextProxy Class
  <br /></h2>

<p>When I first tried to solve this problem I figured I could define the ViewModel again up in the Resources of the nested User Control.  Try this and you’ll quickly realize that it doesn’t work because it’ll cause a new ViewModel object to be created and two will now be in memory (one for the parent and one for the child User Control).  I needed a way to get to the DataContext from the parent but couldn’t do it using Resources it seemed…without writing code anyway (on a side note, I’m not opposed to writing code at all but the application I’m working on encounters the problem defined here frequently and the code started to get ridiculous).  I started thinking about how the ScriptManagerProxy class works in ASP.NET AJAX and played around with something I now call the “DataContextProxy”.  I needed a way to get to the parent’s DataContext and came up with the following class that does just that:</p>

<p> </p>

<pre><span style="color:blue">using </span>System;
<span style="color:blue">using </span>System.Windows;
<span style="color:blue">using </span>System.Windows.Controls;
<span style="color:blue">using </span>System.Windows.Data;

<span style="color:blue">namespace </span>JobPlan.Controls
{
    <span style="color:blue">public class </span><span style="color:#2b91af">DataContextProxy </span>: <span style="color:#2b91af">FrameworkElement
    </span>{
        <span style="color:blue">public </span>DataContextProxy()
        {
            <span style="color:blue">this</span>.Loaded += <span style="color:blue">new </span><span style="color:#2b91af">RoutedEventHandler</span>(DataContextProxy_Loaded);
        }

        <span style="color:blue">void </span>DataContextProxy_Loaded(<span style="color:blue">object </span>sender, <span style="color:#2b91af">RoutedEventArgs </span>e)
        {
            <span style="color:#2b91af">Binding </span>binding = <span style="color:blue">new </span><span style="color:#2b91af">Binding</span>();
            <span style="color:blue">if </span>(!<span style="color:#2b91af">String</span>.IsNullOrEmpty(BindingPropertyName))
            {
                binding.Path = <span style="color:blue">new </span><span style="color:#2b91af">PropertyPath</span>(BindingPropertyName);
            }
            binding.Source = <span style="color:blue">this</span>.DataContext;
            binding.Mode = BindingMode;
            <span style="color:blue">this</span>.SetBinding(<span style="color:#2b91af">DataContextProxy</span>.DataSourceProperty, binding);             
        }

        <span style="color:blue">public </span><span style="color:#2b91af">Object </span>DataSource
        {
            <span style="color:blue">get </span>{ <span style="color:blue">return </span>(<span style="color:#2b91af">Object</span>)GetValue(DataSourceProperty); }
            <span style="color:blue">set </span>{ SetValue(DataSourceProperty, <span style="color:blue">value</span>); }
        }

        <span style="color:blue">public static readonly </span><span style="color:#2b91af">DependencyProperty </span>DataSourceProperty =
            <span style="color:#2b91af">DependencyProperty</span>.Register(<span style="color:#a31515">&#34;DataSource&#34;</span>, <span style="color:blue">typeof</span>(<span style="color:#2b91af">Object</span>), <span style="color:blue">typeof</span>(<span style="color:#2b91af">DataContextProxy</span>), <span style="color:blue">null</span>);


        <span style="color:blue">public string </span>BindingPropertyName { <span style="color:blue">get</span>; <span style="color:blue">set</span>; }

        <span style="color:blue">public </span><span style="color:#2b91af">BindingMode </span>BindingMode { <span style="color:blue">get</span>; <span style="color:blue">set</span>; }
        
    }
}</pre>
<a href="http://11011.net/software/vspaste"></a>

<p>
  <br />The DataContextProxy class grabs the parent DataContext that flows down to the child User Control and binds it to a dependency property named DataSourceProperty.  The DataContextProxy object can be defined in the User Control’s Resource section as shown next:

  <br /></p>

<pre><span style="color:blue">&#60;</span><span style="color:#a31515">UserControl.Resources</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">controls</span><span style="color:blue">:</span><span style="color:#a31515">DataContextProxy </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Key</span><span style="color:blue">=&#34;DataContextProxy&#34; /&#62;
&#60;/</span><span style="color:#a31515">UserControl.Resources</span><span style="color:blue">&#62;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>
  <br />This allows the ViewModel defined in the parent to be accessed using XAML in the child User Control.  For example, a ComboBox control nested in a DataGrid can easily get to the Branches property using the following binding syntax:</p>

<p> </p>

<pre><span style="color:blue">&#60;</span><span style="color:#a31515">ComboBox 
    </span><span style="color:red">DisplayMemberPath</span><span style="color:blue">=&#34;Title&#34;
    </span><span style="color:red">ItemsSource</span><span style="color:blue">=&#34;{</span><span style="color:#a31515">Binding </span><span style="color:red">Source</span><span style="color:blue">={</span><span style="color:#a31515">StaticResource </span><span style="color:red">DataContextProxy</span><span style="color:blue">},</span><span style="color:red">Path</span><span style="color:blue">=DataSource.Branches}&#34; /&#62;</span></pre>
<a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a>

<p>
  <br />The binding syntax tells the ComboBox to bind to the statically defined DataContextProxy object’s DataSource property.  This allows the control to get to the original ViewModel object originally defined in the parent’s Resources section.  The syntax then says to bind to the Branches property of the ViewModel by using the Path property.</p>

<p>
  <br /></p>

<h2>Wrapping it Up
  <br /></h2>

<p>Silverlight has a lot of nice data binding features but there will be times when you’ll run into a few road blocks as you’re developing applications.  In this post you’ve seen different techniques that can be used when binding nested controls to data objects and seen how the DataContextProxy object can be used.  Hopefully this will help some of you out down the road when you’re working with a lot of nested controls.
  <br /></p>

<p> </p>

<p><a href="http://www.thewahlingroup.com/"><img border="0" alt="Logo" src="http://weblogs.asp.net/blogs/dwahlin/Logo_702D5F60.jpg" width="240" height="57"></a></p>

<p>For more information about <strong>onsite, online and video training, mentoring and consulting solutions</strong> for .NET, SharePoint or Silverlight please visit <a href="http://www.thewahlingroup.com/">http://www.thewahlingroup.com</a>.</p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7176078" width="1" height="1"><p class="read-more"><a href="http://zdima.net/blog/archives/4761">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<p>Data binding is one of my favorite features and something that I use a lot while building Silverlight applications.  Silverlight makes it really easy to bind data to different controls and move data from controls back into the original bound object without having to write any C# or VB code in many cases.  Here’s an example of binding a ComboBox control to an object that defines a property named Branches:    </p>
<pre><span >&lt;</span><span >ComboBox
    </span><span >ItemsSource</span><span >=&quot;{</span><span >Binding </span><span >Branches}&quot;
</span><span >    </span><span >DisplayMemberPath</span><span >=&quot;Title&quot;/&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>
  <br />This code binds the ItemsSource property to the DataContext object’s Branches property and displays the Branch object’s Title property in the ComboBox.  The DataContext could be assigned directly to the ComboBox through code or could be assigned to a parent object.  If it’s defined on a parent then all children have access to the object.  </p>
<p>This works great as long as the ComboBox has access to the Branches property as shown in Figure 1 below (note that the Page shown in the figure is a Silverlight Page class or User Control not a web page).  However, figure 2 demonstrates a problem that can occur as the ComboBox control’s DataContext is changed to something other than the ViewModel object that defines the Branches property.  In this example a DataGrid binds to the Jobs property of the ViewModel and each row’s DataContext is a Job type.  The Job type doesn’t have a Branches property (the ViewModel object does obviously) so the ComboBox no longer has access to it for data binding.  Or does it? </p>
<table border="0" cellspacing="5" cellpadding="8" width="934">
<tbody>
<tr bgcolor="#efefef">
<td valign="top" width="242" align="center"><strong></p>
<h3><strong>Figure 1 – All Systems go for binding</strong></h3>
<p>        </strong></td>
<td valign="top" width="675" align="center">
<h3><strong>Figure 2 – Houston, we have a problem</strong></h3>
</td>
</tr>
<tr>
<td valign="top" width="242" align="center"><a href="http://weblogs.asp.net/blogs/dwahlin/image_525928A2.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_5E7AA2C9.png" width="223" height="463"></a> </td>
<td valign="top" width="675" align="center"><a href="http://weblogs.asp.net/blogs/dwahlin/image_4B59761D.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_74810E5B.png" width="656" height="501"></a> </td>
</tr>
</tbody>
</table>
<p> </p>
<h2>Using a Static Resource When Binding Nested Controls</h2>
<p>
  <br />While the ComboBox can’t bind to the Branches property using the standard {Binding Branches} syntax when it’s nested in something like a DataGrid (or ListBox or another items control) it can still get to the ViewModel object’s Branches property with a few minor changes.  The first way that this little dilemma can be solved is to write code that assigns the ViewModel object’s Branches collection to each ComboBox in the LoadingRow event of the DataGrid.  This works but who wants to write code when you don’t have to?  The second way is to create a mini ViewModel class that each row binds to that references the Branches collection.  That’s also an option, but there’s a “codeless” way to do it as well that’s quite easy.  If the ViewModel object is defined in the Resources section of the Page or UserControl you can get to it using its <strong>key</strong> name directly in XAML.  Here’s an example of defining a the ViewModel object declaratively in XAML: </p>
<pre><span >&lt;</span><span >UserControl
    </span><span >xmlns</span><span >=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    </span><span >xmlns</span><span >:</span><span >x</span><span >=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    </span><span >xmlns</span><span >:</span><span >vm</span><span >=&quot;clr-namespace:JobPlan.ViewModel;assembly=JobPlan.ViewModel&quot;
    </span><span >x</span><span >:</span><span >Class</span><span >=&quot;JobPlan.View.UserControls.JobEdit&quot;&gt;
    &lt;</span><span >UserControl.Resources</span><span >&gt;
        <strong>&lt;</strong></span><strong><span >vm</span><span >:</span><span >ViewModel </span><span >x</span><span >:</span><span >Key</span></strong><span ><strong>=&quot;ViewModel&quot; /&gt;</strong>
    &lt;/</span><span >UserControl.Resources</span><span >&gt;

    </span><span >...

</span><span >&lt;/</span><span >UserControl</span><span >&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>
  <br />A ComboBox control within a DataGrid row (or nested in another type of control) can get to the ViewModel object’s Branches property using the following binding syntax:</p>
<p></p>
</p>
<pre><span >&lt;</span><span >ComboBox
    </span><span >ItemsSource</span><span >=&quot;{</span><span >Binding Source={StaticResource ViewModel},Path=</span><span >Branches}&quot;
</span><span >    </span><span >DisplayMemberPath</span><span >=&quot;Title&quot;/&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>
  <br />This XAML code tells the ComboBox control to access a statically defined resource with a key of “ViewModel” and then find a property of that resource object named Branches.  Pretty cool because you don’t have to write any C# or VB code at all by using this solution which is great if you’re dealing with a lot of nested ComboBox controls.  For developers that don’t like defining their ViewModel objects in XAML you can always use an intermediary ViewModel lookup object when things need to be as loosely coupled as possible.</p>
<p>Now that you see how nested objects can get to properties defined at higher levels I can cover the main point of this post.  Everything mentioned to this point works great out of the box especially if you want to avoid writing code as much as possible.  However, there’s one final problem where the StaticResource binding trick won’t work.  Take a look at the figure below to get an idea of the problem:<br />
  </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_47F7DE75.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_2AA286AB.png" width="758" height="550"></a> </p>
<p>
  <br />If the DataGrid and nested ComboBox controls are moved into a User Control you can’t use the StaticResource keyword to get to the ViewModel object.  Why?  Because the ViewModel object is defined in the Resources of the parent not in the actual User Control itself.  You could of course write code to get to it and then bind the data (writing code is always an option but can quickly get out of control in larger applications with a lot of controls), but what if you want to bind everything declaratively in XAML?  I don’t know of a built-in way to do that (and I’ve asked many people and have yet to hear an answer that didn’t involve mini ViewModels for each row or writing code) so I ended up creating a fairly simple solution to address the problem.  </p>
<h2>The DataContextProxy Class<br />
  <br /></h2>
<p>When I first tried to solve this problem I figured I could define the ViewModel again up in the Resources of the nested User Control.  Try this and you’ll quickly realize that it doesn’t work because it’ll cause a new ViewModel object to be created and two will now be in memory (one for the parent and one for the child User Control).  I needed a way to get to the DataContext from the parent but couldn’t do it using Resources it seemed…without writing code anyway (on a side note, I’m not opposed to writing code at all but the application I’m working on encounters the problem defined here frequently and the code started to get ridiculous).  I started thinking about how the ScriptManagerProxy class works in <a href="http://ASP.NET" class="autohyperlink" title="http://ASP.NET" target="_blank" rel="nofollow">ASP.NET</a> AJAX and played around with something I now call the “DataContextProxy”.  I needed a way to get to the parent’s DataContext and came up with the following class that does just that:</p>
<p> </p>
<pre><span >using </span>System;
<span >using </span>System.Windows;
<span >using </span>System.Windows.Controls;
<span >using </span>System.Windows.Data;

<span >namespace </span>JobPlan.Controls
{
    <span >public class </span><span >DataContextProxy </span>: <span >FrameworkElement
    </span>{
        <span >public </span>DataContextProxy()
        {
            <span >this</span>.Loaded += <span >new </span><span >RoutedEventHandler</span>(DataContextProxy_Loaded);
        }

        <span >void </span>DataContextProxy_Loaded(<span >object </span>sender, <span >RoutedEventArgs </span>e)
        {
            <span >Binding </span>binding = <span >new </span><span >Binding</span>();
            <span >if </span>(!<span >String</span>.IsNullOrEmpty(BindingPropertyName))
            {
                binding.Path = <span >new </span><span >PropertyPath</span>(BindingPropertyName);
            }
            binding.Source = <span >this</span>.DataContext;
            binding.Mode = BindingMode;
            <span >this</span>.SetBinding(<span >DataContextProxy</span>.DataSourceProperty, binding);
        }

        <span >public </span><span >Object </span>DataSource
        {
            <span >get </span>{ <span >return </span>(<span >Object</span>)GetValue(DataSourceProperty); }
            <span >set </span>{ SetValue(DataSourceProperty, <span >value</span>); }
        }

        <span >public static readonly </span><span >DependencyProperty </span>DataSourceProperty =
            <span >DependencyProperty</span>.Register(<span >&quot;DataSource&quot;</span>, <span >typeof</span>(<span >Object</span>), <span >typeof</span>(<span >DataContextProxy</span>), <span >null</span>);

        <span >public string </span>BindingPropertyName { <span >get</span>; <span >set</span>; }

        <span >public </span><span >BindingMode </span>BindingMode { <span >get</span>; <span >set</span>; }

    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>
  <br />The DataContextProxy class grabs the parent DataContext that flows down to the child User Control and binds it to a dependency property named DataSourceProperty.  The DataContextProxy object can be defined in the User Control’s Resource section as shown next:</p>
<p></p>
<pre><span >&lt;</span><span >UserControl.Resources</span><span >&gt;
    &lt;</span><span >controls</span><span >:</span><span >DataContextProxy </span><span >x</span><span >:</span><span >Key</span><span >=&quot;DataContextProxy&quot; /&gt;
&lt;/</span><span >UserControl.Resources</span><span >&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>
  <br />This allows the ViewModel defined in the parent to be accessed using XAML in the child User Control.  For example, a ComboBox control nested in a DataGrid can easily get to the Branches property using the following binding syntax:</p>
<p> </p>
<pre><span >&lt;</span><span >ComboBox
    </span><span >DisplayMemberPath</span><span >=&quot;Title&quot;
    </span><span >ItemsSource</span><span >=&quot;{</span><span >Binding </span><span >Source</span><span >={</span><span >StaticResource </span><span >DataContextProxy</span><span >},</span><span >Path</span><span >=DataSource.Branches}&quot; /&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>
  <br />The binding syntax tells the ComboBox to bind to the statically defined DataContextProxy object’s DataSource property.  This allows the control to get to the original ViewModel object originally defined in the parent’s Resources section.  The syntax then says to bind to the Branches property of the ViewModel by using the Path property.</p>
<p>
  </p>
<h2>Wrapping it Up<br />
  <br /></h2>
<p>Silverlight has a lot of nice data binding features but there will be times when you’ll run into a few road blocks as you’re developing applications.  In this post you’ve seen different techniques that can be used when binding nested controls to data objects and seen how the DataContextProxy object can be used.  Hopefully this will help some of you out down the road when you’re working with a lot of nested controls.<br />
  </p>
<p> </p>
<p><a href="http://www.thewahlingroup.com/"><img title="Logo" border="0" alt="Logo" src="http://weblogs.asp.net/blogs/dwahlin/Logo_702D5F60.jpg" width="240" height="57"></a></p>
<p>For more information about <strong>onsite, online and video training, mentoring and consulting solutions</strong> for .NET, SharePoint or Silverlight please visit <a href="http://www.thewahlingroup.com/">www.thewahlingroup.com</a>.</p>
<p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7176078" width="1" height="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/4761/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building Line of Business Applications with Silverlight 3 – Pros and Cons</title>
		<link>http://zdima.net/blog/archives/4667</link>
		<comments>http://zdima.net/blog/archives/4667#comments</comments>
		<pubDate>Tue, 18 Aug 2009 07:06:00 +0000</pubDate>
		<dc:creator>dwahlin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=4667</guid>
		<description><![CDATA[<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_31F38968.png"><img style="margin:0px 15px 10px 0px" border="0" alt="image" align="left" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_460CA5F1.png" width="125" height="131"></a>I’ve been hearing a lot of people talk about how Silverlight 3 can or can’t do various things lately throughout the blogosphere and <a href="http://www.twitter.com/">Twitter</a>.  The sad part is that some of the people giving their two cents about what Silverlight can’t do haven’t built a “real world” application so I’m not sure how their opinion carries any weight (I know because I’ve asked a few of them). Their list of cons are typically based on what they heard on Twitter or various rumors floating around.  As with any technology there are pros and cons and Silverlight is no exception.  The goal of this post is to talk through some of the pros and cons I’ve personally encountered while building a “real world”, enterprise-scale timesheet and job management application for a large electrical contracting company.  I’ll point out what has worked really well and what hasn’t so that people looking to move applications to Silverlight 3 can get an honest assessment on what can be done and what can’t be done.</p>
<p>The application my company is building has a lot of different screens (30+), integrates with the backend database using WCF, uses reporting services for reports and leverages many of the key features Silverlight 3 has to offer.  The existing application used by the client was written using Access Forms and is being ported to Silverlight 3 along with a bunch of new functionality. </p>
<p>Let’s start by going through what I personally feel are the pros and cons that Silverlight brings to the table for Line of Business (LOB) applications.</p>
<h3>Silverlight 3 Pros</h3>
<p>Here are some of the pros I’ve found as I’ve worked through the application:</p>
<ol>
<li><strong>Excellent data binding support</strong> – my favorite feature.  This changes how you look at building applications and allows you to write data-centric code instead of control-centric code as with normal Web applications.  There’s a lot I could cover here but I wrote up a post awhile back that gives additional details about what I like.  <a href="http://weblogs.asp.net/dwahlin/archive/2009/06/20/control-oriented-vs-data-oriented-programming-in-silverlight.aspx">Read it here</a>.</li>
<li><strong>Server code and client code can written in the same language</strong>.  Business and validation rules can be shared between the client and server code base which definitely makes applications more maintainable into the future.</li>
<li><strong>A rich set of controls</strong> – I really like the controls available with the Silverlight SDK as well as those in the <a href="http://www.codeplex.com/silverlight">Silverlight toolkit</a>.  There are a few (mentioned below) that can test your patience when you’re building a more involved application and not a simple demo.</li>
<li><strong>Support for just about any type of animation or effect you want</strong>.  Don’t need that in a LOB app?  I beg to differ.  You can get quite creative with how data is displayed with Silverlight and not be limited to simple slide, sizing or opacity animations.  I’ll show an example of what I call the “card flow” interface later in this post and show how it allows managers to get to timecards faster and easier than before.</li>
<li><strong>Excellent designer support</strong> through Expression Blend 3 – Visual Studio 2008 is great for coding but doesn’t provide any design-time features for Silverlight 3.  Not a big deal….you can use <a href="http://www.microsoft.com/expression/products/Blend_Overview.aspx">Expression Blend 3</a> which provides a great interface for designing your applications.  The new SketchFlow application can even be used to prototype applications upfront and get customer feedback more quickly and easily than in the past.</li>
<li><strong>Easy to integrate distributed data</strong> using WCF, ASMX, REST, ADO.NET Data Services, .NET RIA Services, etc.  The application that I’m working on leverages WCF as well as some <a href="http://weblogs.asp.net/dwahlin/archive/2009/07/12/simplifying-the-process-of-calling-a-wcf-service-from-silverlight-or-any-net-application.aspx">dynamic code</a> on the client-side to make calls to the service.  It works great and FaultExceptions can even be handled now with Silverlight 3.</li>
<li><strong>Desktop-style application</strong> with a web deployment model – Get the responsiveness of a desktop application that can be deployed right through the browser and even run on Macs.</li>
<li><strong>Support for styling of controls</strong>.  Silverlight 3 now allows styles to be changed on the fly and styles to be based on other styles.  If you don’t like how a control currently looks you can completely change it by using styles and control templates.  </li>
<li><strong>Out of browser support</strong> – This was a key reason why my client choose Silverlight 3.  They have a lot of remote workers that don’t always have access to the Internet and needed to be able to enter timesheets even when disconnected and then sync them later once a given employee has connectivity.</li>
<li><strong>Support for behaviors</strong>.  <a href="http://blogs.msdn.com/expression/archive/2009/03/30/behaviors-under-the-hood-api-details-and-constraining-the-type.aspx">Behaviors</a> are very, very useful in Silverlight applications.  I needed to add mouse wheel scroll capabilities to a ScrollViewer control to simplify scrolling in a screen and did it within minutes by using a behavior (thanks to <a href="http://silverlightplayground.boschin.it/post/2009/07/10/Silverlight-30-RTW-An-universal-MouseWheelScrolling-behavior.aspx">Andrea Boschin</a> who created the behavior).</li>
<li><strong>Manipulate pixels using WriteableBitmap</strong>.  This can be used to create some <a href="http://blois.us/blog/2009/07/explode.html">very cool effects</a> (some which may not be applicable to LOB applications…but they’re still cool).  I’m using it mainly to fill the printing hole mentioned below.</li>
<li><strong>Support for storing local data through isolated storage – </strong>By using isolated storage you can cache data, store data when no network connectivity is available plus more.</li>
<li><strong>Support for navigation</strong> – Silverlight 3 has a new navigation application template in Visual Studio that makes creating an application with multiple pages quite easy.  Each “page” can be linked to directly through deep linking and has built-in support for history.  If the client hits the back or forward button in the browser they’re taken to the appropriate Silverlight application page.  The navigation framework allows code to be placed into separate pages (or user controls) and then loaded as a particular link or menu item is clicked.  It’s a great feature that can really reduce the amount of code you have to write especially compared to Silverlight 2.</li></ol>
<h3>Silverlight 3 Cons</h3>
<p>So everything’s all peachy right? Both the client and I are very happy with how things are going with the application but there have been some challenges along the way.  At the beginning of this post I said I’d mention the cons as well and I’m going to be brutally honest here with some of the areas where Silverlight 3 is missing the mark when it comes to Line of Business applications.</p>
<ol>
<li><strong>No printing support</strong>.  Microsoft is working hard on this for future versions of Silverlight but if you can’t wait until then it’s definitely something to be aware of.  We knew about this going into the project so it was supposed to be a non issue since we could pop-up HTML overlays or open new browser windows that could be printed.  But, for one particular screen the lack of printing support is proving to be a challenge since it turns out the end user always prints the screen as they’re doing payroll work and the screen is quite complex.  I’ve come up with a work around using Silverlight 3’s WriteableBitmap but am currently sending bytes up to the server, converting them into a JPEG and then displaying the image in the browser.  Definitely a hack solution.  We’re now looking at generating dynamic Excel files on the fly at the client with a snapshot image of the Silverlight data since Excel will print the image properly and the browser doesn’t (still researching this option). If that doesn’t work we’ll just use reporting services to generate the same screen…not my preference though.</li>
<li><strong>Binding data to controls such as a ComboBox</strong> that is nested in other controls is harder than it should be.  I use a lot of ComboBox controls that are nested in DataGrid or ListBox rows in the application.  While I have it working fine now (after beating my head against the monitor a few times), the ComboBox control itself really needs a SelectedValue and ValueMember property for some situations and a way to more easily bind its ItemsSource to collections that may be defined outside of the current DataContext. All of this can be done via code but if you want to handle the majority of it declaratively in XAML it can be challenging in some cases especially once you start breaking parts of a page into user controls.  I ended up enhancing some code <a href="http://www.lhotka.net/weblog/CommentView,guid,f3353b7c-a1b5-41f2-a9bf-00f0c4e6a999.aspx">Rocky Lhotka</a> blogged about and created my own ComboBox control that simplifies things a lot.</li>
<li><strong>Lack of built-in support for commanding</strong>.  What’s “commanding”?  In a nutshell it’s the ability to call a method within an object directly from XAML as an event fires instead of going through a code-behind file.  For example, when a button is clicked the click event can call directly into a ViewModel object that acts on the event.  By using commanding you can make your applications more testable. Frameworks such as <a href="http://www.codeplex.com/CompositeWPF">Prism</a> (and many others that have popped up) support simple button commanding and provide a code framework that can be used to build other types of commands.  The application I’m working on handles just about every event in the book (click, mouseenter, mouseleave, rowloaded, lostfocus, gotfocus, plus others) though and writing custom code just to handle events got old (so we simplified things and handle the event in the code-behind which notifies the ViewModel via events).  If you want to handle events directly in the code-behind file this is a non-issue for you, but if you want to handle them in another class it can be more challenging than it should be.</li>
<li><strong>Learning curve</strong> – There is certainly a learning curve associated with building Silverlight applications especially if you’re coming from building standard Web applications.  However, I think that’s the case with any technology.  I had already built several demo applications with Silverlight, co-authored a book and several articles on it and still ran into a few challenges with architecture choices along the way (we’re following the MVVM pattern).  I think it boils down to experience though so I list this one simply so that people know they will spend some time learning.  If you’re one of those people who doesn’t like to learn new things then Silverlight probably isn’t for you.  If you enjoy learning new things then I think you’ll love Silverlight once you get the hang of it.</li>
<li><strong>No built-in support for displaying Reporting Services reports</strong> <strong>within Silverlight</strong> – This isn’t a huge issue in my opinion since a report can be brought up in a separate browser window or displayed using an HTML overlay.  However, if you need to display the report directly in Silverlight there isn’t any built-in way to do that in Silverlight 3.  3rd party vendors to the rescue though.  <a href="http://perpetuumsoft.com/Product.aspx?lang=en&#38;pid=116">Perpetuum Software</a> now has a product that can integrate reports directly into Silverlight.</li>
<li><strong>The client has to have the Silverlight plugin installed</strong>.  I personally don’t view this as much of a con for internal enterprise LOB applications since it’s fairly easy for a PC manager to push out Silverlight to client PCs in many environments.  If the application will be run externally then installation of the plugin on each client has to be considered though. </li>
<li><strong>Sharing service types between proxy objects</strong> <strong>needs to be enhanced</strong> - When the project was initially started I wanted to use ADO.NET Data Services for some things and WCF for others.  The problem is that if both types of services reference the same type (such as Customer) then both generated proxy objects will contain a copy of that type which ultimately bloats the XAP size and leads to having to reference types by namespace down in the code versus a using statement at the top.  Although proxies can share code libraries from other projects (that&#39;s an option in the proxy generation wizard), my Model entities use .NET language features not available in Silverlight class libraries so type sharing won&#39;t work there.  It&#39;s something to keep in mind as you decide how you&#39;ll get data into your application.<br /></li></ol>
<p>There are definitely more pros than I’ve listed and probably a few more cons although I honestly can’t think of many more that I’ve had to deal with.  The bottom line is that all of the pieces are there (aside from printing) to build powerful Line of Business applications that are built using existing .NET languages.  You can make the applications look however you’d like and not have to worry if they’ll look good across different browsers.  Here’s a picture of a payroll screen in the early stages of development:</p>
<p><br /><a href="http://weblogs.asp.net/blogs/dwahlin/Makeover_504BDA92.jpg"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="Makeover" src="http://weblogs.asp.net/blogs/dwahlin/Makeover_thumb_2E800201.jpg" width="802" height="523"></a> </p>
<p><br />Here’s what the screen looks like after applying a few styles to the controls and adding support for things like inline editing of data:</p>
<p><br /><a href="http://weblogs.asp.net/blogs/dwahlin/image_65E6132F.png"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_4BA5AA0B.png" width="804" height="464"></a> </p>
<p><br />Some of the more “fun” features in Silverlight 3 can also be put to good use in Line of Business applications.  I needed to create a way for warehouse managers to easily manage multiple time cards for employees.  I ended up going with what I call a “card flow” interface (similar to cover flow in iTunes) to display the time cards.  The end user can use the mouse wheel to quickly navigate through different cards.  The selected card will slide to the middle with a cool animation and the others are angled using perspective 3D.  Here’s what the “card flow” interface looks like (I need to give credit to <a href="http://www.cynergysystems.com/blogs/page/josefajardo?entry=coverflow_built_using_silverlight_3">Jose Fajardo</a> for blogging about the concept): <br /></p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_7BEC7EC1.png"><img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_19EA8CB6.png" width="806" height="549"></a> </p>
<p> </p>
<h3>To Wrap It Up</h3>
<p>So is Silverlight 3 ready for prime time, enterprise level Line of Business applications?  Having worked with the framework nearly every day for the past 3 months in a “real world” scenario my short answer is a big “YES”!  I don’t say this because I’ve been drinking the Kool-Aid though.  Anyone who knows me understands that I use what I feel works best for a given application (unless the client wants something specific of course).  I truly enjoy working with the framework and think it can do a lot of powerful things.</p>
<p>Every company is unique though so the answer really depends on what features your application needs.  Our previous client’s application was built using ASP.NET MVC and jQuery and it did everything they wanted it to do (I really like ASP.NET MVC and jQuery by the way).  However, Silverlight provides a more consistent way to develop enterprise applications that doesn’t require learning JavaScript, additional libraries like jQuery, CSS, HTML and other Web technologies.  With Silverlight you can write code using your favorite .NET language on both the client and server, debug applications like any normal .NET application, bind data in flexible ways, retrieve data from remote services, animate objects as needed, round corners and work with gradients without ever creating a .gif, .jpg or .png and have a ton of controls right at your finger tips.  I’m a big fan.</p>
<p><a href="http://www.thewahlingroup.com/"><img border="0" alt="Logo" src="http://weblogs.asp.net/blogs/dwahlin/Logo_702D5F60.jpg" width="240" height="57"></a></p>
<p>For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit <a href="http://www.thewahlingroup.com/">http://www.thewahlingroup.com</a>.</p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7172146" width="1" height="1"><p class="read-more"><a href="http://zdima.net/blog/archives/4667">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_31F38968.png"><img  title="image" border="0" alt="image" align="left" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_460CA5F1.png" width="125" height="131"></a>I’ve been hearing a lot of people talk about how Silverlight 3 can or can’t do various things lately throughout the blogosphere and <a href="http://www.twitter.com/">Twitter</a>.  The sad part is that some of the people giving their two cents about what Silverlight can’t do haven’t built a “real world” application so I’m not sure how their opinion carries any weight (I know because I’ve asked a few of them). Their list of cons are typically based on what they heard on Twitter or various rumors floating around.  As with any technology there are pros and cons and Silverlight is no exception.  The goal of this post is to talk through some of the pros and cons I’ve personally encountered while building a “real world”, enterprise-scale timesheet and job management application for a large electrical contracting company.  I’ll point out what has worked really well and what hasn’t so that people looking to move applications to Silverlight 3 can get an honest assessment on what can be done and what can’t be done.</p>
<p>The application my company is building has a lot of different screens (30+), integrates with the backend database using WCF, uses reporting services for reports and leverages many of the key features Silverlight 3 has to offer.  The existing application used by the client was written using Access Forms and is being ported to Silverlight 3 along with a bunch of new functionality. </p>
<p>Let’s start by going through what I personally feel are the pros and cons that Silverlight brings to the table for Line of Business (LOB) applications.</p>
<h3>Silverlight 3 Pros</h3>
<p>Here are some of the pros I’ve found as I’ve worked through the application:</p>
<ol>
<li><strong>Excellent data binding support</strong> – my favorite feature.  This changes how you look at building applications and allows you to write data-centric code instead of control-centric code as with normal Web applications.  There’s a lot I could cover here but I wrote up a post awhile back that gives additional details about what I like.  <a href="http://weblogs.asp.net/dwahlin/archive/2009/06/20/control-oriented-vs-data-oriented-programming-in-silverlight.aspx">Read it here</a>.</li>
<li><strong>Server code and client code can written in the same language</strong>.  Business and validation rules can be shared between the client and server code base which definitely makes applications more maintainable into the future.</li>
<li><strong>A rich set of controls</strong> – I really like the controls available with the Silverlight SDK as well as those in the <a href="http://www.codeplex.com/silverlight">Silverlight toolkit</a>.  There are a few (mentioned below) that can test your patience when you’re building a more involved application and not a simple demo.</li>
<li><strong>Support for just about any type of animation or effect you want</strong>.  Don’t need that in a LOB app?  I beg to differ.  You can get quite creative with how data is displayed with Silverlight and not be limited to simple slide, sizing or opacity animations.  I’ll show an example of what I call the “card flow” interface later in this post and show how it allows managers to get to timecards faster and easier than before.</li>
<li><strong>Excellent designer support</strong> through Expression Blend 3 – Visual Studio 2008 is great for coding but doesn’t provide any design-time features for Silverlight 3.  Not a big deal….you can use <a href="http://www.microsoft.com/expression/products/Blend_Overview.aspx">Expression Blend 3</a> which provides a great interface for designing your applications.  The new SketchFlow application can even be used to prototype applications upfront and get customer feedback more quickly and easily than in the past.</li>
<li><strong>Easy to integrate distributed data</strong> using WCF, ASMX, REST, <a href="http://ADO.NET" class="autohyperlink" title="http://ADO.NET" target="_blank" rel="nofollow">ADO.NET</a> Data Services, .NET RIA Services, etc.  The application that I’m working on leverages WCF as well as some <a href="http://weblogs.asp.net/dwahlin/archive/2009/07/12/simplifying-the-process-of-calling-a-wcf-service-from-silverlight-or-any-net-application.aspx">dynamic code</a> on the client-side to make calls to the service.  It works great and FaultExceptions can even be handled now with Silverlight 3.</li>
<li><strong>Desktop-style application</strong> with a web deployment model – Get the responsiveness of a desktop application that can be deployed right through the browser and even run on Macs.</li>
<li><strong>Support for styling of controls</strong>.  Silverlight 3 now allows styles to be changed on the fly and styles to be based on other styles.  If you don’t like how a control currently looks you can completely change it by using styles and control templates.  </li>
<li><strong>Out of browser support</strong> – This was a key reason why my client choose Silverlight 3.  They have a lot of remote workers that don’t always have access to the Internet and needed to be able to enter timesheets even when disconnected and then sync them later once a given employee has connectivity.</li>
<li><strong>Support for behaviors</strong>.  <a href="http://blogs.msdn.com/expression/archive/2009/03/30/behaviors-under-the-hood-api-details-and-constraining-the-type.aspx">Behaviors</a> are very, very useful in Silverlight applications.  I needed to add mouse wheel scroll capabilities to a ScrollViewer control to simplify scrolling in a screen and did it within minutes by using a behavior (thanks to <a href="http://silverlightplayground.boschin.it/post/2009/07/10/Silverlight-30-RTW-An-universal-MouseWheelScrolling-behavior.aspx">Andrea Boschin</a> who created the behavior).</li>
<li><strong>Manipulate pixels using WriteableBitmap</strong>.  This can be used to create some <a href="http://blois.us/blog/2009/07/explode.html">very cool effects</a> (some which may not be applicable to LOB applications…but they’re still cool).  I’m using it mainly to fill the printing hole mentioned below.</li>
<li><strong>Support for storing local data through isolated storage – </strong>By using isolated storage you can cache data, store data when no network connectivity is available plus more.</li>
<li><strong>Support for navigation</strong> – Silverlight 3 has a new navigation application template in Visual Studio that makes creating an application with multiple pages quite easy.  Each “page” can be linked to directly through deep linking and has built-in support for history.  If the client hits the back or forward button in the browser they’re taken to the appropriate Silverlight application page.  The navigation framework allows code to be placed into separate pages (or user controls) and then loaded as a particular link or menu item is clicked.  It’s a great feature that can really reduce the amount of code you have to write especially compared to Silverlight 2.</li>
</ol>
<h3>Silverlight 3 Cons</h3>
<p>So everything’s all peachy right? Both the client and I are very happy with how things are going with the application but there have been some challenges along the way.  At the beginning of this post I said I’d mention the cons as well and I’m going to be brutally honest here with some of the areas where Silverlight 3 is missing the mark when it comes to Line of Business applications.</p>
<ol>
<li><strong>No printing support</strong>.  Microsoft is working hard on this for future versions of Silverlight but if you can’t wait until then it’s definitely something to be aware of.  We knew about this going into the project so it was supposed to be a non issue since we could pop-up HTML overlays or open new browser windows that could be printed.  But, for one particular screen the lack of printing support is proving to be a challenge since it turns out the end user always prints the screen as they’re doing payroll work and the screen is quite complex.  I’ve come up with a work around using Silverlight 3’s WriteableBitmap but am currently sending bytes up to the server, converting them into a JPEG and then displaying the image in the browser.  Definitely a hack solution.  We’re now looking at generating dynamic Excel files on the fly at the client with a snapshot image of the Silverlight data since Excel will print the image properly and the browser doesn’t (still researching this option). If that doesn’t work we’ll just use reporting services to generate the same screen…not my preference though.</li>
<li><strong>Binding data to controls such as a ComboBox</strong> that is nested in other controls is harder than it should be.  I use a lot of ComboBox controls that are nested in DataGrid or ListBox rows in the application.  While I have it working fine now (after beating my head against the monitor a few times), the ComboBox control itself really needs a SelectedValue and ValueMember property for some situations and a way to more easily bind its ItemsSource to collections that may be defined outside of the current DataContext. All of this can be done via code but if you want to handle the majority of it declaratively in XAML it can be challenging in some cases especially once you start breaking parts of a page into user controls.  I ended up enhancing some code <a href="http://www.lhotka.net/weblog/CommentView,guid,f3353b7c-a1b5-41f2-a9bf-00f0c4e6a999.aspx">Rocky Lhotka</a> blogged about and created my own ComboBox control that simplifies things a lot.</li>
<li><strong>Lack of built-in support for commanding</strong>.  What’s “commanding”?  In a nutshell it’s the ability to call a method within an object directly from XAML as an event fires instead of going through a code-behind file.  For example, when a button is clicked the click event can call directly into a ViewModel object that acts on the event.  By using commanding you can make your applications more testable. Frameworks such as <a href="http://www.codeplex.com/CompositeWPF">Prism</a> (and many others that have popped up) support simple button commanding and provide a code framework that can be used to build other types of commands.  The application I’m working on handles just about every event in the book (click, mouseenter, mouseleave, rowloaded, lostfocus, gotfocus, plus others) though and writing custom code just to handle events got old (so we simplified things and handle the event in the code-behind which notifies the ViewModel via events).  If you want to handle events directly in the code-behind file this is a non-issue for you, but if you want to handle them in another class it can be more challenging than it should be.</li>
<li><strong>Learning curve</strong> – There is certainly a learning curve associated with building Silverlight applications especially if you’re coming from building standard Web applications.  However, I think that’s the case with any technology.  I had already built several demo applications with Silverlight, co-authored a book and several articles on it and still ran into a few challenges with architecture choices along the way (we’re following the MVVM pattern).  I think it boils down to experience though so I list this one simply so that people know they will spend some time learning.  If you’re one of those people who doesn’t like to learn new things then Silverlight probably isn’t for you.  If you enjoy learning new things then I think you’ll love Silverlight once you get the hang of it.</li>
<li><strong>No built-in support for displaying Reporting Services reports</strong> <strong>within Silverlight</strong> – This isn’t a huge issue in my opinion since a report can be brought up in a separate browser window or displayed using an HTML overlay.  However, if you need to display the report directly in Silverlight there isn’t any built-in way to do that in Silverlight 3.  3rd party vendors to the rescue though.  <a href="http://perpetuumsoft.com/Product.aspx?lang=en&amp;pid=116">Perpetuum Software</a> now has a product that can integrate reports directly into Silverlight.</li>
<li><strong>The client has to have the Silverlight plugin installed</strong>.  I personally don’t view this as much of a con for internal enterprise LOB applications since it’s fairly easy for a PC manager to push out Silverlight to client PCs in many environments.  If the application will be run externally then installation of the plugin on each client has to be considered though. </li>
<li><strong>Sharing service types between proxy objects</strong> <strong>needs to be enhanced</strong> &#8211; When the project was initially started I wanted to use <a href="http://ADO.NET" class="autohyperlink" title="http://ADO.NET" target="_blank" rel="nofollow">ADO.NET</a> Data Services for some things and WCF for others.  The problem is that if both types of services reference the same type (such as Customer) then both generated proxy objects will contain a copy of that type which ultimately bloats the XAP size and leads to having to reference types by namespace down in the code versus a using statement at the top.  Although proxies can share code libraries from other projects (that&#39;s an option in the proxy generation wizard), my Model entities use .NET language features not available in Silverlight class libraries so type sharing won&#39;t work there.  It&#39;s something to keep in mind as you decide how you&#39;ll get data into your application.</li>
</ol>
<p>There are definitely more pros than I’ve listed and probably a few more cons although I honestly can’t think of many more that I’ve had to deal with.  The bottom line is that all of the pieces are there (aside from printing) to build powerful Line of Business applications that are built using existing .NET languages.  You can make the applications look however you’d like and not have to worry if they’ll look good across different browsers.  Here’s a picture of a payroll screen in the early stages of development:</p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/Makeover_504BDA92.jpg"><img  title="Makeover" border="0" alt="Makeover" src="http://weblogs.asp.net/blogs/dwahlin/Makeover_thumb_2E800201.jpg" width="802" height="523"></a> </p>
<p>Here’s what the screen looks like after applying a few styles to the controls and adding support for things like inline editing of data:</p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_65E6132F.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_4BA5AA0B.png" width="804" height="464"></a> </p>
<p>Some of the more “fun” features in Silverlight 3 can also be put to good use in Line of Business applications.  I needed to create a way for warehouse managers to easily manage multiple time cards for employees.  I ended up going with what I call a “card flow” interface (similar to cover flow in iTunes) to display the time cards.  The end user can use the mouse wheel to quickly navigate through different cards.  The selected card will slide to the middle with a cool animation and the others are angled using perspective 3D.  Here’s what the “card flow” interface looks like (I need to give credit to <a href="http://www.cynergysystems.com/blogs/page/josefajardo?entry=coverflow_built_using_silverlight_3">Jose Fajardo</a> for blogging about the concept): </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_7BEC7EC1.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_19EA8CB6.png" width="806" height="549"></a> </p>
<p> </p>
<h3>To Wrap It Up</h3>
<p>So is Silverlight 3 ready for prime time, enterprise level Line of Business applications?  Having worked with the framework nearly every day for the past 3 months in a “real world” scenario my short answer is a big “YES”!  I don’t say this because I’ve been drinking the Kool-Aid though.  Anyone who knows me understands that I use what I feel works best for a given application (unless the client wants something specific of course).  I truly enjoy working with the framework and think it can do a lot of powerful things.</p>
<p>Every company is unique though so the answer really depends on what features your application needs.  Our previous client’s application was built using <a href="http://ASP.NET" class="autohyperlink" title="http://ASP.NET" target="_blank" rel="nofollow">ASP.NET</a> MVC and jQuery and it did everything they wanted it to do (I really like <a href="http://ASP.NET" class="autohyperlink" title="http://ASP.NET" target="_blank" rel="nofollow">ASP.NET</a> MVC and jQuery by the way).  However, Silverlight provides a more consistent way to develop enterprise applications that doesn’t require learning JavaScript, additional libraries like jQuery, CSS, HTML and other Web technologies.  With Silverlight you can write code using your favorite .NET language on both the client and server, debug applications like any normal .NET application, bind data in flexible ways, retrieve data from remote services, animate objects as needed, round corners and work with gradients without ever creating a .gif, .jpg or .png and have a ton of controls right at your finger tips.  I’m a big fan.</p>
<p><a href="http://www.thewahlingroup.com/"><img title="Logo" border="0" alt="Logo" src="http://weblogs.asp.net/blogs/dwahlin/Logo_702D5F60.jpg" width="240" height="57"></a></p>
<p>For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit <a href="http://www.thewahlingroup.com/">www.thewahlingroup.com</a>.</p>
<p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7172146" width="1" height="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/4667/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>So What’s a Silverlight Value Converter Anyway?</title>
		<link>http://zdima.net/blog/archives/4556</link>
		<comments>http://zdima.net/blog/archives/4556#comments</comments>
		<pubDate>Sun, 16 Aug 2009 04:16:00 +0000</pubDate>
		<dc:creator>dwahlin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=4556</guid>
		<description><![CDATA[<p>Silverlight has an excellent data binding engine that allows data to be bound through XAML or programmatically with code.  My number one reason for using Silverlight on client projects is the data binding support.  Once you get into it and understand how it works it can save a lot of time when building applications.</p>
<p>When you’re binding data to controls there will be times when the data needs to be modified or tweaked some on the way into a control or as the data leaves a control and goes back to the source property (during a TwoWay binding for example).  Sure, you can always write code to change a given value, but in many cases it’s much easier to write a simple value converter instead that can be re-used.  In this post I’ll walk through creating a value converter and then show the code for a few of the value converters I find myself using fairly frequently. <br /></p>
<h3>Creating a Value Converter</h3>
<p>Let’s look at a simple example of creating a value converter to get started.  Many applications work with DateTime objects but don’t want the time displayed or want the date formatted a specific way.  If you bind a DateTime property to something like a TextBlock in Silverlight you’ll get the standard output based upon the current culture: <br /></p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/clip_image00211_140D92B9.jpg"><img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px" border="0" alt="clip_image002[11]" src="http://weblogs.asp.net/blogs/dwahlin/clip_image00211_thumb_0BA9BD62.jpg" width="211" height="179"></a> <br /><br />In the case of a birthday you want to show the date but don’t need the time of course.  You’d want something like the following: <br /></p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/clip_image00213_4690F02B.jpg"><img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px" border="0" alt="clip_image002[13]" src="http://weblogs.asp.net/blogs/dwahlin/clip_image00213_thumb_45B88A41.jpg" width="176" height="180"></a></p>
<p>Although a separate property could be created in the source object being bound that handles formatting the date, a value converter can be created and re-used over and over anytime a specific date format needs to be created.  To create a value converter you’ll need to add a Silverlight class into your project and implement an interface named IValueConverter (located in the System.Windows.Data namespace).  This interface defines two members including Convert and ConvertBack. Convert is used to modify data as its bound from the source object to the control. ConvertBack works the other way. As a user changes data in a control such as a TextBox the data can be &#34;converted back&#34; to the original data type in the source object by using ConvertBack. </p>
<p>Both Convert and ConvertBack accept the same parameters including the data being bound, the type of the data being bound, any parameter data passed in that can be used in the data conversion process as well as the target culture that the entire process is running under (English, Spanish, French, etc.). Here's what the method signatures look like: <br /></p>
<p><font face="Courier New">object Convert(object value, Type targetType, object parameter, CultureInfo culture); <br />object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);</font> <br /></p>
<p>Once IValueConverter is added to your class you can right-click it in Visual Studio and select <em>Implement Interface</em> from the menu to automatically fill in the Convert and ConvertBack methods. If you&#39;re using Visual Basic you can simply hit enter after the interface name to accomplish the same thing.  Here’s an example of a date value converter that allows dates to be formatted: <br /></p><pre><span style="color:blue">using </span>System;
<span style="color:blue">using </span>System.Windows;
<span style="color:blue">using </span>System.Windows.Data;
<span style="color:blue">using </span>System.Globalization;

<span style="color:blue">namespace </span>View.Converters
{
   <span style="color:blue">public class </span><span style="color:#2b91af">DateConverter </span>: <span style="color:#2b91af">IValueConverter
    </span>{

        <span style="color:blue">#region </span>IValueConverter Members

        <span style="background:#e2e2e2;color:#008200">//Called when binding from an object property to a control property
</span>        <span style="color:blue">public object </span>Convert(<span style="color:blue">object </span>value, <span style="color:#2b91af">Type </span>targetType, <span style="color:blue">object </span>parameter, System.Globalization.<span style="color:#2b91af">CultureInfo </span>culture)
        {
            <span style="color:blue">if </span>(value == <span style="color:blue">null </span>&#124;&#124; (<span style="color:#2b91af">DateTime</span>)value == <span style="color:#2b91af">DateTime</span>.MinValue) <span style="color:blue">return null</span>;
            <span style="color:#2b91af">DateTime </span>dt = (<span style="color:#2b91af">DateTime</span>)value;
            <span style="color:blue">return </span>dt.ToString((<span style="color:blue">string</span>)parameter, culture);
        }

        <span style="background:#e2e2e2;color:#008200">//Called with two-way data binding as value is pulled out of control and put back into the property
</span>        <span style="color:blue">public object </span>ConvertBack(<span style="color:blue">object </span>value, <span style="color:#2b91af">Type </span>targetType, <span style="color:blue">object </span>parameter, System.Globalization.<span style="color:#2b91af">CultureInfo </span>culture)
        {
            <span style="color:blue">string </span>val = (<span style="color:blue">string</span>)value;
            <span style="color:#2b91af">DateTime </span>outDate;
            <span style="color:blue">if </span>(<span style="color:#2b91af">DateTime</span>.TryParse(val, culture, <span style="color:#2b91af">DateTimeStyles</span>.None, <span style="color:blue">out </span>outDate))
            {
                <span style="color:blue">return </span>outDate;
            }
            <span style="color:blue">return </span><span style="color:#2b91af">DependencyProperty</span>.UnsetValue;

        }

        <span style="color:blue">#endregion
    </span>}
}</pre><a href="http://11011.net/software/vspaste"></a>
<p><br />To use a value converter you’ll need to first reference the class’s namespace (and assembly if the class is in a separate project).  This can be done in the XAML file where the value converter will be used, in App.xaml or in a merged resource dictionary file.  An example of defining a namespace in a resource dictionary file named Styles.xaml is shown next: <br /></p><pre><span style="color:blue">&#60;</span><span style="color:#a31515">ResourceDictionary
  </span><span style="color:red">xmlns</span><span style="color:blue">="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  </span><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">x</span><span style="color:blue">="http://schemas.microsoft.com/winfx/2006/xaml"
</span><span style="color:blue">  </span><span style="color:red">xmlns</span><span style="color:blue">:</span><span style="color:red">converters</span><span style="color:blue">="clr-namespace:View.Converters"
</span><span style="color:blue">&#62;</span>

<span style="color:blue">   …</span>

<span style="color:blue">&#60;/</span><span style="color:#a31515">ResourceDictionary&#62; </span></pre>
<p><br />Once the namespace is defined you need to define the converter using XAML and give it a key that can be used to reference the value converter (similar to an ID in ASP.NET): <br /><br /></p><pre><span style="color:blue">&#60;</span><span style="color:#a31515">converters</span><span style="color:blue">:</span><span style="color:#a31515">DateConverter </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Key</span><span style="color:blue">=&#34;DateConverter&#34; /&#62;
</span></pre><a href="http://11011.net/software/vspaste"></a>
<p><br />Now that the converter is defined you can use it in any data binding that handles a DateTime object using the Binding object’s Converter and ConverterParameter properties.  Looking at the code below you can see that the converter is referenced using the StaticResource keyword (since it’s defined as a resource within your Silverlight project) which locates the appropriate key for the converter. <br /><br /></p><pre><span style="color:blue">&#60;</span><span style="color:#a31515">TextBox </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Name</span><span style="color:blue">="txtBirthday" 
         </span><span style="color:red">Text</span><span style="color:blue">="{</span><span style="color:#a31515">Binding </span><span style="color:red">Birthday</span><span style="color:blue">, </span><span style="color:red">Mode</span><span style="color:blue">=TwoWay, </span><span style="color:red">Converter</span><span style="color:blue">={</span><span style="color:#a31515">StaticResource </span><span style="color:red">DateConverter</span><span style="color:blue">},</span><span style="color:red">ConverterParameter</span><span style="color:blue">=d}"
         </span><span style="color:red">FontFamily</span><span style="color:blue">="Arial" 
         </span><span style="color:red">Width</span><span style="color:blue">="200" 
         </span><span style="color:red">Height</span><span style="color:blue">="20" 
         </span><span style="color:red">Margin</span><span style="color:blue">=&#34;5&#34;  /&#62;</span></pre>
<p><br />This automatically routes all in and out data binding operations (since it’s a TwoWay binding) through the value converter.  If data is being bound to a control such as a TextBox the parameter passed (“d” in this example) is used to format the DateTime object data.  If data is updated in the control it’ll automatically be converted from a string back into a DateTime object. <br /><br /></p>
<h3>Value Converter Examples</h3>
<p><br />I have quite a few value converters that I use from time to time in client applications and have listed some of them below.  If you have a favorite one you’re willing to share with others please add a comment to this post with your name, a description of the value converter as well as the code and I’ll update the blog (and give you credit of course) so that a nice library of value converters built-up over time. Update: <a href="http://wildermuth.com/">Shawn Wildermuth</a> let me know that the <a href="http://silverlightcontrib.codeplex.com/">Silverlight Contrib project</a> has some similar value converters as well as others so check that out as well if you get a chance.</p>
<h4>BoolToVisibilityConverter </h4>
<p>Handles converting boolean values into Visibility enumeration values.  This is useful when controls need to be shown and hidden based upon the value of a boolean property.  The <em>Inverse</em> parameter value can be passed when you want to hide a control when the property being bound is true or show the control when the value is false. </p><pre><span style="color:blue">using </span>System;
<span style="color:blue">using </span>System.Windows;
<span style="color:blue">using </span>System.Windows.Data;

<span style="color:blue">namespace </span>JobPlan.View.Converters
{
    <span style="color:blue">public class </span><span style="color:#2b91af">BoolToVisibilityConverter </span>: <span style="color:#2b91af">IValueConverter
    </span>{
        <span style="color:blue">#region </span>IValueConverter Members

        <span style="color:blue">public object </span>Convert(<span style="color:blue">object </span>value, <span style="color:#2b91af">Type </span>targetType, <span style="color:blue">object </span>parameter, System.Globalization.<span style="color:#2b91af">CultureInfo </span>culture)
        {
            <span style="color:blue">if </span>(parameter == <span style="color:blue">null</span>)
            {
                <span style="color:blue">return </span>((<span style="color:blue">bool</span>)value == <span style="color:blue">true</span>) ? <span style="color:#2b91af">Visibility</span>.Visible : <span style="color:#2b91af">Visibility</span>.Collapsed;
            }
            <span style="color:blue">else if </span>(parameter.ToString() == <span style="color:#a31515">"Inverse"</span>)
            {
                <span style="color:blue">return </span>((<span style="color:blue">bool</span>)value == <span style="color:blue">true</span>) ? <span style="color:#2b91af">Visibility</span>.Collapsed : <span style="color:#2b91af">Visibility</span>.Visible;
            }
            <span style="color:blue">return false</span>;
        }

        <span style="color:blue">public object </span>ConvertBack(<span style="color:blue">object </span>value, <span style="color:#2b91af">Type </span>targetType, <span style="color:blue">object </span>parameter, System.Globalization.<span style="color:#2b91af">CultureInfo </span>culture)
        {
            <span style="color:blue">throw new </span><span style="color:#2b91af">NotImplementedException</span>();
        }

        <span style="color:blue">#endregion
    </span>}
}</pre>
<p><strong><br />DecimalFormatterConverter</strong> </p>
<p>Converts decimal values into different formats.</p><pre><span style="color:blue">using </span>System;
<span style="color:blue">using </span>System.Windows.Data;

<span style="color:blue">namespace </span>JobPlan.View.Converters
{
    <span style="color:blue">public class </span><span style="color:#2b91af">DecimalFormatterConverter </span>: <span style="color:#2b91af">IValueConverter
    </span>{

        <span style="color:blue">#region </span>IValueConverter Members

        <span style="color:blue">public object </span>Convert(<span style="color:blue">object </span>value, <span style="color:#2b91af">Type </span>targetType, <span style="color:blue">object </span>parameter, System.Globalization.<span style="color:#2b91af">CultureInfo </span>culture)
        {
            <span style="color:blue">string </span>format = (parameter == <span style="color:blue">null</span>) ? <span style="color:#a31515">"#.##" </span>: parameter.ToString();
            <span style="color:blue">return </span>(value == <span style="color:blue">null</span>) ? <span style="color:#2b91af">String</span>.Empty : <span style="color:blue">decimal</span>.Parse(value.ToString()).ToString(format);
        }

        <span style="color:blue">public object </span>ConvertBack(<span style="color:blue">object </span>value, <span style="color:#2b91af">Type </span>targetType, <span style="color:blue">object </span>parameter, System.Globalization.<span style="color:#2b91af">CultureInfo </span>culture)
        {
            <span style="color:blue">try
            </span>{
                <span style="color:blue">if </span>(value != <span style="color:blue">null </span>&#38;&#38; value.ToString() != <span style="color:#2b91af">String</span>.Empty)
                {
                    <span style="color:blue">return decimal</span>.Parse(value.ToString());
                }
            }
            <span style="color:blue">catch </span>{ }
            <span style="color:blue">return null</span>;
        }

        <span style="color:blue">#endregion
    </span>}
}</pre><a href="http://11011.net/software/vspaste"></a>
<p><br /></p>
<h4>ListCountVisibilityConverter</h4>
<p>Handles showing and hiding controls such as ListBox based upon the number of items in the collection the control is bound to.  For example if there is only one item in a collection you may not want to show a ListBox control due to the data being shown with other controls in the UI.  You could pass a value of 1 for the ConverterParameter and the ListBox would automatically be hidden.</p><pre><span style="color:blue">using </span>System;
<span style="color:blue">using </span>System.Windows;
<span style="color:blue">using </span>System.Windows.Data;
<span style="color:blue">using </span>System.Collections;

<span style="color:blue">namespace </span>JobPlan.View.Converters
{
    <span style="color:blue">public class </span><span style="color:#2b91af">ListCountVisibilityConverter </span>: <span style="color:#2b91af">IValueConverter
    </span>{

        <span style="color:blue">#region </span>IValueConverter Members

        <span style="color:blue">public object </span>Convert(<span style="color:blue">object </span>value, <span style="color:#2b91af">Type </span>targetType, <span style="color:blue">object </span>parameter, System.Globalization.<span style="color:#2b91af">CultureInfo </span>culture)
        {
            <span style="color:blue">if </span>(value != <span style="color:blue">null</span>)
            {
                <span style="color:#2b91af">IList </span>list = value <span style="color:blue">as </span><span style="color:#2b91af">IList</span>;
                <span style="color:blue">if </span>(list != <span style="color:blue">null</span>)
                {
                    <span style="color:blue">int </span>minCount = <span style="color:blue">int</span>.Parse(parameter.ToString());
                    <span style="color:blue">return </span>(list.Count &#62; minCount) ? <span style="color:#2b91af">Visibility</span>.Visible : <span style="color:#2b91af">Visibility</span>.Collapsed;
                }
                
            }
            <span style="color:blue">return </span><span style="color:#2b91af">Visibility</span>.Collapsed;
        }

        <span style="color:blue">public object </span>ConvertBack(<span style="color:blue">object </span>value, <span style="color:#2b91af">Type </span>targetType, <span style="color:blue">object </span>parameter, System.Globalization.<span style="color:#2b91af">CultureInfo </span>culture)
        {
            <span style="color:blue">throw new </span><span style="color:#2b91af">NotImplementedException</span>();
        }

        <span style="color:blue">#endregion
    </span>}
}</pre>
<p><br /></p>
<h4>NullToVisibilityConverter</h4>
<p>Handles showing and hiding a control based upon a value being null or not.</p><pre><span style="color:blue">using </span>System;
<span style="color:blue">using </span>System.Windows;
<span style="color:blue">using </span>System.Windows.Data;

<span style="color:blue">namespace </span>JobPlan.View.Converters
{
    <span style="color:blue">public class </span><span style="color:#2b91af">NullToVisibilityConverter </span>: <span style="color:#2b91af">IValueConverter
    </span>{

        <span style="color:blue">#region </span>IValueConverter Members

        <span style="color:blue">public object </span>Convert(<span style="color:blue">object </span>value, <span style="color:#2b91af">Type </span>targetType, <span style="color:blue">object </span>parameter, System.Globalization.<span style="color:#2b91af">CultureInfo </span>culture)
        {
            <span style="color:blue">if </span>(parameter == <span style="color:blue">null</span>) <span style="background:#e2e2e2;color:#008200">//Not invert parameter passed
</span>            {
                <span style="color:blue">return </span>(value == <span style="color:blue">null</span>) ? <span style="color:#2b91af">Visibility</span>.Collapsed : <span style="color:#2b91af">Visibility</span>.Visible;
            }
            <span style="color:blue">else if </span>(parameter.ToString() == <span style="color:#a31515">"Inverse"</span>)
            {
                <span style="color:blue">return </span>(value == <span style="color:blue">null</span>) ? <span style="color:#2b91af">Visibility</span>.Visible : <span style="color:#2b91af">Visibility</span>.Collapsed;
            }
            <span style="color:blue">return </span><span style="color:#2b91af">Visibility</span>.Collapsed;
        }

        <span style="color:blue">public object </span>ConvertBack(<span style="color:blue">object </span>value, <span style="color:#2b91af">Type </span>targetType, <span style="color:blue">object </span>parameter, System.Globalization.<span style="color:#2b91af">CultureInfo </span>culture)
        {
            <span style="color:blue">throw new </span><span style="color:#2b91af">NotImplementedException</span>();
        }

        <span style="color:blue">#endregion
    </span>}
}</pre>
<p><br /></p>
<h4>StringTruncateConverter</h4>
<p>Trims a string down to a specific length for display in the user interface.</p><pre><span style="color:blue">using </span>System;
<span style="color:blue">using </span>System.Windows.Data;

<span style="color:blue">namespace </span>JobPlan.View.Converters
{
    <span style="color:blue">public class </span><span style="color:#2b91af">StringTruncateConverter </span>: <span style="color:#2b91af">IValueConverter
    </span>{

        <span style="color:blue">#region </span>IValueConverter Members

        <span style="color:blue">public object </span>Convert(<span style="color:blue">object </span>value, <span style="color:#2b91af">Type </span>targetType, <span style="color:blue">object </span>parameter, System.Globalization.<span style="color:#2b91af">CultureInfo </span>culture)
        {
            <span style="color:blue">int </span>maxLength;
            <span style="color:blue">if </span>(<span style="color:blue">int</span>.TryParse(parameter.ToString(), <span style="color:blue">out </span>maxLength))
            {
                <span style="color:blue">string </span>val = (value == <span style="color:blue">null</span>) ? <span style="color:blue">null </span>: value.ToString();
                <span style="color:blue">if </span>(val != <span style="color:blue">null </span>&#38;&#38; val.Length &#62; maxLength)
                {
                    <span style="color:blue">return </span>val.Substring(0, maxLength) + <span style="color:#a31515">".."</span>;
                }
            }
            <span style="color:blue">return </span>value;
        }

        <span style="color:blue">public object </span>ConvertBack(<span style="color:blue">object </span>value, <span style="color:#2b91af">Type </span>targetType, <span style="color:blue">object </span>parameter, System.Globalization.<span style="color:#2b91af">CultureInfo </span>culture)
        {
            <span style="color:blue">throw new </span><span style="color:#2b91af">NotImplementedException</span>();
        }

        <span style="color:blue">#endregion
    </span>}
}</pre><a href="http://11011.net/software/vspaste"></a><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7170562" width="1" height="1"><p class="read-more"><a href="http://zdima.net/blog/archives/4556">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<p>Silverlight has an excellent data binding engine that allows data to be bound through XAML or programmatically with code.  My number one reason for using Silverlight on client projects is the data binding support.  Once you get into it and understand how it works it can save a lot of time when building applications.</p>
<p>When you’re binding data to controls there will be times when the data needs to be modified or tweaked some on the way into a control or as the data leaves a control and goes back to the source property (during a TwoWay binding for example).  Sure, you can always write code to change a given value, but in many cases it’s much easier to write a simple value converter instead that can be re-used.  In this post I’ll walk through creating a value converter and then show the code for a few of the value converters I find myself using fairly frequently. </p>
<h3>Creating a Value Converter</h3>
<p>Let’s look at a simple example of creating a value converter to get started.  Many applications work with DateTime objects but don’t want the time displayed or want the date formatted a specific way.  If you bind a DateTime property to something like a TextBlock in Silverlight you’ll get the standard output based upon the current culture: </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/clip_image00211_140D92B9.jpg"><img  title="clip_image002[11]" border="0" alt="clip_image002[11]" src="http://weblogs.asp.net/blogs/dwahlin/clip_image00211_thumb_0BA9BD62.jpg" width="211" height="179"></a> </p>
<p>In the case of a birthday you want to show the date but don’t need the time of course.  You’d want something like the following: </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/clip_image00213_4690F02B.jpg"><img  title="clip_image002[13]" border="0" alt="clip_image002[13]" src="http://weblogs.asp.net/blogs/dwahlin/clip_image00213_thumb_45B88A41.jpg" width="176" height="180"></a></p>
<p>Although a separate property could be created in the source object being bound that handles formatting the date, a value converter can be created and re-used over and over anytime a specific date format needs to be created.  To create a value converter you’ll need to add a Silverlight class into your project and implement an interface named IValueConverter (located in the System.Windows.Data namespace).  This interface defines two members including Convert and ConvertBack. Convert is used to modify data as its bound from the source object to the control. ConvertBack works the other way. As a user changes data in a control such as a TextBox the data can be &quot;converted back&quot; to the original data type in the source object by using ConvertBack. </p>
<p>Both Convert and ConvertBack accept the same parameters including the data being bound, the type of the data being bound, any parameter data passed in that can be used in the data conversion process as well as the target culture that the entire process is running under (English, Spanish, French, etc.). Here&#8217;s what the method signatures look like: </p>
<p><font face="Courier New">object Convert(object value, Type targetType, object parameter, CultureInfo culture); <br />object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);</font> </p>
<p>Once IValueConverter is added to your class you can right-click it in Visual Studio and select <em>Implement Interface</em> from the menu to automatically fill in the Convert and ConvertBack methods. If you&#39;re using Visual Basic you can simply hit enter after the interface name to accomplish the same thing.  Here’s an example of a date value converter that allows dates to be formatted: </p>
<pre><span >using </span>System;
<span >using </span>System.Windows;
<span >using </span>System.Windows.Data;
<span >using </span>System.Globalization;

<span >namespace </span>View.Converters
{
   <span >public class </span><span >DateConverter </span>: <span >IValueConverter
    </span>{

        <span >#region </span>IValueConverter Members

        <span >//Called when binding from an object property to a control property
</span>        <span >public object </span>Convert(<span >object </span>value, <span >Type </span>targetType, <span >object </span>parameter, System.Globalization.<span >CultureInfo </span>culture)
        {
            <span >if </span>(value == <span >null </span>|| (<span >DateTime</span>)value == <span >DateTime</span>.MinValue) <span >return null</span>;
            <span >DateTime </span>dt = (<span >DateTime</span>)value;
            <span >return </span>dt.ToString((<span >string</span>)parameter, culture);
        }

        <span >//Called with two-way data binding as value is pulled out of control and put back into the property
</span>        <span >public object </span>ConvertBack(<span >object </span>value, <span >Type </span>targetType, <span >object </span>parameter, System.Globalization.<span >CultureInfo </span>culture)
        {
            <span >string </span>val = (<span >string</span>)value;
            <span >DateTime </span>outDate;
            <span >if </span>(<span >DateTime</span>.TryParse(val, culture, <span >DateTimeStyles</span>.None, <span >out </span>outDate))
            {
                <span >return </span>outDate;
            }
            <span >return </span><span >DependencyProperty</span>.UnsetValue;

        }

        <span >#endregion
    </span>}
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>To use a value converter you’ll need to first reference the class’s namespace (and assembly if the class is in a separate project).  This can be done in the XAML file where the value converter will be used, in App.xaml or in a merged resource dictionary file.  An example of defining a namespace in a resource dictionary file named Styles.xaml is shown next: </p>
<pre><span >&lt;</span><span >ResourceDictionary
  </span><span >xmlns</span><span >="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  </span><span >xmlns</span><span >:</span><span >x</span><span >="http://schemas.microsoft.com/winfx/2006/xaml"
</span><span >  </span><span >xmlns</span><span >:</span><span >converters</span><span >="clr-namespace:View.Converters"
</span><span >&gt;</span>

<span >   …</span>

<span >&lt;/</span><span >ResourceDictionary&gt; </span></pre>
<p>Once the namespace is defined you need to define the converter using XAML and give it a key that can be used to reference the value converter (similar to an ID in <a href="http://ASP.NET" class="autohyperlink" title="http://ASP.NET" target="_blank" rel="nofollow">ASP.NET</a>): </p>
<pre><span >&lt;</span><span >converters</span><span >:</span><span >DateConverter </span><span >x</span><span >:</span><span >Key</span><span >=&quot;DateConverter&quot; /&gt;
</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Now that the converter is defined you can use it in any data binding that handles a DateTime object using the Binding object’s Converter and ConverterParameter properties.  Looking at the code below you can see that the converter is referenced using the StaticResource keyword (since it’s defined as a resource within your Silverlight project) which locates the appropriate key for the converter. </p>
<pre><span >&lt;</span><span >TextBox </span><span >x</span><span >:</span><span >Name</span><span >="txtBirthday"
         </span><span >Text</span><span >="{</span><span >Binding </span><span >Birthday</span><span >, </span><span >Mode</span><span >=TwoWay, </span><span >Converter</span><span >={</span><span >StaticResource </span><span >DateConverter</span><span >},</span><span >ConverterParameter</span><span >=d}"
         </span><span >FontFamily</span><span >="Arial"
         </span><span >Width</span><span >="200"
         </span><span >Height</span><span >="20"
         </span><span >Margin</span><span >=&quot;5&quot;  /&gt;</span></pre>
<p>This automatically routes all in and out data binding operations (since it’s a TwoWay binding) through the value converter.  If data is being bound to a control such as a TextBox the parameter passed (“d” in this example) is used to format the DateTime object data.  If data is updated in the control it’ll automatically be converted from a string back into a DateTime object. </p>
<h3>Value Converter Examples</h3>
<p>I have quite a few value converters that I use from time to time in client applications and have listed some of them below.  If you have a favorite one you’re willing to share with others please add a comment to this post with your name, a description of the value converter as well as the code and I’ll update the blog (and give you credit of course) so that a nice library of value converters built-up over time. Update: <a href="http://wildermuth.com/">Shawn Wildermuth</a> let me know that the <a href="http://silverlightcontrib.codeplex.com/">Silverlight Contrib project</a> has some similar value converters as well as others so check that out as well if you get a chance.</p>
<h4>BoolToVisibilityConverter </h4>
<p>Handles converting boolean values into Visibility enumeration values.  This is useful when controls need to be shown and hidden based upon the value of a boolean property.  The <em>Inverse</em> parameter value can be passed when you want to hide a control when the property being bound is true or show the control when the value is false. </p>
<pre><span >using </span>System;
<span >using </span>System.Windows;
<span >using </span>System.Windows.Data;

<span >namespace </span>JobPlan.View.Converters
{
    <span >public class </span><span >BoolToVisibilityConverter </span>: <span >IValueConverter
    </span>{
        <span >#region </span>IValueConverter Members

        <span >public object </span>Convert(<span >object </span>value, <span >Type </span>targetType, <span >object </span>parameter, System.Globalization.<span >CultureInfo </span>culture)
        {
            <span >if </span>(parameter == <span >null</span>)
            {
                <span >return </span>((<span >bool</span>)value == <span >true</span>) ? <span >Visibility</span>.Visible : <span >Visibility</span>.Collapsed;
            }
            <span >else if </span>(parameter.ToString() == <span >"Inverse"</span>)
            {
                <span >return </span>((<span >bool</span>)value == <span >true</span>) ? <span >Visibility</span>.Collapsed : <span >Visibility</span>.Visible;
            }
            <span >return false</span>;
        }

        <span >public object </span>ConvertBack(<span >object </span>value, <span >Type </span>targetType, <span >object </span>parameter, System.Globalization.<span >CultureInfo </span>culture)
        {
            <span >throw new </span><span >NotImplementedException</span>();
        }

        <span >#endregion
    </span>}
}</pre>
<p><strong><br />DecimalFormatterConverter</strong> </p>
<p>Converts decimal values into different formats.</p>
<pre><span >using </span>System;
<span >using </span>System.Windows.Data;

<span >namespace </span>JobPlan.View.Converters
{
    <span >public class </span><span >DecimalFormatterConverter </span>: <span >IValueConverter
    </span>{

        <span >#region </span>IValueConverter Members

        <span >public object </span>Convert(<span >object </span>value, <span >Type </span>targetType, <span >object </span>parameter, System.Globalization.<span >CultureInfo </span>culture)
        {
            <span >string </span>format = (parameter == <span >null</span>) ? <span >"#.##" </span>: parameter.ToString();
            <span >return </span>(value == <span >null</span>) ? <span >String</span>.Empty : <span >decimal</span>.Parse(value.ToString()).ToString(format);
        }

        <span >public object </span>ConvertBack(<span >object </span>value, <span >Type </span>targetType, <span >object </span>parameter, System.Globalization.<span >CultureInfo </span>culture)
        {
            <span >try
            </span>{
                <span >if </span>(value != <span >null </span>&amp;&amp; value.ToString() != <span >String</span>.Empty)
                {
                    <span >return decimal</span>.Parse(value.ToString());
                }
            }
            <span >catch </span>{ }
            <span >return null</span>;
        }

        <span >#endregion
    </span>}
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p></p>
<h4>ListCountVisibilityConverter</h4>
<p>Handles showing and hiding controls such as ListBox based upon the number of items in the collection the control is bound to.  For example if there is only one item in a collection you may not want to show a ListBox control due to the data being shown with other controls in the UI.  You could pass a value of 1 for the ConverterParameter and the ListBox would automatically be hidden.</p>
<pre><span >using </span>System;
<span >using </span>System.Windows;
<span >using </span>System.Windows.Data;
<span >using </span>System.Collections;

<span >namespace </span>JobPlan.View.Converters
{
    <span >public class </span><span >ListCountVisibilityConverter </span>: <span >IValueConverter
    </span>{

        <span >#region </span>IValueConverter Members

        <span >public object </span>Convert(<span >object </span>value, <span >Type </span>targetType, <span >object </span>parameter, System.Globalization.<span >CultureInfo </span>culture)
        {
            <span >if </span>(value != <span >null</span>)
            {
                <span >IList </span>list = value <span >as </span><span >IList</span>;
                <span >if </span>(list != <span >null</span>)
                {
                    <span >int </span>minCount = <span >int</span>.Parse(parameter.ToString());
                    <span >return </span>(list.Count &gt; minCount) ? <span >Visibility</span>.Visible : <span >Visibility</span>.Collapsed;
                }

            }
            <span >return </span><span >Visibility</span>.Collapsed;
        }

        <span >public object </span>ConvertBack(<span >object </span>value, <span >Type </span>targetType, <span >object </span>parameter, System.Globalization.<span >CultureInfo </span>culture)
        {
            <span >throw new </span><span >NotImplementedException</span>();
        }

        <span >#endregion
    </span>}
}</pre>
<p></p>
<h4>NullToVisibilityConverter</h4>
<p>Handles showing and hiding a control based upon a value being null or not.</p>
<pre><span >using </span>System;
<span >using </span>System.Windows;
<span >using </span>System.Windows.Data;

<span >namespace </span>JobPlan.View.Converters
{
    <span >public class </span><span >NullToVisibilityConverter </span>: <span >IValueConverter
    </span>{

        <span >#region </span>IValueConverter Members

        <span >public object </span>Convert(<span >object </span>value, <span >Type </span>targetType, <span >object </span>parameter, System.Globalization.<span >CultureInfo </span>culture)
        {
            <span >if </span>(parameter == <span >null</span>) <span >//Not invert parameter passed
</span>            {
                <span >return </span>(value == <span >null</span>) ? <span >Visibility</span>.Collapsed : <span >Visibility</span>.Visible;
            }
            <span >else if </span>(parameter.ToString() == <span >"Inverse"</span>)
            {
                <span >return </span>(value == <span >null</span>) ? <span >Visibility</span>.Visible : <span >Visibility</span>.Collapsed;
            }
            <span >return </span><span >Visibility</span>.Collapsed;
        }

        <span >public object </span>ConvertBack(<span >object </span>value, <span >Type </span>targetType, <span >object </span>parameter, System.Globalization.<span >CultureInfo </span>culture)
        {
            <span >throw new </span><span >NotImplementedException</span>();
        }

        <span >#endregion
    </span>}
}</pre>
<p></p>
<h4>StringTruncateConverter</h4>
<p>Trims a string down to a specific length for display in the user interface.</p>
<pre><span >using </span>System;
<span >using </span>System.Windows.Data;

<span >namespace </span>JobPlan.View.Converters
{
    <span >public class </span><span >StringTruncateConverter </span>: <span >IValueConverter
    </span>{

        <span >#region </span>IValueConverter Members

        <span >public object </span>Convert(<span >object </span>value, <span >Type </span>targetType, <span >object </span>parameter, System.Globalization.<span >CultureInfo </span>culture)
        {
            <span >int </span>maxLength;
            <span >if </span>(<span >int</span>.TryParse(parameter.ToString(), <span >out </span>maxLength))
            {
                <span >string </span>val = (value == <span >null</span>) ? <span >null </span>: value.ToString();
                <span >if </span>(val != <span >null </span>&amp;&amp; val.Length &gt; maxLength)
                {
                    <span >return </span>val.Substring(0, maxLength) + <span >".."</span>;
                }
            }
            <span >return </span>value;
        }

        <span >public object </span>ConvertBack(<span >object </span>value, <span >Type </span>targetType, <span >object </span>parameter, System.Globalization.<span >CultureInfo </span>culture)
        {
            <span >throw new </span><span >NotImplementedException</span>();
        }

        <span >#endregion
    </span>}
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7170562" width="1" height="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/4556/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Silverlight 3 Application Code More Compatible with Blend</title>
		<link>http://zdima.net/blog/archives/3871</link>
		<comments>http://zdima.net/blog/archives/3871#comments</comments>
		<pubDate>Thu, 30 Jul 2009 02:24:00 +0000</pubDate>
		<dc:creator>dwahlin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Expression Blend]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=3871</guid>
		<description><![CDATA[<p>Expression Blend 3 is a great tool for creating Silverlight or WPF user interfaces using design time tools and controls.  If you haven’t tried version 3 you’re really missing out since it adds a ton of new time-saving features.</p>
<p>While I really enjoy working in Blend, one of the things I’ve struggled with in the past is making code work better in Blend.  If you’ve ever had an error like the following you know what I mean: <br /></p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_31EC0900.png"><img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_25EA18CC.png" width="770" height="87"></a> <br /></p>
<p>What’s up with the error?  In short, I’m declaratively assigning my ViewModel object (my object that contains the data being bound to the Silverlight View if you’re new to the whole MVVM terminology) in the View’s resources area as shown next:</p><pre><span style="color:blue">&#60;</span><span style="color:#a31515">navigation</span><span style="color:blue">:</span><span style="color:#a31515">Page.Resources</span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">viewModel</span><span style="color:blue">:</span><span style="color:#a31515">PayrollSummaryViewModel </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Key</span><span style="color:blue">=&#34;ViewModel&#34; /&#62;
&#60;/</span><span style="color:#a31515">navigation</span><span style="color:blue">:</span><span style="color:#a31515">Page.Resources</span><span style="color:blue">&#62;</span></pre>
<p>There’s nothing wrong with that except that when the ViewModel object’s constructor is called an error is occurring due to a null reference exception.  <strong>Note:</strong> Some people like the declarative way of defining ViewModels and some people don&#39;t.  A few months ago I was against that approach until I started working on my current project and realized that the pros outweighed the cons (at least for my scenario).  Plus, the declarative approach is used when working with test data in Blend 3.  Ultimately each application has different requirements so I&#39;ll leave it as an &#34;exercise for the reader&#34; to decide what works best for you.</p>
<p>Here’s the code in the constructor which is calling out to a WCF service to retrieve some data: <br /></p><pre><span style="color:blue">public </span>PayrollSummaryViewModel(<span style="color:#2b91af">IServiceProxy </span>proxy)
{
    _Proxy = (proxy != <span style="color:blue">null</span>) ? proxy : <span style="color:blue">new </span><span style="color:#2b91af">ServiceProxy</span>();
    GetPayrollSummary();
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>You obviously can’t call out to a WCF service when you don’t have access to an HTTP stack.  Fortunately, fixing the problem and making the code more “Blendable” is easy.  Silverlight has a class named DesignerProperties that can be used to check if the code is being run in a designer such as Blend or if the code is being run live.  Here’s an example of using the DesignerProperties class and wrapping it in a property named IsDesignTime:</p><pre><span style="color:blue">public bool </span>IsDesignTime
{
    <span style="color:blue">get
    </span>{
        <span style="color:blue">return </span><span style="color:#2b91af">DesignerProperties</span>.GetIsInDesignMode(<span style="color:#2b91af">Application</span>.Current.RootVisual);
    }
}</pre>
<p><br /><a href="http://11011.net/software/vspaste"></a>To avoid trying to call the WCF service in the ViewModel object’s constructor when the code is run in Blend I can wrap the code with the call to IsDesignTime as shown next and Blend is happy with everything.  <br /></p><pre><span style="color:blue">public </span>PayrollSummaryViewModel(<span style="color:#2b91af">IServiceProxy </span>proxy)
{
    <span style="color:blue">if </span>(!<span style="color:blue">this</span>.IsDesignTime)
    {
        _Proxy = (proxy != <span style="color:blue">null</span>) ? proxy : <span style="color:blue">new </span><span style="color:#2b91af">ServiceProxy</span>();
        GetPayrollSummary();
    }
}</pre>
<p><br />You can see that creating more “Blendable” code is pretty easy once you know this simple trick.  More info on the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.designerproperties.getisindesignmode(VS.95).aspx">DesignerProperties class can be found here</a> if you’re interested.  There are apparently some issues using it with the Visual Studio designer used for Silverlight 2, but since Silverlight 3 doesn’t have a Visual Studio designer that’s kind of a moot point. </p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7157399" width="1" height="1"><p class="read-more"><a href="http://zdima.net/blog/archives/3871">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<p>Expression Blend 3 is a great tool for creating Silverlight or WPF user interfaces using design time tools and controls.  If you haven’t tried version 3 you’re really missing out since it adds a ton of new time-saving features.</p>
<p>While I really enjoy working in Blend, one of the things I’ve struggled with in the past is making code work better in Blend.  If you’ve ever had an error like the following you know what I mean: </p>
<p><a href="http://weblogs.asp.net/blogs/dwahlin/image_31EC0900.png"><img  title="image" border="0" alt="image" src="http://weblogs.asp.net/blogs/dwahlin/image_thumb_25EA18CC.png" width="770" height="87"></a> </p>
<p>What’s up with the error?  In short, I’m declaratively assigning my ViewModel object (my object that contains the data being bound to the Silverlight View if you’re new to the whole MVVM terminology) in the View’s resources area as shown next:</p>
<pre><span >&lt;</span><span >navigation</span><span >:</span><span >Page.Resources</span><span >&gt;
    &lt;</span><span >viewModel</span><span >:</span><span >PayrollSummaryViewModel </span><span >x</span><span >:</span><span >Key</span><span >=&quot;ViewModel&quot; /&gt;
&lt;/</span><span >navigation</span><span >:</span><span >Page.Resources</span><span >&gt;</span></pre>
<p>There’s nothing wrong with that except that when the ViewModel object’s constructor is called an error is occurring due to a null reference exception.  <strong>Note:</strong> Some people like the declarative way of defining ViewModels and some people don&#39;t.  A few months ago I was against that approach until I started working on my current project and realized that the pros outweighed the cons (at least for my scenario).  Plus, the declarative approach is used when working with test data in Blend 3.  Ultimately each application has different requirements so I&#39;ll leave it as an &quot;exercise for the reader&quot; to decide what works best for you.</p>
<p>Here’s the code in the constructor which is calling out to a WCF service to retrieve some data: </p>
<pre><span >public </span>PayrollSummaryViewModel(<span >IServiceProxy </span>proxy)
{
    _Proxy = (proxy != <span >null</span>) ? proxy : <span >new </span><span >ServiceProxy</span>();
    GetPayrollSummary();
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>You obviously can’t call out to a WCF service when you don’t have access to an HTTP stack.  Fortunately, fixing the problem and making the code more “Blendable” is easy.  Silverlight has a class named DesignerProperties that can be used to check if the code is being run in a designer such as Blend or if the code is being run live.  Here’s an example of using the DesignerProperties class and wrapping it in a property named IsDesignTime:</p>
<pre><span >public bool </span>IsDesignTime
{
    <span >get
    </span>{
        <span >return </span><span >DesignerProperties</span>.GetIsInDesignMode(<span >Application</span>.Current.RootVisual);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>To avoid trying to call the WCF service in the ViewModel object’s constructor when the code is run in Blend I can wrap the code with the call to IsDesignTime as shown next and Blend is happy with everything.  </p>
<pre><span >public </span>PayrollSummaryViewModel(<span >IServiceProxy </span>proxy)
{
    <span >if </span>(!<span >this</span>.IsDesignTime)
    {
        _Proxy = (proxy != <span >null</span>) ? proxy : <span >new </span><span >ServiceProxy</span>();
        GetPayrollSummary();
    }
}</pre>
<p>You can see that creating more “Blendable” code is pretty easy once you know this simple trick.  More info on the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.designerproperties.getisindesignmode(VS.95).aspx">DesignerProperties class can be found here</a> if you’re interested.  There are apparently some issues using it with the Visual Studio designer used for Silverlight 2, but since Silverlight 3 doesn’t have a Visual Studio designer that’s kind of a moot point. </p>
<p><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7157399" width="1" height="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/3871/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Element to Element Binding for ToolTips in Silverlight 3</title>
		<link>http://zdima.net/blog/archives/3189</link>
		<comments>http://zdima.net/blog/archives/3189#comments</comments>
		<pubDate>Tue, 14 Jul 2009 03:43:00 +0000</pubDate>
		<dc:creator>dwahlin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Contributors]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://zdima.net/blog/?p=3189</guid>
		<description><![CDATA[<p>Silverlight 3 provides a new feature called “element to element” binding that allows one element to bind to another element’s property.  It’s really useful when you want to tie two objects together so that when one object changes the other changes as well.</p>
<p>A lot of the samples I see for this new technology tend to focus on using slider controls but I just don’t have a need for sliders most of the time (although it certainly depends upon what type of application you’re building).  Here’s a simple yet effective way to leverage element to element binding for tooltips.  I currently have a ComboBox control with a data template and want to show a description of the selected item as the user mouses over the control.  With Silverlight 2 you’d have to write code since there wouldn’t be a way for the tooltip service to bind to the selected item declaratively.  Now, you can do something like this (notice the ToolTipService attribute): <br /></p><pre><span style="color:blue">&#60;</span><span style="color:#a31515">ComboBox 
    </span><span style="color:red">x</span><span style="color:blue">:</span><span style="color:red">Name</span><span style="color:blue">="WorkCodeComboBox"
</span><span style="color:red">    ItemsSource</span><span style="color:blue">="{</span><span style="color:#a31515">Binding </span><span style="color:red">Source</span><span style="color:blue">={</span><span style="color:#a31515">StaticResource </span><span style="color:red">ViewModel</span><span style="color:blue">},</span><span style="color:red">Path</span><span style="color:blue">=CurrentTimeSheetView.WorkCodes}"
    </span><span style="color:red">Style</span><span style="color:blue">="{</span><span style="color:#a31515">StaticResource </span><span style="color:red">TimeSheetComboBoxStyle</span><span style="color:blue">}" 
    </span><span style="color:red">SelectionChanged</span><span style="color:blue">="WorkCode_SelectionChanged"
    </span><strong><span style="color:red">ToolTipService.ToolTip</span><span style="color:blue">="{</span><span style="color:#a31515">Binding </span><span style="color:red">Path</span><span style="color:blue">=SelectedItem.Description, </span><span style="color:red">ElementName</span></strong><span style="color:blue"><strong>=WorkCodeComboBox}"</strong></span><span style="color:blue">&#62;
    &#60;</span><span style="color:#a31515">ComboBox.ItemTemplate</span><span style="color:blue">&#62;
        &#60;</span><span style="color:#a31515">DataTemplate</span><span style="color:blue">&#62;
            &#60;</span><span style="color:#a31515">StackPanel </span><span style="color:red">Orientation</span><span style="color:blue">="Horizontal" </span><span style="color:red">Margin</span><span style="color:blue">=&#34;0&#34;&#62;
                &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Text</span><span style="color:blue">="{</span><span style="color:#a31515">Binding </span><span style="color:red">WorkCodeID</span><span style="color:blue">}" </span><span style="color:red">Width</span><span style="color:blue">="30" </span><span style="color:red">Margin</span><span style="color:blue">=&#34;5,0,0,0&#34; /&#62;
                &#60;</span><span style="color:#a31515">Rectangle </span><span style="color:red">Style</span><span style="color:blue">="{</span><span style="color:#a31515">StaticResource </span><span style="color:red">ComboBoxVerticalLine</span><span style="color:blue">}&#34; /&#62;
                &#60;</span><span style="color:#a31515">TextBlock </span><span style="color:red">Text</span><span style="color:blue">="{</span><span style="color:#a31515">Binding </span><span style="color:red">Description</span><span style="color:blue">}" </span><span style="color:red">Width</span><span style="color:blue">="250" </span><span style="color:red">Margin</span><span style="color:blue">=&#34;10,0,0,0&#34; /&#62;
            &#60;/</span><span style="color:#a31515">StackPanel</span><span style="color:blue">&#62;
        &#60;/</span><span style="color:#a31515">DataTemplate</span><span style="color:blue">&#62;
   &#60;/</span><span style="color:#a31515">ComboBox.ItemTemplate</span><span style="color:blue">&#62;
&#60;/</span><span style="color:#a31515">ComboBox</span><span style="color:blue">&#62;</span></pre>
<p><br />In this case I’m binding the tooltip to the selected item’s Description property.  At first glance it looks like the ComboBox is binding to itself but in reality it’s binding to the ToolTipService’s Tooltip property.  A simple little trick but nice when you need it since it saves a line or two of C# code.</p>
<p> </p><span style="text-transform:none;text-indent:0px;border-collapse:separate;font:medium Arial, Helvetica;white-space:normal;letter-spacing:normal;color:rgb(0,0,0);word-spacing:0px"><span style="text-align:left;font-size:12px">
<p style="margin:10px 0px"><a href="http://www.thewahlingroup.com/"><img style="margin:0.5em;max-width:100%" border="0" alt="Logo" src="http://weblogs.asp.net/blogs/dwahlin/Logo_702D5F60.jpg" width="240" height="57"></a></p>
<p style="margin:10px 0px">For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit<span> </span><a href="http://www.thewahlingroup.com/"><font color="#0066cc">http://www.thewahlingroup.com/</font></a>.</p></span></span><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7146911" width="1" height="1"><p class="read-more"><a href="http://zdima.net/blog/archives/3189">> Read more</a></p>]]></description>
			<content:encoded><![CDATA[<p>Silverlight 3 provides a new feature called “element to element” binding that allows one element to bind to another element’s property.  It’s really useful when you want to tie two objects together so that when one object changes the other changes as well.</p>
<p>A lot of the samples I see for this new technology tend to focus on using slider controls but I just don’t have a need for sliders most of the time (although it certainly depends upon what type of application you’re building).  Here’s a simple yet effective way to leverage element to element binding for tooltips.  I currently have a ComboBox control with a data template and want to show a description of the selected item as the user mouses over the control.  With Silverlight 2 you’d have to write code since there wouldn’t be a way for the tooltip service to bind to the selected item declaratively.  Now, you can do something like this (notice the ToolTipService attribute): </p>
<pre><span >&lt;</span><span >ComboBox
    </span><span >x</span><span >:</span><span >Name</span><span >="WorkCodeComboBox"
</span><span >    ItemsSource</span><span >="{</span><span >Binding </span><span >Source</span><span >={</span><span >StaticResource </span><span >ViewModel</span><span >},</span><span >Path</span><span >=CurrentTimeSheetView.WorkCodes}"
    </span><span >Style</span><span >="{</span><span >StaticResource </span><span >TimeSheetComboBoxStyle</span><span >}"
    </span><span >SelectionChanged</span><span >="WorkCode_SelectionChanged"
    </span><strong><span >ToolTipService.ToolTip</span><span >="{</span><span >Binding </span><span >Path</span><span >=SelectedItem.Description, </span><span >ElementName</span></strong><span ><strong>=WorkCodeComboBox}"</strong></span><span >&gt;
    &lt;</span><span >ComboBox.ItemTemplate</span><span >&gt;
        &lt;</span><span >DataTemplate</span><span >&gt;
            &lt;</span><span >StackPanel </span><span >Orientation</span><span >="Horizontal" </span><span >Margin</span><span >=&quot;0&quot;&gt;
                &lt;</span><span >TextBlock </span><span >Text</span><span >="{</span><span >Binding </span><span >WorkCodeID</span><span >}" </span><span >Width</span><span >="30" </span><span >Margin</span><span >=&quot;5,0,0,0&quot; /&gt;
                &lt;</span><span >Rectangle </span><span >Style</span><span >="{</span><span >StaticResource </span><span >ComboBoxVerticalLine</span><span >}&quot; /&gt;
                &lt;</span><span >TextBlock </span><span >Text</span><span >="{</span><span >Binding </span><span >Description</span><span >}" </span><span >Width</span><span >="250" </span><span >Margin</span><span >=&quot;10,0,0,0&quot; /&gt;
            &lt;/</span><span >StackPanel</span><span >&gt;
        &lt;/</span><span >DataTemplate</span><span >&gt;
   &lt;/</span><span >ComboBox.ItemTemplate</span><span >&gt;
&lt;/</span><span >ComboBox</span><span >&gt;</span></pre>
<p>In this case I’m binding the tooltip to the selected item’s Description property.  At first glance it looks like the ComboBox is binding to itself but in reality it’s binding to the ToolTipService’s Tooltip property.  A simple little trick but nice when you need it since it saves a line or two of C# code.</p>
<p> </p>
<p><span ><span ></p>
<p ><a  href="http://www.thewahlingroup.com/"><img  title="Logo" border="0" alt="Logo" src="http://weblogs.asp.net/blogs/dwahlin/Logo_702D5F60.jpg" width="240" height="57"></a></p>
<p >For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit<span> </span><a  href="http://www.thewahlingroup.com/"><font color="#0066cc"><a href="http://www.thewahlingroup.com/" class="autohyperlink" title="http://www.thewahlingroup.com/" target="_blank" rel="nofollow">www.thewahlingroup.com/</a></font></a>.</p>
<p></span></span><img src="http://weblogs.asp.net/aggbug.aspx?PostID=7146911" width="1" height="1"></p>
]]></content:encoded>
			<wfw:commentRss>http://zdima.net/blog/archives/3189/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

