<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>DarioSantarelli.Blog(this);</title>
	<atom:link href="https://dariosantarelli.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://dariosantarelli.wordpress.com</link>
	<description></description>
	<lastBuildDate>Wed, 26 Apr 2017 20:01:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='dariosantarelli.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>https://secure.gravatar.com/blavatar/fb8d38f4751afac9e1f91c647c98356d37cf0af7a028811c66396ebd947b5ee0?s=96&#038;d=https%3A%2F%2Fs0.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>DarioSantarelli.Blog(this);</title>
		<link>https://dariosantarelli.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="https://dariosantarelli.wordpress.com/osd.xml" title="DarioSantarelli.Blog(this);" />
	<atom:link rel='hub' href='https://dariosantarelli.wordpress.com/?pushpress=hub'/>
	<item>
		<title>ASP.NET SignalR and Ext.NET MessageBus</title>
		<link>https://dariosantarelli.wordpress.com/2013/10/20/asp-net-signalr-and-ext-net-messagebus/</link>
					<comments>https://dariosantarelli.wordpress.com/2013/10/20/asp-net-signalr-and-ext-net-messagebus/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sun, 20 Oct 2013 16:24:01 +0000</pubDate>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft Technology]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[client side]]></category>
		<category><![CDATA[Ext.NET]]></category>
		<category><![CDATA[MessageBus]]></category>
		<category><![CDATA[RealTime]]></category>
		<category><![CDATA[SignalR]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[UI components]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=607</guid>

					<description><![CDATA[Most of the modern web applications provides real-time functionalities (&#8220;real-time web&#8220;) through a set of technologies and practices that enable users to receive information as soon as it is published by its authors, rather than requiring that they or their software check a source periodically for updates.  Moreover, in very scalable and complex architectures, server-side [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Most of the modern web applications provides real-time functionalities (&#8220;<a href="http://en.wikipedia.org/wiki/Real-time_web" target="_blank">real-time web</a>&#8220;) through a set of technologies and practices that enable users to receive information as soon as it is published by its authors, rather than requiring that they or their software check a source periodically for updates.  Moreover, in very scalable and complex architectures, server-side code execution is often asynchronous. Just for example, let&#8217;s think to a task-based UI which submits a command like &#8220;<em>book a plane ticket</em>&#8221; to a web service. The server-side command processing could be performed after some hours: for example, the command could be just enqueued to a command-bus to be processed later. In scenarios like that, the client can&#8217;t count on an updated read model just after sending the command. As a consequence, in order to receive a feedback as soon as possible, all the involved clients should poll the server until the command execution reaches a significant state (e.g. in progress, completed, canceled etc.) and the read model is updated, ready for queries.</p>
<p>Before <a href="http://en.wikipedia.org/wiki/WebSocket" target="_blank">WebSockets</a>, the classic implementations of this kind of real-time features were not so easy and they used to adopt strategies like forever frame (see &#8220;<a href="http://en.wikipedia.org/wiki/Comet_(programming)" target="_blank">Comet</a>&#8220;) or periodic/<a href="http://en.wikipedia.org/wiki/Push_technology#Long_polling" target="_blank">long polling</a>. Today, all the modern browsers and web servers fully support WebSockets and they can extabilish bi-directional and persistent communications, so that a client can receive content through a &#8220;push&#8221; action performed by the server. In the ASP.NET world, <a href="http://signalr.net/" target="_blank">SignalR</a> is a growing new library that uses WebSockets under the covers when it&#8217;s available, and gracefully fallbacks to other techniques and technologies when it isn&#8217;t, while the application code stays the same. SignalR also provides a very simple, high-level API for doing server-to-client RPC (call JavaScript functions in clients&#8217; browsers from server-side code) in an ASP.NET application, as well as adding useful hooks for connection management, e.g. connect/disconnect events, grouping connections, authorization.</p>
<p>Developers that are currently using the <a href="http://www.ext.net/" target="_blank">Ext.NET component framework</a> can take advantage on SignalR by combining it with the <a href="http://mvc.ext.net/#/MessageBus_Basic/Simple/" target="_blank"><strong>Ext.NET MessageBus</strong> component</a>. The MessageBus provides a simple and robust client-side infrastructure to propagate notifications to listening UI components. The reference scenario I&#8217;m talking about in this post is represented in the figure below:</p>
<p><img class="aligncenter" alt="" src="https://dariosantarelli.wordpress.com/wp-content/uploads/2013/10/picture12.png?w=700" /><br />
1. The client browser extabilishes a persistent connection to a server-side SignalR application hub. After that the client mantains a reference to an auto-generated hub proxy.<br />
2. The Ext.NET UI components submits commands to the server.<br />
3. At any time of the server-side command execution, the server can use the SignalR hub to push notification messages back to all the involved clients via RPC.<br />
4. Any client receiving a SignalR message through the hub proxy redirects the message to the Ext.NET Message Bus<br />
5. On the basis of the specific type of message, the Ext.NET UI components are updated through a message handler function. In fact, each Ext.NET component has a <code>MessageBusListeners</code> property (client side handlers of MessageBus client side events) and a <code>MessageBusDirectEvents</code> property (server side handlers of MessageBus client side events).</p>
<p>Let&#8217;s have a look to a minimalistic example implemented in an ASP.NET MVC web application. Here&#8217;s the view :</p>
<pre class="code" style="font-size:12px;"><span style="background:yellow;color:black;">@</span><span style="background:white;color:blue;">using </span><span style="background:white;color:black;">Ext.Net;
</span><span style="background:yellow;color:black;">@</span><span style="background:white;color:blue;">using </span><span style="background:white;color:black;">Ext.Net.MVC;
</span><span style="background:yellow;color:black;">@{
</span><span style="background:white;color:black;">    Layout = </span><span style="background:white;color:blue;">null</span><span style="background:white;color:black;">;
    </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">X = Html.X();
</span><span style="background:yellow;color:black;">}
</span><span style="background:white;color:blue;">&lt;!</span><span style="background:white;color:maroon;">DOCTYPE </span><span style="background:white;color:red;">html</span><span style="background:white;color:blue;">&gt;
&lt;</span><span style="background:white;color:maroon;">html</span><span style="background:white;color:blue;">&gt;
    &lt;</span><span style="background:white;color:maroon;">head</span><span style="background:white;color:blue;">&gt;        
        &lt;</span><span style="background:white;color:maroon;">title</span><span style="background:white;color:blue;">&gt;</span><span style="background:white;color:black;">SignalR and Ext.NET MessageBus example</span><span style="background:white;color:blue;">&lt;/</span><span style="background:white;color:maroon;">title</span><span style="background:white;color:blue;">&gt;
        </span><span style="background:yellow;color:black;">@</span><span style="background:white;color:#2b91af;">Scripts</span><span style="background:white;color:black;">.Render(</span><span style="background:white;color:#a31515;">"~/bundles/modernizr"</span><span style="background:white;color:black;">)
        </span><span style="background:yellow;color:black;">@</span><span style="background:white;color:#2b91af;">Scripts</span><span style="background:white;color:black;">.Render(</span><span style="background:white;color:#a31515;">"~/bundles/jquery"</span><span style="background:white;color:black;">)
        </span><span style="background:yellow;color:black;">@</span><span style="background:white;color:#2b91af;">Scripts</span><span style="background:white;color:black;">.Render(</span><span style="background:white;color:#a31515;">"~/bundles/jquery.signalR"</span><span style="background:white;color:black;">)
        </span><span style="background:white;color:blue;">&lt;</span><span style="background:white;color:maroon;">script </span><span style="background:white;color:red;">src</span><span style="background:white;color:blue;">="</span><span style="background:yellow;color:black;">@</span><span style="background:white;color:black;">Url.Content(</span><span style="background:white;color:#a31515;">"~/signalr/hubs"</span><span style="background:white;color:black;">)</span><span style="background:white;color:blue;">" </span><span style="background:white;color:red;">type</span><span style="background:white;color:blue;">="text/javascript"&gt;&lt;/</span><span style="background:white;color:maroon;">script</span><span style="background:white;color:blue;">&gt;
    &lt;/</span><span style="background:white;color:maroon;">head</span><span style="background:white;color:blue;">&gt;
&lt;</span><span style="background:white;color:maroon;">body</span><span style="background:white;color:blue;">&gt;
</span><span style="background:yellow;color:black;">@(</span><span style="background:white;color:black;">X.ResourceManager()</span><span style="background:yellow;color:black;">)
@(</span><span style="background:white;color:black;">X.Viewport().Padding(20).Items()

.Add(X.Button().Icon(</span><span style="background:white;color:#2b91af;">Icon</span><span style="background:white;color:black;">.Add).Text(</span><span style="background:white;color:#a31515;">"New customer"</span><span style="background:white;color:black;">)
      .DirectClickAction(</span><span style="background:white;color:#a31515;">"AddCustomer"</span><span style="background:white;color:black;">, </span><span style="background:white;color:#a31515;">"Customers"</span><span style="background:white;color:black;">)) 

.Add(X.Button().Icon(</span><span style="background:white;color:#2b91af;">Icon</span><span style="background:white;color:black;">.Delete).Text(</span><span style="background:white;color:#a31515;">"Delete customer"</span><span style="background:white;color:black;">)
      .DirectClickAction(</span><span style="background:white;color:#a31515;">"DeleteCustomer"</span><span style="background:white;color:black;">, </span><span style="background:white;color:#a31515;">"Customers"</span><span style="background:white;color:black;">))

.Add(X.GridPanel().Title(</span><span style="background:white;color:#a31515;">"Customers"</span><span style="background:white;color:black;">).MarginSpec(</span><span style="background:white;color:#a31515;">"10 0 0 0"</span><span style="background:white;color:black;">)</span><span style="background:white;color:black;">.Icon(</span><span style="background:white;color:#2b91af;">Icon</span><span style="background:white;color:black;">.User)
      .Store(X.Store()
              .AutoLoad(</span><span style="background:white;color:blue;">true</span><span style="background:white;color:black;">)
              .Proxy(X.AjaxProxy().Url(</span><span style="background:white;color:#a31515;">"/customers/all"</span><span style="background:white;color:black;">).Reader(X.JsonReader()))
              .Model(X.Model()
                      .Fields(fields =&gt;
                      {
                        fields.Add(X.ModelField().Name(</span><span style="background:white;color:#a31515;">"Id"</span><span style="background:white;color:black;">));
                        fields.Add(X.ModelField().Name(</span><span style="background:white;color:#a31515;">"Name"</span><span style="background:white;color:black;">));
                        fields.Add(X.ModelField().Name(</span><span style="background:white;color:#a31515;">"Surname"</span><span style="background:white;color:black;">));
                        fields.Add(X.ModelField().Name(</span><span style="background:white;color:#a31515;">"Email"</span><span style="background:white;color:black;">));
                      })))
              .ColumnModel(columnModel =&gt;
              {
                columnModel.Columns.Add(X.Column().Text(</span><span style="background:white;color:#a31515;">"Name"</span><span style="background:white;color:black;">).DataIndex(</span><span style="background:white;color:#a31515;">"Name"</span><span style="background:white;color:black;">).Flex(1));
                columnModel.Columns.Add(X.Column().Text(</span><span style="background:white;color:#a31515;">"Surname"</span><span style="background:white;color:black;">).DataIndex(</span><span style="background:white;color:#a31515;">"Surname"</span><span style="background:white;color:black;">).Flex(1));
                columnModel.Columns.Add(X.Column().Text(</span><span style="background:white;color:#a31515;">"Email"</span><span style="background:white;color:black;">).DataIndex(</span><span style="background:white;color:#a31515;">"Email"</span><span style="background:white;color:black;">).Flex(1));
              })
              .MessageBusListeners(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">MessageBusListener 
              </span><span style="background:white;color:black;">{   
                 Name = </span><span style="background:white;color:#a31515;">"Customers.*"</span><span style="background:white;color:black;">,
                 Handler = </span><span style="background:white;color:#a31515;">"this.getStore().reload();"</span><span style="background:white;color:black;">,
                 Buffer = 500
              }))

.Add(X.GridPanel().Title(</span><span style="background:white;color:#a31515;">"Events log"</span><span style="background:white;color:black;">).MarginSpec(</span><span style="background:white;color:#a31515;">"10 0 0 0"</span><span style="background:white;color:black;">).Icon(</span><span style="background:white;color:#2b91af;">Icon</span><span style="background:white;color:black;">.Report)
      .Store(X.Store()
      .Model(X.Model()
              .Fields(fields =&gt;
                          {
                              fields.Add(X.ModelField().Name(</span><span style="background:white;color:#a31515;">"EventId"</span><span style="background:white;color:black;">));
                              fields.Add(X.ModelField().Name(</span><span style="background:white;color:#a31515;">"DateTime"</span><span style="background:white;color:black;">));
                              fields.Add(X.ModelField().Name(</span><span style="background:white;color:#a31515;">"Name"</span><span style="background:white;color:black;">));
                              fields.Add(X.ModelField().Name(</span><span style="background:white;color:#a31515;">"Data"</span><span style="background:white;color:black;">));
                          })))
                    .ColumnModel(columnModel =&gt;
                    {
                        columnModel.Columns.Add(X.Column().Text(</span><span style="background:white;color:#a31515;">"EventId"</span><span style="background:white;color:black;">).DataIndex(</span><span style="background:white;color:#a31515;">"EventId"</span><span style="background:white;color:black;">).Flex(1));
                        columnModel.Columns.Add(X.Column().Text(</span><span style="background:white;color:#a31515;">"DateTime"</span><span style="background:white;color:black;">).DataIndex(</span><span style="background:white;color:#a31515;">"DateTime"</span><span style="background:white;color:black;">).Flex(1));
                        columnModel.Columns.Add(X.Column().Text(</span><span style="background:white;color:#a31515;">"Event name"</span><span style="background:white;color:black;">).DataIndex(</span><span style="background:white;color:#a31515;">"Name"</span><span style="background:white;color:black;">).Flex(1));
                        columnModel.Columns.Add(X.Column().Text(</span><span style="background:white;color:#a31515;">"Event data"</span><span style="background:white;color:black;">).DataIndex(</span><span style="background:white;color:#a31515;">"Data"</span><span style="background:white;color:black;">).Flex(1));
                    })
                    .MessageBusListeners(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">MessageBusListener
                    </span><span style="background:white;color:black;">{
                        Name = </span><span style="background:white;color:#a31515;">"Customers.*"</span><span style="background:white;color:black;">,
                        Handler = </span><span style="background:white;color:#a31515;">"this.getStore().add({ EventId: data.Id, DateTime: getFormattedDateTime(), 
</span><span style="background:white;color:#a31515;">                                   Name: name, Data: \"CustomerId: \" + data.CustomerId });"</span>
<span style="background:white;color:black;">}))</span><span style="background:yellow;color:black;">)
</span><span style="background:white;color:blue;">&lt;</span><span style="background:white;color:maroon;">script </span><span style="background:white;color:red;">type</span><span style="background:white;color:blue;">="text/javascript"&gt;      
</span><strong><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">loadHub = </span><span style="background:white;color:blue;">function </span><span style="background:white;color:black;">() {
    </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">hubProxy = $.connection.applicationHub;
    hubProxy.client.publish = </span><span style="background:white;color:blue;">function </span><span style="background:white;color:black;">(name, message) {
        Ext.net.Bus.publish(name, message);
    };
    $.connection.hub.start().done(</span><span style="background:white;color:blue;">function </span><span style="background:white;color:black;">() {
        Ext.net.Notification.show({
            title: </span><span style="background:white;color:#a31515;">"Info"</span><span style="background:white;color:black;">,
            iconCls: </span><span style="background:white;color:#a31515;">"#Accept"</span><span style="background:white;color:black;">,
            html: </span><span style="background:white;color:#a31515;">"SignalR connection is active!"
        </span><span style="background:white;color:black;">});
    });
};

$(document).ready(</span><span style="background:white;color:blue;">function </span><span style="background:white;color:black;">() {
    loadHub();
});</span></strong>

<span style="background:white;color:blue;">&lt;/</span><span style="background:white;color:maroon;">script</span><span style="background:white;color:blue;">&gt;    
&lt;/</span><span style="background:white;color:maroon;">body</span><span style="background:white;color:blue;">&gt;
&lt;/</span><span style="background:white;color:maroon;">html</span><span style="background:white;color:blue;">&gt;
</span></pre>
<p>As you can see, the view is composed by the following Ext.NET components:</p>
<p>&#8211; A couple of buttons which send commands to the server (e.g. Add/Remove a customer)<br />
&#8211; A grid panel which holds the current customer data<br />
&#8211; A grid panel which holds trace data about messages received through the SignalR connection.<br />
<a href="https://dariosantarelli.wordpress.com/wp-content/uploads/2013/10/ss.jpg" target="_blank"><img class="aligncenter" alt="" src="https://dariosantarelli.wordpress.com/wp-content/uploads/2013/10/ss.jpg?w=300" /></a></p>
<p>The integration between the client-side SignalR hub proxy and the Ext.NET components MessageBus is done through the <strong>loadHub</strong> javascript function: it wraps the SignalR hub named &#8220;applicationHub&#8221; so that all the received messages are redirected to the Ext.NET MessageBus and again to the listening UI components. Please note that the SignalR &#8220;<em>publish</em>&#8221; function and the Ext.NET MessageBus &#8220;<em>publish</em>&#8221; function accept the same parameters: the message name and the message data. For this reason, the integration between the two worlds is practically natural.</p>
<p>In the example above, the <em>Store</em> of the former <em>GridPanel</em> is reloaded each time its MessageBusListener intercepts any message whose name starts with the prefix &#8220;<em>Customers.</em>&#8221; . Please pay attention to the <em>Buffer</em> property: it&#8217;s very useful when the component is under message storming and we want the UI to be refreshed just after a specified delay during which no messages have been received.</p>
<p>What about server-side code? Well, the server-side code is not so relevant in this post. The most important thing to be considered here is that at some point of the server-side command execution, the code retrieves the SignalR hub, selects which clients will receive the RPC (for simplicity, in this example a message is sent to all connected clients) and finally pushes a message containing the data the client needs for updating UI. Here an example:</p>
<pre class="code" style="font-size:13px;"><span style="background:white;color:#2b91af;">GlobalHost</span><span style="background:white;color:black;">.ConnectionManager.GetHubContext&lt;</span><span style="background:white;color:#2b91af;">ApplicationHub</span><span style="background:white;color:black;">&gt;()
</span><span style="background:white;color:black;">          .Clients.All.publish(</span><span style="background:white;color:#a31515;">"Customers.Added"</span><span style="background:white;color:black;">, </span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">CustomerAdded </span><span style="background:white;color:black;">{ ...&lt;data for clients&gt;... });</span></pre>
<p><strong>Useful links</strong></p>
<ul>
<li><a href="http://mvc.ext.net/#/MessageBus_Basic/Simple/" target="_blank">Ext.NET MessageBus example</a></li>
<li><a href="http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/introduction-to-signalr" target="_blank">Introduction to SignalR</a></li>
<li><a href="http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server" target="_blank">ASP.NET SignalR Hubs API Guide</a></li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2013/10/20/asp-net-signalr-and-ext-net-messagebus/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>

		<media:content url="https://dariosantarelli.wordpress.com/wp-content/uploads/2013/10/picture12.png?w=700" medium="image" />

		<media:content url="https://dariosantarelli.wordpress.com/wp-content/uploads/2013/10/ss.jpg?w=300" medium="image" />
	</item>
		<item>
		<title>Two new projects released!</title>
		<link>https://dariosantarelli.wordpress.com/2013/03/22/two-new-projects-released/</link>
					<comments>https://dariosantarelli.wordpress.com/2013/03/22/two-new-projects-released/#respond</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Fri, 22 Mar 2013 20:52:57 +0000</pubDate>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[About Me...]]></category>
		<category><![CDATA[Microsoft Technology]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[WPF]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=600</guid>

					<description><![CDATA[I&#8217;ve just published two new projects I&#8217;ve worked on in the last months: LogLive LogLive is free software for Windows written in .NET (WPF 4) that enables you to perform real-time monitoring on different types of log sources through components called “listeners”. TextTableFormatter.NET TextTableFormatter is a .NET porting of Java TextTableFormatter. This library renders tables [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I&#8217;ve just published two new projects I&#8217;ve worked on in the last months:</p>
<h2><span style="line-height:13px;"><strong><a title="LogLive" href="https://dariosantarelli.wordpress.com/loglive/" target="_blank">LogLive</a></strong></span></h2>
<p><span style="line-height:13px;">LogLive is free software for Windows written in .NET (WPF 4) that enables you to perform real-time monitoring on different types of log sources through components called “listeners”.</span></p>
<h2><strong><a title="TextTableFormatter.NET" href="https://texttableformatter.codeplex.com/" target="_blank">TextTableFormatter.NET</a></strong></h2>
<p>TextTableFormatter is a .NET porting of <a title="Java TextTableFormatter" href="http://texttablefmt.sourceforge.net/" target="_blank">Java TextTableFormatter</a>.<br />
This library renders tables made of characters. The user add cells and can add format characteristics like predefined/custom table styles, text alignment, abbreviation, column width, border types, colspan, etc.</p>
<p>In the next months I will publish other projects, so please stay tuned! <img src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2013/03/22/two-new-projects-released/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>C# dynamic dispatch and class inheritance</title>
		<link>https://dariosantarelli.wordpress.com/2012/12/08/c-dynamic-dispatch-and-class-inheritance/</link>
					<comments>https://dariosantarelli.wordpress.com/2012/12/08/c-dynamic-dispatch-and-class-inheritance/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sat, 08 Dec 2012 19:38:20 +0000</pubDate>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft Technology]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[DLR]]></category>
		<category><![CDATA[Dynamic dispatch]]></category>
		<category><![CDATA[runtime]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=497</guid>

					<description><![CDATA[I believe dynamic dispatch is a very cool feature of C# 4.0. It was designed to simplify interop between statically typed C# and dynamically typed languages or COM components by deferring method resolution at runtime, dynamically applying the same overload selection logic that the C# compiler would normally use at compile time. This feature is [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I believe dynamic dispatch is a very cool feature of C# 4.0. It was designed to simplify interop between statically typed C# and dynamically typed languages or COM components by deferring method resolution at runtime, dynamically applying the same overload selection logic that the C# compiler would normally use at compile time. This feature is known as <a href="http://en.wikipedia.org/wiki/Multiple_dispatch" target="_blank">single/multiple dispatch</a>. A common usage of this technique can be found in many <a href="http://code.logos.com/blog/2010/03/the_visitor_pattern_and_dynamic_in_c_4.html" target="_blank">implementations of the visitor pattern</a>. Maybe you have already read something like this:</p>
<pre class="code" style="font-size:12px;"><span style="background:white;color:blue;">public class </span><span style="background:white;color:#2b91af;">MessageHandler
</span><span style="background:white;color:black;">{
    </span><span style="background:white;color:blue;">public void </span><span style="background:white;color:black;">HandleMessage(</span><span style="background:white;color:#2b91af;">Message </span><span style="background:white;color:black;">message)
    {
        ProcessMessage((</span><span style="background:white;color:blue;">dynamic</span><span style="background:white;color:black;">)message);
    }
    </span><span style="background:white;color:blue;">protected void </span><span style="background:white;color:black;">ProcessMessage(</span><span style="background:white;color:#2b91af;">MessageA </span><span style="background:white;color:black;">messageA)
    {
        </span><span style="background:white;color:#2b91af;">Console</span><span style="background:white;color:black;">.WriteLine(</span><span style="background:white;color:#a31515;">"MessageA processed"</span><span style="background:white;color:black;">);
    }

    </span><span style="background:white;color:blue;">protected void </span><span style="background:white;color:black;">ProcessMessage(</span><span style="background:white;color:#2b91af;">MessageB </span><span style="background:white;color:black;">messageB)
    {
        </span><span style="background:white;color:#2b91af;">Console</span><span style="background:white;color:black;">.WriteLine(</span><span style="background:white;color:#a31515;">"MessageB processed"</span><span style="background:white;color:black;">);
    }
}</span></pre>
<p>This code works great when you don&#8217;t know the exact type beforehand and you don&#8217;t want to use a big switch statement. If you use dynamic dispatch within the same class everything should work as expected. So, if you execute the following lines of code..</p>
<pre class="code" style="font-size:12px;"><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">messageHandler = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">MessageHandler</span><span style="background:white;color:black;">();
messageHandler.HandleMessage(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">MessageA</span><span style="background:white;color:black;">());
messageHandler.HandleMessage(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">MessageB</span><span style="background:white;color:black;">());</span></pre>
<p>&#8230;the console output would be the following:</p>
<p style="font-family:'Courier New';"><strong>MessageA processed<br />
MessageB processed</strong></p>
<p>OK, but what happens if you introduce a class derived from <em>MessageHandler</em> in order to separate message handling?</p>
<p><strong><span style="font-size:medium;">The problem</span></strong></p>
<p>Let’s suppose to have an <em>DefaultMessageHandler</em> that holds the fallback message handling method and a <em>DerivedMessageHandler</em> which holds methods for some specific messages.</p>
<pre class="code" style="font-size:12px;"><span style="background:white;color:blue;">public abstract class </span><span style="background:white;color:#2b91af;">Message </span><span style="background:white;color:black;">{ }
</span><span style="background:white;color:blue;">public class </span><span style="background:white;color:#2b91af;">MessageA </span><span style="background:white;color:black;">: </span><span style="background:white;color:#2b91af;">Message </span><span style="background:white;color:black;">{ }
</span><span style="background:white;color:blue;">public class </span><span style="background:white;color:#2b91af;">MessageB </span><span style="background:white;color:black;">: </span><span style="background:white;color:#2b91af;">Message </span><span style="background:white;color:black;">{ }
</span><span style="background:white;color:blue;">public class </span><span style="background:white;color:#2b91af;">MessageC </span><span style="background:white;color:black;">: </span><span style="background:white;color:#2b91af;">Message </span><span style="background:white;color:black;">{ }

</span><span style="background:white;color:blue;">public class </span><span style="background:white;color:#2b91af;">DefaultMessageHandler
</span><span style="background:white;color:black;">{
    </span><span style="background:white;color:blue;">public void </span><span style="background:white;color:black;">HandleMessage(</span><span style="background:white;color:#2b91af;">Message </span><span style="background:white;color:black;">message)
    {
        ProcessMessage((</span><span style="background:white;color:blue;">dynamic</span><span style="background:white;color:black;">)message);
    }

    </span><span style="background:white;color:blue;">protected void </span><span style="background:white;color:black;">ProcessMessage(</span><span style="background:white;color:#2b91af;">Message </span><span style="background:white;color:black;">message)
    {
        </span><span style="background:white;color:#2b91af;">Console</span><span style="background:white;color:black;">.WriteLine(</span><span style="background:white;color:#a31515;">"Message processed"</span><span style="background:white;color:black;">);
    }

    </span><span style="background:white;color:blue;">protected void </span><span style="background:white;color:black;">ProcessMessage(</span><span style="background:white;color:#2b91af;">MessageA </span><span style="background:white;color:black;">messageA)
    {
        </span><span style="background:white;color:#2b91af;">Console</span><span style="background:white;color:black;">.WriteLine(</span><span style="background:white;color:#a31515;">"MessageA processed"</span><span style="background:white;color:black;">);
    }
}

</span><span style="background:white;color:blue;">public class </span><span style="background:white;color:#2b91af;">DerivedMessageHandler </span><span style="background:white;color:black;">: </span><span style="background:white;color:#2b91af;">DefaultMessageHandler
</span><span style="background:white;color:black;">{
    </span><span style="background:white;color:blue;">protected void </span><span style="background:white;color:black;">ProcessMessage(</span><span style="background:white;color:#2b91af;">MessageB </span><span style="background:white;color:black;">messageB)
    {
        </span><span style="background:white;color:#2b91af;">Console</span><span style="background:white;color:black;">.WriteLine(</span><span style="background:white;color:#a31515;">"MessageB processed"</span><span style="background:white;color:black;">);
    }

    </span><span style="background:white;color:blue;">protected void </span><span style="background:white;color:black;">ProcessMessage(</span><span style="background:white;color:#2b91af;">MessageC </span><span style="background:white;color:black;">messageC)
    {
        </span><span style="background:white;color:#2b91af;">Console</span><span style="background:white;color:black;">.WriteLine(</span><span style="background:white;color:#a31515;">"MessageC processed"</span><span style="background:white;color:black;">);
    }
}</span></pre>
<p>When we try to execute the following lines of code&#8230;</p>
<pre class="code" style="font-size:12px;"><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">messageHandler = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">DerivedMessageHandler</span><span style="background:white;color:black;">();
messageHandler.HandleMessage(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">MessageA</span><span style="background:white;color:black;">());
messageHandler.HandleMessage(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">MessageB</span><span style="background:white;color:black;">());
</span><span style="background:white;color:black;">messageHandler.HandleMessage(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">MessageC</span><span style="background:white;color:black;">());</span></pre>
<p class="MsoNormal" style="line-height:13pt;margin:0 0 10pt;">&#8230;the console output is&#8230;</p>
<p style="font-family:'Courier New';"><strong><span style="color:#ff0000;"><span style="color:#008000;">MessageA processed</span><br />
</span><span style="color:#ff0000;">Message processed<br />
Message processed</span></strong></p>
<p>The problem here is that every call to the <em>ProcessMessage</em> method via dynamic dispatch is linked to the only implementation of the method that is found in the <em>DefaultMessageHandler</em> class, and the ones in the derived classes will never be executed. At first glance, this behaviour could be not so easy to expect.</p>
<p><strong><span style="font-size:medium;">A simple solution</span></strong></p>
<p>In order for our code to work as expected we could just override the <em>HandleMessage</em> method in the <em>DerivedMessageHandler</em> class, leaving it exactly the same as the one defined in the base class. As alternative, we could completely move the <em>HandleMessage</em> method to derived classes.</p>
<pre class="code" style="font-size:12px;"><span style="background:white;color:blue;">public class </span><span style="background:white;color:#2b91af;">DefaultMessageHandler
</span><span style="background:white;color:black;">{
    </span><strong><span style="background-color:white;color:blue;background-position:initial initial;background-repeat:initial initial;">public virtual void </span><span style="background-color:white;color:black;background-position:initial initial;background-repeat:initial initial;">HandleMessage(</span><span style="background-color:white;color:#2b91af;background-position:initial initial;background-repeat:initial initial;">Message </span><span style="background-color:white;color:black;background-position:initial initial;background-repeat:initial initial;">message)
    {
        ProcessMessage((</span><span style="background-color:white;color:blue;background-position:initial initial;background-repeat:initial initial;">dynamic</span><span style="background-color:white;color:black;background-position:initial initial;background-repeat:initial initial;">)message);
    }

    </span></strong><span style="background:white;color:blue;">protected void </span><span style="background:white;color:black;">ProcessMessage(</span><span style="background:white;color:#2b91af;">Message </span><span style="background:white;color:black;">message)
    {
        </span><span style="background:white;color:#2b91af;">Console</span><span style="background:white;color:black;">.WriteLine(</span><span style="background:white;color:#a31515;">"Message processed"</span><span style="background:white;color:black;">);
    }

    </span><span style="background:white;color:blue;">protected void </span><span style="background:white;color:black;">ProcessMessage(</span><span style="background:white;color:#2b91af;">MessageA </span><span style="background:white;color:black;">messageA)
    {
        </span><span style="background:white;color:#2b91af;">Console</span><span style="background:white;color:black;">.WriteLine(</span><span style="background:white;color:#a31515;">"MessageA processed"</span><span style="background:white;color:black;">);
    }
}

</span><span style="background:white;color:blue;">public class </span><span style="background:white;color:#2b91af;">DerivedMessageHandler </span><span style="background:white;color:black;">: </span><span style="background:white;color:#2b91af;">DefaultMessageHandler
</span><span style="background:white;color:black;">{
    </span><strong><span style="background:white;color:blue;">public override void </span><span style="background:white;color:black;">HandleMessage(</span><span style="background:white;color:#2b91af;">Message </span></strong><strong><span style="background:white;color:black;">message)
    {
        ProcessMessage((</span><span style="background:white;color:blue;">dynamic</span></strong><span style="background:white;color:black;"><strong>)message);
    }</strong>

    </span><span style="background:white;color:blue;">protected void </span><span style="background:white;color:black;">ProcessMessage(</span><span style="background:white;color:#2b91af;">MessageB </span><span style="background:white;color:black;">messageB)
    {
        </span><span style="background:white;color:#2b91af;">Console</span><span style="background:white;color:black;">.WriteLine(</span><span style="background:white;color:#a31515;">"MessageB processed"</span><span style="background:white;color:black;">);
    }

    </span><span style="background:white;color:blue;">protected void </span><span style="background:white;color:black;">ProcessMessage(</span><span style="background:white;color:#2b91af;">MessageC </span><span style="background:white;color:black;">messageC)
    {
        </span><span style="background:white;color:#2b91af;">Console</span><span style="background:white;color:black;">.WriteLine(</span><span style="background:white;color:#a31515;">"MessageC processed"</span><span style="background:white;color:black;">);
    }
}</span></pre>
<p>Now, if we try to handle specific messages&#8230;</p>
<pre class="code" style="font-size:12px;"><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">messageHandler = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">DerivedMessageHandler</span><span style="background:white;color:black;">();
messageHandler.HandleMessage(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">MessageA</span><span style="background:white;color:black;">());
messageHandler.HandleMessage(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">MessageB</span><span style="background:white;color:black;">());
messageHandler.HandleMessage(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">MessageC</span><span style="background:white;color:black;">());
messageHandler.HandleMessage(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">MessageD</span><span style="background:white;color:black;">());
</span></pre>
<p>&#8230;everything works as expected and the console output is</p>
<p style="font-family:'Courier New';"><strong><span style="color:#008000;">MessageA processed</span></strong><br />
<strong><span style="color:#008000;">MessageB processed</span></strong><br />
<strong><span style="color:#008000;">MessageC processed<br />
<strong>Message processed // fallback for MessageD</strong></span></strong></p>
<p>Please note that the fallback overload of the <em>ProcessMessage</em> method has been invoked for <em>MessageD</em> because a specific overload has not been dinamically found by the runtime binder.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2012/12/08/c-dynamic-dispatch-and-class-inheritance/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] From Visual to Bitmap</title>
		<link>https://dariosantarelli.wordpress.com/2012/10/21/wpf-from-visual-to-bitmap/</link>
					<comments>https://dariosantarelli.wordpress.com/2012/10/21/wpf-from-visual-to-bitmap/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sun, 21 Oct 2012 21:52:42 +0000</pubDate>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft Technology]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Graphics]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=486</guid>

					<description><![CDATA[I&#8217;d like to share a couple of extension methods that helped me in situations where I needed to convert some rendered WPF windows or controls to bitmaps. Many devs know how complex this task was in Windows Forms. Instead, in WPF it&#8217;s quite simple, at least if you&#8217;re familiar with the RenderTargetBitmap class, and the range of BitmapEncoders. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I&#8217;d like to share a couple of extension methods that helped me in situations where I needed to convert some rendered WPF windows or controls to bitmaps. Many devs know how complex this task was in Windows Forms. Instead, in WPF it&#8217;s quite simple, at least if you&#8217;re familiar with the <i><a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.rendertargetbitmap.aspx">RenderTargetBitmap</a> </i>class, and the range of <i><a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapencoder.aspx">BitmapEncoders</a>. </i>In order to convert a visual to a bitmap,<i> </i>I like to see something like this:</p>
<p><span style="font-family:'Courier New';"><span style="color:#000000;">myVisual.ToBitmapSource().ToPngFile(<span style="color:#a31515;">@&#8221;C:\ScreenShot.png&#8221;</span>);</span></span></p>
<p>The <em>ToBitmapSource()</em> extension method allows you to get a single, constant set of pixels at a certain size and resolution representing the visual (please note that a <em>BitmapSource </em>uses automatic codec discovery, based on the installed codecs on the user&#8217;s system). I&#8217;ve always found useful to replace the default black background that WPF reserves for transparency with a custom brush. So I introduced the <em>transparentBackground</em> parameter (default: white) which overrides the default black one.</p>
<div style="font-family:'Courier New';"><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">static</span><span style="color:#000000;"> </span><span style="color:#2b91af;">BitmapSource</span><span style="color:#000000;"> ToBitmapSource(</span><span style="color:#0000ff;">this</span><span style="color:#000000;"> </span><span style="color:#2b91af;">Visual</span><span style="color:#000000;"> visual, </span><span style="color:#2b91af;">Brush</span><span style="color:#000000;"> transparentBackground)</span><br />
<span style="color:#000000;">{</span><br />
<span style="color:#000000;">  </span><span style="color:#0000ff;">var</span><span style="color:#000000;"> bounds = </span><span style="color:#2b91af;">VisualTreeHelper</span><span style="color:#000000;">.GetDescendantBounds(visual);</span><br />
<span style="color:#000000;">  </span><span style="color:#0000ff;">var</span><span style="color:#000000;"> bitmapSource = </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">RenderTargetBitmap</span><span style="color:#000000;">((</span><span style="color:#2b91af;">Int32</span><span style="color:#000000;">)bounds.Width, (</span><span style="color:#2b91af;">Int32</span><span style="color:#000000;">)bounds.Height, 96, 96, </span><span style="color:#2b91af;">PixelFormats</span><span style="color:#000000;">.Pbgra32);</span><br />
<span style="color:#000000;">  </span><span style="color:#0000ff;">var</span><span style="color:#000000;"> drawingVisual = </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">DrawingVisual</span><span style="color:#000000;">();</span><span style="color:#0000ff;">  </span></div>
<div style="font-family:'Courier New';"></div>
<div style="font-family:'Courier New';">  <span style="color:#0000ff;">using</span><span style="color:#000000;"> (</span><span style="color:#0000ff;">var</span><span style="color:#000000;"> drawingContext = drawingVisual.RenderOpen())</span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;"> <span style="color:#000000;">  {</span><br />
<span style="color:#000000;">    </span><span style="color:#0000ff;">var</span><span style="color:#000000;"> visualBrush = </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">VisualBrush</span><span style="color:#000000;">(visual);</span></span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;">    drawingContext.DrawRectangle(transparentBackground, </span><span style="color:#0000ff;">null</span><span style="color:#000000;">, </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">Rect</span><span style="color:#000000;">(</span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">Point</span><span style="color:#000000;">(), bounds.Size));</span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;">    drawingContext.DrawRectangle(visualBrush, </span><span style="color:#0000ff;">null</span><span style="color:#000000;">, </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">Rect</span><span style="color:#000000;">(</span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">Point</span><span style="color:#000000;">(), bounds.Size));</span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;">  }</span></div>
<div style="font-family:'Courier New';">
<p><span style="color:#000000;font-family:'Courier New';">  bitmapSource.Render(drawingVisual);<br />
</span><span style="color:#0000ff;"><span style="color:#000000;">  </span></span><span style="color:#0000ff;">return</span><span style="color:#000000;"> bitmapSource;<br />
}</span></p>
<p><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">static</span><span style="color:#000000;"> </span><span style="color:#2b91af;">BitmapSource</span><span style="color:#000000;"> ToBitmapSource(</span><span style="color:#0000ff;">this</span><span style="color:#000000;"> </span><span style="color:#2b91af;">Visual</span><span style="color:#000000;"><span style="color:#000000;"> visual)</span><br />
<span style="color:#000000;">{</span><br />
<span style="color:#000000;">  </span><span style="color:#0000ff;">return</span><span style="color:#000000;"> visual.ToBitmapSource(</span><span style="color:#2b91af;">Brushes</span><span style="color:#000000;">.White);<br />
</span></span><span style="color:#000000;font-family:'Courier New';">}</span></p>
<p><span style="color:#000000;"><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">static void</span><span style="color:#000000;"> ToPngFile(</span><span style="color:#0000ff;">this</span><span style="color:#000000;"> </span><span style="color:#2b91af;">BitmapSource</span><span style="color:#000000;"> bitmapSource, </span><span style="color:#0000ff;">string</span><span style="color:#000000;"> fileName)</span><br />
<span style="color:#000000;">{</span><br />
<span style="color:#000000;">  var</span><span style="color:#000000;"> encoder = </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">PngBitmapEncoder</span><span style="color:#000000;">();</span><br />
<span style="color:#000000;">  encoder.Frames.Add(</span><span style="color:#2b91af;">BitmapFrame</span><span style="color:#000000;">.Create(bitmapSource));</span><br />
<span style="color:#000000;">  </span><span style="color:#0000ff;">using</span><span style="color:#000000;"> (</span><span style="color:#0000ff;">var</span><span style="color:#000000;"> file = </span><span style="color:#2b91af;">File</span><span style="color:#000000;">.Create(fileName)) encoder.Save(file);</span><span style="color:#000000;"><br />
}</span></span></p>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2012/10/21/wpf-from-visual-to-bitmap/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>Unity Interception Extension</title>
		<link>https://dariosantarelli.wordpress.com/2012/09/30/unity-interception-extension/</link>
					<comments>https://dariosantarelli.wordpress.com/2012/09/30/unity-interception-extension/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sun, 30 Sep 2012 10:31:39 +0000</pubDate>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft Technology]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Proxy]]></category>
		<category><![CDATA[Unity]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=366</guid>

					<description><![CDATA[Starting from Enterprise Library 5.0, Unity supports interception mechanisms which captures the call to an object at invocation time and provides the full implementation of the object through lightweight code generation (ILEmit). It&#8217;s something very similar to the aspect-oriented programming (AOP) approach. However, Unity is NOT an AOP framework implementation for the following reasons: It uses interception to [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Starting from <a href="http://msdn.microsoft.com/en-us/library/ff632023.aspx" target="_blank">Enterprise Library 5.0</a>, Unity supports interception mechanisms which captures the call to an object at invocation time and provides the full implementation of the object through lightweight code generation (<em>ILEmit</em>). It&#8217;s something very similar to the aspect-oriented programming (AOP) approach.</p>
<p>However, <span style="text-decoration:underline;"><strong>Unity is NOT an AOP framework implementation</strong></span> for the following reasons:</p>
<ul>
<li>It uses interception to enable only preprocessing behaviors and post-processing behaviors.</li>
<li>It does not insert code into methods, although it can create derived classes containing policy pipelines.</li>
<li>It does not provide interception for class constructors.</li>
</ul>
<h2>Instance Interception VS Type Interception</h2>
<p>With <strong>instance interception</strong>, when the application resolves the object through the container,</p>
<ol>
<li>The Unity interception container obtains a new or an existing instance of the object and creates a proxy.</li>
<li>Then it creates the handler pipeline and connects it to the target object before returning a reference to the proxy.</li>
<li>The client then calls methods and sets properties on the proxy as though it were the target object.</li>
</ol>
<div data-shortcode="caption" id="attachment_444" style="width: 610px" class="wp-caption aligncenter"><a href="https://dariosantarelli.wordpress.com/wp-content/uploads/2012/09/ic404024.png"><img aria-describedby="caption-attachment-444" class=" " title="Instance Interception" src="https://dariosantarelli.wordpress.com/wp-content/uploads/2012/09/ic404024.png?w=600&#038;h=248" alt="" width="600" height="248" /></a><p id="caption-attachment-444" class="wp-caption-text">Interface interception</p></div>
<p>With <strong>type interception</strong> , the container uses a derived class instead of a proxy (it  resembles AOP techniques). Type interception avoids the possible performance penalties of using a proxy object by dynamically deriving a new class from the original class, and inserting calls to the behaviors that make up the pipeline. When the application resolves the required type through the Unity container,</p>
<ol>
<li>the Unity interception container extension creates the new derived type and passes it, rather than the resolved type, back to the caller.</li>
<li>Because the type passed to the caller derives from the original class, it can be used in the same way as the original class.</li>
<li>The caller simply calls the object, and the derived class will pass the call through the behaviors in the pipeline just as is done when using instance interception.</li>
</ol>
<div data-shortcode="caption" id="attachment_445" style="width: 610px" class="wp-caption aligncenter"><a href="https://dariosantarelli.wordpress.com/wp-content/uploads/2012/09/ic404025.png"><img aria-describedby="caption-attachment-445" title="Type Interception" src="https://dariosantarelli.wordpress.com/wp-content/uploads/2012/09/ic404025.png?w=600&#038;h=319" alt="" width="600" height="319" /></a><p id="caption-attachment-445" class="wp-caption-text">Type Interception</p></div>
<p>However, there are some limitations with this approach. It can only be used to intercept public and protected virtual methods, and cannot be used with existing object instances. In general, type interception is most suited to scenarios where you create objects especially to support interception and allow for the flexibility and decoupling provided by policy injection, or when you have mappings in your container for base classes that expose virtual methods.</p>
<h2>Interceptors and Behaviors</h2>
<p>Unity uses an <strong><em>Interceptor</em> </strong>class to specify <strong>how interception happens</strong>, and an <strong><em>InterceptionBehavior</em> </strong>class to describe <strong>what to do when an object is intercepted</strong>. There are three built-in interceptors in Unity:</p>
<ul>
<li><strong><a href="http://msdn.microsoft.com/en-us/library/microsoft.practices.unity.interceptionextension.virtualmethodinterceptor(v=pandp.20).aspx" target="_blank">VirtualMethodInterceptor</a></strong>: a type based interceptor that works by generating a new class on the fly that derives from the target class. It uses dynamic code generation to create a derived class that gets instantiated instead of the original, intercepted class and to hook up the call handlers. Interception only happens on virtual methods. You must set up interception at object creation time and cannot intercept an existing object.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/microsoft.practices.unity.interceptionextension.interfaceinterceptor(v=pandp.20).aspx" target="_blank"><strong>InterfaceInterceptor</strong></a>:  an instance interceptor that works by generating a proxy class on the fly for a single interface. It can proxy only one interface on the object. It uses dynamic code generation to create the proxy class. Proxy supports casting to all the interfaces or types of the target object. It only intercepts methods on a single interface. It cannot cast a proxy back to target object&#8217;s class or to other interfaces on the target object.</li>
<li><strong><a href="http://msdn.microsoft.com/en-us/library/microsoft.practices.unity.interceptionextension.transparentproxyinterceptor.aspx" target="_blank">TransparentProxyInterceptor</a></strong>: an instance interceptor that uses remoting proxies to do the interception. When the type to intercept is a MarshalByRefObject or when only methods from the type&#8217;s implemented interfaces need to be intercepted. The object must either implement an interface or inherit from <strong>System.MarshalByRefObject</strong>. If the marshal by reference object is not a base class, you can only proxy interface methods. The<strong>TransparentProxy</strong> process is much slower than a regular method call.</li>
</ul>
<p>Interception is based on <strong>one or a pipeline of behaviors</strong> that describe what to do when an object is intercepted. You can create your own custom behaviors by implementing the <strong><a href="http://msdn.microsoft.com/en-us/library/microsoft.practices.unity.interceptionextension.iinterceptionbehavior(v=pandp.20).aspx" target="_blank">IInterceptionBehavior</a> </strong>interface. The interception behaviors are added to a pipeline and are called for each invocation of that pipeline, as shown below.</p>
<p style="text-align:center;"><a href="https://dariosantarelli.wordpress.com/wp-content/uploads/2012/09/image.png"><img class="aligncenter" title="Unity interception pipeline" src="https://dariosantarelli.wordpress.com/wp-content/uploads/2012/09/image.png?w=600&#038;h=229" alt="" width="600" height="229" /></a></p>
<p>Here an example of interception behavior which intercepts a call to a method and logs some useful info if the call throws an exception internally:</p>
<div></div>
<div></div>
<p><span style="font-family:'Courier New';"><span style="color:#0000ff;">public </span><span style="color:#0000ff;">class </span><span style="color:#2b91af;">ExceptionLoggerInterceptionBehavior</span><span style="color:#000000;"> : </span><span style="color:#2b91af;"><span style="color:#2b91af;">IInterceptionBehavior</span><br />
<span style="color:#000000;">{<br />
</span><span style="color:#000000;">  </span><span style="color:#0000ff;">private </span><span style="color:#0000ff;">readonly </span><span style="color:#2b91af;">ILogger</span><span style="color:#000000;"> _logger;</span></span><span style="color:#0000ff;"> </span></span></p>
<div style="font-family:'Courier New';"></div>
<div style="font-family:'Courier New';"><span style="color:#0000ff;">  public</span><span style="color:#000000;"> ExceptionLogInterceptionBehavior(</span><span style="color:#2b91af;">ILogger</span><span style="color:#000000;"> logger)</span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;">  {</span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;">    _logger = logger;<br />
</span><span style="color:#000000;font-family:'Courier New';">  }</span></div>
<div style="font-family:'Courier New';"></div>
<div style="font-family:'Courier New';"><span style="color:#0000ff;">  </span></div>
<div style="font-family:'Courier New';"><span style="color:#0000ff;">  public <span style="color:#2b91af;">IEnumerable</span><span style="color:#000000;">&lt;</span><span style="color:#2b91af;">Type</span><span style="color:#000000;">&gt; GetRequiredInterfaces() </span><span style="color:#000000;font-family:'Courier New';">{ </span>return <span style="color:#2b91af;">Type</span><span style="color:#000000;">.EmptyTypes; </span><span style="color:#000000;font-family:'Courier New';">}</span></span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;font-family:'Courier New';"><span style="color:#000000;font-family:'Courier New';"><br />
</span></span><span style="color:#0000ff;">  public </span><span style="color:#2b91af;">IMethodReturn</span><span style="color:#000000;"> Invoke(</span><span style="color:#2b91af;">IMethodInvocation</span><span style="color:#000000;"> input, </span><span style="color:#2b91af;">GetNextInterceptionBehaviorDelegate </span><span style="color:#000000;">getNext)</span><span style="color:#000000;"> <span style="color:#000000;">    </span></span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;"><span style="color:#000000;">  {</span><br />
<span style="color:#000000;">      </span><span style="color:#2b91af;">IMethodReturn</span><span style="color:#000000;"> result = getNext()(input, getNext);</span><br />
<span style="color:#000000;"><br />
</span><span style="color:#000000;">      </span><span style="color:#0000ff;">if</span><span style="color:#000000;"> (result.Exception != </span><span style="color:#0000ff;">null</span><span style="color:#000000;">)</span><br />
<span style="color:#000000;">      {</span><br />
<span style="color:#000000;">        _logger.Log(</span><span style="color:#0000ff;">string</span><span style="color:#000000;">.Format(</span><span style="color:#a31515;">&#8220;Exception occurred in </span><span style="color:#3cb371;">{0}</span><span style="color:#a31515;">.\nParameters: </span><span style="color:#3cb371;">{1}</span><span style="color:#a31515;">\nException: </span><span style="color:#3cb371;">{2}</span><span style="color:#a31515;">&#8220;</span><span style="color:#000000;">,</span><br />
<span style="color:#000000;">                               input.MethodBase,</span><br />
<span style="color:#000000;">                               </span><span style="color:#0000ff;">string</span><span style="color:#000000;">.Join(</span><span style="color:#a31515;">&#8220;,&#8221;</span><span style="color:#000000;">, input.Inputs.Cast&lt;</span><span style="color:#0000ff;">object</span><span style="color:#000000;">&gt;()),</span></span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;"><span style="color:#000000;">                               result.Exception));</span></span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;"><span style="color:#000000;">      }<br />
</span></span><span style="color:#0000ff;">      return</span><span style="color:#000000;"> result;</span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;">  }</span></div>
<div style="font-family:'Courier New';"></div>
<div style="font-family:'Courier New';"><span style="color:#0000ff;">  </span></div>
<div style="font-family:'Courier New';"><span style="color:#0000ff;">  public </span><span style="color:#0000ff;">bool</span><span style="color:#000000;"> WillExecute</span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;"> <span style="color:#000000;">  {</span><br />
<span style="color:#000000;">    </span><span style="color:#0000ff;">get</span><span style="color:#000000;"> { </span><span style="color:#0000ff;">return </span><span style="color:#0000ff;">true</span><span style="color:#000000;">; }<br />
</span></span><span style="color:#000000;font-family:'Courier New';">  }<br />
</span><span style="color:#000000;font-family:'Courier New';">}</span></div>
<div style="font-family:'Courier New';"></div>
<div style="margin-bottom:10px;"></div>
<p>In detail, you must provide an implementation of the two <em>IInterceptionBehavior </em>interface methods, <em>Invoke() </em>and <em>GetRequiredInterfaces()</em>, and set the <em>WillExecute </em>property.</p>
<ul>
<li>The <strong><em>WillExecute </em></strong>property indicate if the behavior perform any operation when invoked. This is used to optimize interception. If the behaviors won&#8217;t actually do anything (for example, PIAB where no policies match) then the interception mechanism can be skipped completely.</li>
<li>The <strong><em>GetRequiredInterfaces </em></strong>method returns the interfaces required by the behavior for the intercepted objects. The <em>Invoke </em>method execute the behavior processing.</li>
<li>The <strong><em>Invoke </em></strong>method has two parameters: <em>input </em>and <em>getNext</em>. The <em>input </em>parameter rapresents the current call to the original method, the <em>getNext </em>parameter is a delegate to execute to get the next delegate in the behavior chain.</li>
</ul>
<p>Now let&#8217;s see an example of usage.  The following code executes a statement that makes my <em>IService</em> implementation raise an ArgumentNullException. This exception will be logged thanks to the <em>ExceptionLoggerInterceptionBehavior</em> registered for my <em>IService</em> interface.</p>
<p><span style="font-family:'Courier New';"><span style="color:#0000ff;">new </span><span style="color:#2b91af;">UnityContainer</span><span style="color:#000000;">()</span><br />
<span style="color:#000000;">    .AddNewExtension&lt;</span><span style="color:#2b91af;">Interception</span><span style="color:#000000;">&gt;()</span><br />
<span style="color:#000000;">    .RegisterType&lt;</span><span style="color:#2b91af;">ILogger</span><span style="color:#000000;">, </span><span style="color:#2b91af;">ConsoleLogger</span><span style="color:#000000;">&gt;()</span><br />
<span style="color:#000000;">    .RegisterType&lt;</span><span style="color:#2b91af;">IService</span><span style="color:#000000;">, </span><span style="color:#2b91af;">Service</span><span style="color:#000000;">&gt;(</span><span style="color:#0000ff;">new </span><span style="color:#2b91af;">Interceptor</span><span style="color:#000000;">&lt;</span><span style="color:#2b91af;">InterfaceInterceptor</span><span style="color:#000000;">&gt;(),</span><br />
<span style="color:#000000;">                                     </span><span style="color:#0000ff;">new </span><span style="color:#2b91af;">InterceptionBehavior</span><span style="color:#000000;">&lt;</span><span style="color:#2b91af;">ExceptionLoggingInterceptionBehavior</span><span style="color:#000000;">&gt;())<br />
.Resolve&lt;<span style="color:#2b91af;">IService</span>&gt;()<br />
.Process(<span style="color:#0000ff;">null</span>); <span style="color:#008000;">// It throws ArgumentNullException!!!</span></span></span></p>
<p>If we open the Console output window we&#8217;ll find something like this&#8230;</p>
<p><span style="font-family:'Courier New';"><span style="color:#1e1e1e;">Exception occurred in MyNamespace.Response Process(MyNamespace.Request).<br />
Parameters:<br />
Exception: System.ArgumentNullException: Value cannot be null.<br />
Parameter name: request<br />
at MyNamespace.Service.Process(Request request) in &#8230;<br />
at <strong>DynamicModule.ns.Wrapped_IService_1cccb54f8a8b4109a353b589ea96c30e</strong>.&lt;Process_DelegateImplementation&gt;__0(IMethodInvocation inputs, GetNextInterceptionBehaviorDelegate getNext)<br />
</span></span></p>
<p><span style="font-family:Consolas;"><span style="color:#1e1e1e;">A first chance exception of type &#8216;System.ArgumentNullException&#8217; occurred in <strong>Unity_ILEmit_InterfaceProxies</strong></span></span></p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2012/09/30/unity-interception-extension/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>

		<media:content url="https://dariosantarelli.wordpress.com/wp-content/uploads/2012/09/ic404024.png" medium="image">
			<media:title type="html">Instance Interception</media:title>
		</media:content>

		<media:content url="https://dariosantarelli.wordpress.com/wp-content/uploads/2012/09/ic404025.png" medium="image">
			<media:title type="html">Type Interception</media:title>
		</media:content>

		<media:content url="https://dariosantarelli.wordpress.com/wp-content/uploads/2012/09/image.png" medium="image">
			<media:title type="html">Unity interception pipeline</media:title>
		</media:content>
	</item>
		<item>
		<title>Unity container and the Decorator Pattern</title>
		<link>https://dariosantarelli.wordpress.com/2012/09/12/unity-container-and-decorator-pattern/</link>
					<comments>https://dariosantarelli.wordpress.com/2012/09/12/unity-container-and-decorator-pattern/#respond</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Wed, 12 Sep 2012 20:37:46 +0000</pubDate>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft Technology]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Decorator pattern]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[Unity]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=351</guid>

					<description><![CDATA[In these days I&#8217;m using Unity as IoC and DI container in a project. One of the &#8220;must-have&#8221; features of a modern container is the ability to be configured at runtime, preferably with a  fluent mapping registration interface. Moreover, one of the expected features is the support for decorator or chain object pattern configurations with intuitive [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In these days I&#8217;m using <a title="Unity container" href="http://msdn.microsoft.com/en-us/library/ff647202.aspx" target="_blank">Unity</a> as IoC and DI container in a project. One of the &#8220;must-have&#8221; features of a modern container is the ability to be configured at runtime, preferably with a  fluent mapping registration interface. Moreover, one of the expected features is the support for decorator or chain object pattern configurations with intuitive code. A simple scenario could be something like this:</p>
<div style="font-family:'Courier New';">
<p><span style="color:#0000ff;">public </span><span style="color:#0000ff;">interface </span><span style="color:#2b91af;">IService</span><span style="color:#000000;"> {}</span></p>
<p><span style="color:#0000ff;">public </span><span style="color:#0000ff;">class </span><span style="color:#2b91af;">Service</span><span style="color:#000000;"> : </span><span style="color:#2b91af;">IService</span><span style="color:#000000;"> {}</span></p>
<p><span style="color:#0000ff;">public </span><span style="color:#0000ff;">class </span><span style="color:#2b91af;">ServiceDecorator</span><span style="color:#000000;"> : </span><span style="color:#2b91af;">IService<br />
</span><span style="color:#000000;">{<br />
</span><span style="color:#0000ff;"><span style="color:#000000;">  </span></span><span style="color:#0000ff;">protected </span><span style="color:#2b91af;">IService</span><span style="color:#000000;"> DecoratedService { </span><span style="color:#0000ff;">get</span><span style="color:#000000;">; </span><span style="color:#0000ff;">private </span><span style="color:#0000ff;">set</span><span style="color:#000000;">; }</span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">  </span></span><span style="color:#0000ff;">public</span><span style="color:#000000;"> ServiceDecorator(</span><span style="color:#2b91af;">IService</span><span style="color:#000000;"> service)<br />
</span><span style="color:#000000;">  {<br />
</span><span style="color:#000000;">    DecoratedService = service;<br />
</span><span style="color:#000000;">  }<br />
</span><span style="color:#000000;">}</span></p>
</div>
<p>The intent is straightforward and quite common: registering the relationship between the <em>Service</em> and the <em>ServiceDecorator </em>class, so when someone asks for an <em>IService</em>, he gets a <em>Service</em> instance wrapped in a <em>ServiceDecorator</em> instance. Let&#8217;s have a look at the most used solutions.</p>
<p><strong> </strong></p>
<h3><strong>Solution 1: Using an InjectionConstructor</strong></h3>
<p>Well, configuring the Unity container to support a decorator in the old-fashioned way requires some not so much readable code. In fact, making this work seems a kind of magic.</p>
<div style="font-family:'Courier New';"><span style="font-family:'Courier New';"><span style="color:#000000;">[</span><span style="color:#2b91af;">TestMethod</span><span style="color:#000000;">]<br />
</span></span><span style="color:#0000ff;">public </span><span style="color:#0000ff;">void</span><span style="color:#000000;"> UnityContainer_Should_Resolve_The_ServiceDecorator_With_InjectionConstructor()<br />
</span><span style="color:#000000;font-family:'Courier New';">{<br />
</span><span style="color:#0000ff;"><span style="color:#000000;">  </span></span><span style="color:#0000ff;">var</span><span style="color:#000000;"> container = </span><span style="color:#0000ff;">new</span><span style="color:#2b91af;">UnityContainer</span><span style="color:#000000;">();<br />
</span><span style="color:#000000;">  container.RegisterType&lt;</span><span style="color:#2b91af;">IService</span><span style="color:#000000;">, </span><span style="color:#2b91af;">Service</span><span style="color:#000000;">&gt;(</span><span style="color:#a31515;">&#8220;Service&#8221;</span><span style="color:#000000;">);<br />
</span><span style="color:#000000;">  container.RegisterType&lt;</span><span style="color:#2b91af;">IService</span><span style="color:#000000;">,</span><span style="color:#2b91af;">ServiceDecorator&gt;</span><span style="color:#000000;">(</span></div>
<div style="font-family:'Courier New';"><span style="color:#0000ff;">                new </span><span style="color:#2b91af;">InjectionConstructor</span><span style="color:#000000;">(</span><span style="color:#0000ff;">new </span><span style="color:#2b91af;">ResolvedParameter</span><span style="color:#000000;">(</span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(</span><span style="color:#2b91af;">IService</span><span style="color:#000000;">), </span><span style="color:#a31515;">&#8220;Service&#8221;</span><span style="color:#000000;">)));</span></div>
<div style="font-family:'Courier New';"><span style="color:#0000ff;">  </span></div>
<div style="font-family:'Courier New';"><span style="color:#0000ff;">  var</span><span style="color:#000000;"> service = container.Resolve&lt;</span><span style="color:#2b91af;">IService</span><span style="color:#000000;">&gt;();</span></div>
<div style="font-family:'Courier New';"><span style="color:#2b91af;">  Assert</span><span style="color:#000000;">.IsInstanceOfType(service, </span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(</span><span style="color:#2b91af;">ServiceDecorator</span><span style="color:#000000;">));</span></div>
<div style="font-family:'Courier New';">
<p><span style="color:#000000;">}</span></p>
</div>
<p>I think the code above is not optimal, because it uses magic strings.  It also has a dangerous disadvantage: changes to the <em>ServiceDecorator</em> constructors will generate runtime instead of compile time errors.</p>
<h3><strong> </strong></h3>
<h3><strong>Solution 2: Using an InjectionFactory</strong></h3>
<p>This is a substantial improvement of the previous solution. It allows to specify a factory function which can use the injected container to explicitly resolve eventual dependencies to decorated/decorator constructors.</p>
<div style="font-family:'Courier New';"><span style="font-family:'Courier New';"><span style="color:#000000;"> [</span><span style="color:#2b91af;">TestMethod</span><span style="color:#000000;">]<br />
</span></span><span style="color:#0000ff;">public </span><span style="color:#0000ff;">void</span><span style="color:#000000;"> UnityContainer_Should_Resolve_The_ServiceDecorator_With_InjectionFactory()<br />
</span><span style="color:#000000;font-family:'Courier New';">{<br />
</span></div>
<div style="font-family:'Courier New';"> <span style="color:#0000ff;">var</span><span style="color:#000000;"> container = </span><span style="color:#0000ff;">new </span><span style="color:#2b91af;">UnityContainer</span><span style="color:#000000;">();</span></div>
<div style="font-family:'Courier New';"><span style="color:#2b91af;"><span style="color:#000000;"> </span></span><span style="color:#2b91af;">Func</span><span style="color:#000000;">&lt;</span><span style="color:#2b91af;">IUnityContainer</span><span style="color:#000000;">, </span><span style="color:#0000ff;">object</span><span style="color:#000000;">&gt; factoryFunc = c =&gt; </span><span style="color:#0000ff;">new </span><span style="color:#2b91af;">ServiceDecorator</span><span style="color:#000000;">(</span><span style="color:#0000ff;">new </span><span style="color:#2b91af;">Service</span><span style="color:#000000;">(</span></div>
<div style="font-family:'Courier New';"><span style="color:#008000;font-family:'Courier New';">       // Here you can use the container to resolve further dependencies&#8230;<br />
</span><span style="font-family:'Courier New';"><span style="color:#008000;"> </span></span><span style="color:#000000;font-family:'Courier New';">));</span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;font-family:'Courier New';"><br />
</span><span style="color:#000000;"> container.RegisterType&lt;</span><span style="color:#2b91af;">IService</span><span style="color:#000000;">&gt;(</span><span style="color:#0000ff;">new </span><span style="color:#2b91af;">InjectionFactory</span><span style="color:#000000;">(factoryFunc));<br />
</span><span style="color:#0000ff;"><span style="color:#000000;"><br />
</span></span><span style="color:#0000ff;"> var</span><span style="color:#000000;"> service = container.Resolve&lt;</span><span style="color:#2b91af;">IService</span><span style="color:#000000;">&gt;();<br />
</span><span style="color:#2b91af;"><span style="color:#000000;"> </span></span><span style="color:#2b91af;">Assert</span><span style="color:#000000;">.IsInstanceOfType(service, </span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(</span><span style="color:#2b91af;">ServiceDecorator</span><span style="color:#000000;">));</span></div>
<div style="font-family:'Courier New';"><span style="color:#000000;">}</span></div>
<div style="font-family:'Courier New';">
<p><span style="color:#ffffff;">&#8211;</span></p>
</div>
<p>The downside is that code still needs updating every time a new constructor parameter is added to <em>Service</em> or <em>ServiceDecorator</em> class. But now we have three noticeable advantages:</p>
<ul>
<li>code is much easier to understand</li>
<li>only a single registration into the container is required</li>
<li>changes to the constructors will generate compile time instead of runtime errors.</li>
</ul>
<h3><strong> </strong></h3>
<h3><strong>Solution 3: Using a custom Unity Container Extension</strong></h3>
<p>You can use a container extension like this <a href="http://www.beefycode.com/post/Decorator-Unity-Container-Extension.aspx" target="_blank">DecoratorContainerExtension</a> in order to use the same convention available for example in the <strong>Castle Windsor</strong> container:</p>
<div style="font-family:'Courier New';"><span style="font-family:'Courier New';"><span style="color:#000000;"> [</span><span style="color:#2b91af;">TestMethod</span><span style="color:#000000;">]<br />
</span></span><span style="color:#0000ff;">public </span><span style="color:#0000ff;">void</span><span style="color:#000000;"> UnityContainer_Should_Resolve_The_ServiceDecorator_With_DecoratorContainerExtension()<br />
</span><span style="color:#000000;font-family:'Courier New';">{<br />
</span><span style="color:#0000ff;"><span style="color:#000000;">  </span></span><span style="color:#0000ff;">var</span><span style="color:#000000;"> container = </span><span style="color:#0000ff;">new </span><span style="color:#2b91af;">UnityContainer</span><span style="color:#000000;">();<br />
</span><span style="color:#000000;">  container.AddNewExtension&lt;</span><span style="color:#2b91af;">DecoratorContainerExtension</span><span style="color:#000000;">&gt;();<br />
</span><span style="color:#000000;">  container.RegisterType&lt;</span><span style="color:#2b91af;">IService</span><span style="color:#000000;">, </span><span style="color:#2b91af;">ServiceDecorator</span><span style="color:#000000;">&gt;();<br />
</span><span style="color:#000000;">  container.RegisterType&lt;</span><span style="color:#2b91af;">IService</span><span style="color:#000000;">, </span><span style="color:#2b91af;">Service</span><span style="color:#000000;">&gt;();</span><span style="color:#0000ff;">  </span></div>
<div style="font-family:'Courier New';"><span style="color:#0000ff;">  </span></div>
<div style="font-family:'Courier New';"><span style="color:#0000ff;">  var</span><span style="color:#000000;"> service = container.Resolve&lt;</span><span style="color:#2b91af;">IService</span><span style="color:#000000;">&gt;();<br />
</span><span style="color:#2b91af;"><span style="color:#000000;">  </span></span><span style="color:#2b91af;">Assert</span><span style="color:#000000;">.IsInstanceOfType(service, </span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(</span><span style="color:#2b91af;">ServiceDecorator</span><span style="color:#000000;">));<br />
</span><span style="color:#000000;font-family:'Courier New';">}</span></div>
<div style="font-family:'Courier New';">
<p><span style="color:#ffffff;">&#8211;</span></p>
</div>
<p>This is absolutely my favourite solution.  It’s less code, and most importantly it describes the intent in a better way, because it’s focused on the developer&#8217;s object model and not the on the Unity’s one.</p>
<div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2012/09/12/unity-container-and-decorator-pattern/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>Experimenting with Ext.NET support for Razor: a GridPanel with AJAX proxy</title>
		<link>https://dariosantarelli.wordpress.com/2012/06/02/experimenting-with-ext-net-support-for-razor-a-gridpanel-with-ajax-proxy/</link>
					<comments>https://dariosantarelli.wordpress.com/2012/06/02/experimenting-with-ext-net-support-for-razor-a-gridpanel-with-ajax-proxy/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sat, 02 Jun 2012 09:48:50 +0000</pubDate>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=320</guid>

					<description><![CDATA[In these days I’m having fun experimenting the Razor View Engine support introduced in Ext.NET v.2.0 (Beta3 at the time of writing) and I&#8217;m appreciating how fluently you can configure any Ext.NET component. Nowadays there isn’t a good documentation about these new features (on Ext.NET official site you can read “Server-side Ext.NET API documentation is [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In these days I’m having fun experimenting the Razor View Engine support introduced in <a href="http://examples.ext.net/" target="_blank">Ext.NET v.2.0</a> (Beta3 at the time of writing) and I&#8217;m appreciating how fluently you can configure any <a href="http://examples.ext.net/" target="_blank">Ext.NET component</a>. Nowadays there isn’t a good documentation about these new features (on Ext.NET official site you can read “<span style="text-decoration:underline;">Server-side Ext.NET API documentation is being worked on</span>”) so if you want more info about Razor support please have a look at the <a href="http://forums.ext.net/tags.php?tag=razor" target="_blank">Ext.NET official forum</a> (I’ve found <a href="http://forums.ext.net/showthread.php?16920" target="_blank">this thread</a> particularly helpful!). Moreover, in the Ext.NET <a href="http://examples.ext.net/" target="_blank">Examples Explorer</a> you can try to get the necessary knowledge for translating WebForms code examples into Razor views.<br />
In this post I’d like to show one of my first tests: a simple GridPanel supporting server-side data paging via AJAX proxy.<br />
Here the interesting Razor syntax:</p>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">@Html.X().ResourceManager()</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">@(Html.X().GridPanel()</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">        .Title("<span style="color:#8b0000;">Customers</span>")</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">        .Store(store =&gt; store.Add(Html.X().Store()</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">            .AutoLoad(<span style="color:#0000ff;">true</span>)</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">            .RemoteSort(<span style="color:#0000ff;">false</span>)</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">            .IsPagingStore(<span style="color:#0000ff;">true</span>)</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">            .RemotePaging(<span style="color:#0000ff;">true</span>)</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">            .PageSize(20)</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">            .Proxy(proxy =&gt; proxy.Add(Html.X()<strong>.AjaxProxy()</strong></pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                            .Url("<span style="color:#8b0000;">/Customers/GetCustomers</span>")</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                            .Reader(reader =&gt; reader.Add(Html.X().<strong>JsonReader()</strong></pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                                                   .Root("<span style="color:#8b0000;">data</span>")</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                                                   .TotalProperty("<span style="color:#8b0000;">total</span>")</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                                                   .IDProperty("<span style="color:#8b0000;">CustomerID</span>")))))</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">            .Model(model =&gt; model.Add(Html.X().Model()</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                        .Fields(fields =&gt;</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                        {</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                            fields.Add(Html.X().ModelField().Name("<span style="color:#8b0000;">CustomerID</span>"));</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                            fields.Add(Html.X().ModelField().Name("<span style="color:#8b0000;">ContactName</span>"));</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                            fields.Add(Html.X().ModelField().Name("<span style="color:#8b0000;">CompanyName</span>"));</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                            fields.Add(Html.X().ModelField().Name("<span style="color:#8b0000;">Phone</span>"));</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                            fields.Add(Html.X().ModelField().Name("<span style="color:#8b0000;">Fax</span>"));</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                            fields.Add(Html.X().ModelField().Name("<span style="color:#8b0000;">Region</span>"));</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                        })))))</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">        .ColumnModel(columnModel =&gt;</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">        {</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">            columnModel.Columns.Add(Html.X().Column().Text("<span style="color:#8b0000;">ContactName</span>").DataIndex("<span style="color:#8b0000;">ContactName</span>").Flex(1));</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">            columnModel.Columns.Add(Html.X().Column().Text("<span style="color:#8b0000;">CompanyName</span>").DataIndex("<span style="color:#8b0000;">CompanyName</span>").Flex(1));</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">            columnModel.Columns.Add(Html.X().Column().Text("<span style="color:#8b0000;">Phone</span>").DataIndex("<span style="color:#8b0000;">Phone</span>"));</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">            columnModel.Columns.Add(Html.X().Column().Text("<span style="color:#8b0000;">Fax</span>").DataIndex("<span style="color:#8b0000;">Fax</span>"));</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">            columnModel.Columns.Add(Html.X().Column().Text("<span style="color:#8b0000;">Region</span>").DataIndex("<span style="color:#8b0000;">Region</span>"));</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">        })</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">        .BottomBar(bar =&gt; bar.Add(Html.X().PagingToolbar()
                                          .DisplayInfo(<span style="color:#0000ff;">true</span>)
                                          .DisplayMsg("<span style="color:#8b0000;">Displaying customers {0} - {1} of {2}</span>")))</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">        .View(view =&gt; view.Add(Html.X().GridView())))</pre>
<p>&nbsp;</p>
<p>First of all, please note the <strong>Html.X()</strong> helper method. This is the entry point for configuring any Ext.NET component. As requisite for getting started, you can call the <strong>Html.X().ResourceManager()</strong> helper method. Like the counterpart of Ext.NET for WebForms, it automatically injects every script and stylesheet you need into your page. The output should be something like this:</p>
<div style="font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:maroon;">link </span><span style="color:red;">type</span><span style="color:blue;">="text/css" </span><span style="color:red;">rel</span><span style="color:blue;">="stylesheet" </span><span style="color:red;">href</span><span style="color:blue;">="/extjs/resources/css/ext-all-gray-embedded-css/ext.axd?v=25767" /&gt;   </span></pre>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:maroon;">link </span><span style="color:red;">type</span><span style="color:blue;">="text/css" </span><span style="color:red;">rel</span><span style="color:blue;">="stylesheet" </span><span style="color:red;">href</span><span style="color:blue;">="/extnet/resources/extnet-all-embedded-css/ext.axd?v=25767" /&gt;</span></pre>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:maroon;">script </span><span style="color:red;">type</span><span style="color:blue;">="text/javascript" </span><span style="color:red;">src</span><span style="color:blue;">="/extjs/ext-all-js/ext.axd?v=25767"&gt;&lt;/</span><span style="color:maroon;">script</span><span style="color:blue;">&gt;</span></pre>
<pre class="code"><span style="color:#0000ff;">&lt;</span><span style="color:maroon;">script </span><span style="color:red;">type</span><span style="color:blue;">="text/javascript" </span><span style="color:red;">src</span><span style="color:blue;">="/extnet/extnet-all-js/ext.axd?v=25767"&gt;&lt;/</span><span style="color:maroon;">script</span><span style="color:blue;">&gt; </span></pre>
</div>
<p>OK, now through the <strong>Html.X()</strong> helper you can start configuring the GridPanel. In my example I have an AjaxProxy which calls a controller action in order to get back some JSON data to bind to the GridPanel. Some point of interest:</p>
<ul>
<li><strong><em>start</em></strong> and <strong><em>limit</em></strong> are the two standard ExtJs querystring parameters sent by the proxy to the remote data source in order to tell it how to page data.</li>
<li>AjaxProxy can process the resulting JSON via a <strong><em>JsonReader</em></strong>. In particular, pay attention to the <strong><em>Root()</em></strong> and <strong><em>TotalProperty()</em></strong> methods. They tell the reader respectively which root property in the JSON response contains the data rows and which property contains the total results count. They are two fundamental info for the right grid rendering.</li>
</ul>
<p>Finally, the controller action code:</p>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;"><span style="color:#0000ff;">public</span> ActionResult GetCustomers(<span style="color:#0000ff;">int</span> <strong>start</strong>, <span style="color:#0000ff;">int</span> <strong>limit</strong>)</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">{</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">    IEnumerable dtoArray;</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">    <span style="color:#0000ff;">int</span> total;</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;"></pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">   <span style="color:#0000ff;"> using</span> (var unitOfWork = _unitOfWorkFactory.Create())</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">    {</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">        var customerRepository = _repositoryFactory.CreateCustomerRepository(unitOfWork);</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">        var customers = customerRepository.Query()</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                          .Skip(start)</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                          .Take(limit);

         dtoArray = (from customer <span style="color:#0000ff;">in</span> customers</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                        select <span style="color:#0000ff;">new</span></pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                {</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                    customer.CustomerID,</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                    customer.CompanyName,</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                    customer.ContactName,</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                    customer.Phone,</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                    customer.Fax,</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                    customer.Region</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">                                }).ToArray();

         total = customerRepository.Query().Count();</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">    }</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;"></pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">   <span style="color:#0000ff;"> return</span> Json(<span style="color:#0000ff;">new</span> { <strong>data</strong> = dtoArray, <strong>total </strong>= total }, JsonRequestBehavior.AllowGet);</pre>
<pre style="background-color:#ffffff;margin:0;width:100%;font-family:consolas, 'Courier New', courier, monospace;font-size:12px;">}</pre>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2012/06/02/experimenting-with-ext-net-support-for-razor-a-gridpanel-with-ajax-proxy/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>Using MEF in a Request/Response Service Layer</title>
		<link>https://dariosantarelli.wordpress.com/2011/12/30/using-mef-in-a-requestresponse-service-layer/</link>
					<comments>https://dariosantarelli.wordpress.com/2011/12/30/using-mef-in-a-requestresponse-service-layer/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Fri, 30 Dec 2011 15:17:07 +0000</pubDate>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Microsoft Technology]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[MEF]]></category>
		<category><![CDATA[WCF]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=292</guid>

					<description><![CDATA[In a project of mine I’m using a simple Request/Response service layer very similar to the amazing Davy Brion’s Agatha project. Everything started a few time ago when I was searching for a smart way to design a client-server infrastructure which was focused on messages and not on operations. This layer would be not only [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In a project of mine I’m using a simple Request/Response service layer very similar to the amazing <a href="http://davybrion.github.com/Agatha/">Davy Brion’s Agatha project</a>. Everything started a few time ago when I was searching for a smart way to design a client-server infrastructure which was focused on messages and not on operations. This layer would be not only a classic WCF-based service, but also a some kind of in-process facade to my business layer where I could centralize any cross cutting concern. So I was focused on the capability of moving my service layer and its business logic to a separate machine and hosting it through WCF without any significant modifications to my code (admitting that service layer doesn’t share state with upper layers like the presentation layer). After reading Davy’s “<a href="http://davybrion.com/blog/2009/07/why-i-dislike-classic-or-typical-wcf-usage/">Why I Dislike Classic Or Typical WCF Usage</a>” , I was convinced to address myself to one service contract with one service operation, avoiding to spend time thinking about how to design and implement service contracts and operations. In this way, the first (great) advantage I got is that I can add functionalities simply defining a request message, a response message and a request handler which executes the logic needed between a request receiving and a response sending. Very simple and effective!</p>
<h4>Overview of the service layer</h4>
<p>Everything starts from an interface called <em>IRequestHandler</em>:</p>
<div style="font-size:11px;">
<pre class="code"><span style="color:blue;">public interface </span><span style="color:#2b91af;">IRequestHandler </span>
{
  <span style="color:#2b91af;">Response </span>HandleRequest(<span style="color:#2b91af;">Request </span>request);
}</pre>
</div>
<p><em>Request</em> and <em>Response</em> are empty base abstract classes:</p>
<div style="font-size:11px;">
<pre class="code"><span style="color:blue;">public abstract class </span><span style="color:#2b91af;">Request </span>{}
<span style="color:blue;">public abstract class </span><span style="color:#2b91af;">Response </span>{}</pre>
</div>
<p>Now let&#8217;s define a simple rule: every concrete request type must be corresponded by a concrete response type. The idea is to basically consider each service operation as a request which must have a response. For each request you define, you need to provide an handler which does whatever it needs to do to handle the request and returns a response. In my solution, a simple generic base request handler has been defined in the following way:</p>
<div style="font-size:11px;">
<pre class="code"><span style="color:blue;">public abstract class </span><span style="color:#2b91af;">RequestHandlerBase</span>&lt;TRequest, TResponse&gt; : <span style="color:#2b91af;">IRequestHandler </span>
                                                             <span style="color:blue;"> where </span>TRequest : <span style="color:#2b91af;">Request </span>
                                                             <span style="color:blue;"> where </span>TResponse : <span style="color:#2b91af;">Response </span>
{
    <span style="color:blue;">public </span><span style="color:#2b91af;">Response </span>HandleRequest(<span style="color:#2b91af;">Request </span>request)
    {
        <span style="color:blue;">return </span>HandleRequest((TRequest)request);
    }

    <span style="color:blue;">public abstract </span>TResponse HandleRequest(TRequest request);
}</pre>
</div>
<p>For example, by inheriting this <em>RequestHandlerBase</em> base class, we could create a login request handler, which implements the business logic for validating a user:</p>
<div style="font-size:11px;">
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">LoginRequestHandler </span>: <span style="color:#2b91af;">RequestHandlerBase</span>&lt;<span style="color:#2b91af;">LoginRequest</span>, <span style="color:#2b91af;">LoginResponse</span>&gt;
{
    <span style="color:blue;">public override </span><span style="color:#2b91af;">LoginResponse </span>HandleRequest(<span style="color:#2b91af;">LoginRequest </span>request)
    {
     <span style="color:green;"> // validate the user credentials contained in the LoginRequest </span>
     <span style="color:green;"> // and return a LoginResponse containing, for example, a session token </span>
    }
}</pre>
</div>
<p>Having each request handler implemented in the same fashion as the <em>LoginRequestHandler</em>, I’d like to reach a service implementation like this:</p>
<div style="font-size:11px;">
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">MyService </span>: <span style="color:#2b91af;">IRequestHandler </span>
{
    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">IRequestHandlerProvider </span>_requestHandlerProvider;

    <span style="color:blue;">public </span>MyService(<span style="color:#2b91af;">IRequestHandlerProvider </span>requestHandlerProvider)
    {
        _requestHandlerProvider = requestHandlerProvider;
    }

    <span style="color:blue;">public </span><span style="color:#2b91af;">Response </span>HandleRequest(<span style="color:#2b91af;">Request </span>request)
    {
        <span style="color:blue;">return </span>_requestHandlerProvider.GetRequestHandler(request.GetType()).HandleRequest(request);
    }
}</pre>
</div>
<p>As you can see, the service itself implements the <em>IRequestHandler</em> interface and the actual implementation is very minimal: it&#8217;s just a small class which resolves the appropriate handler through an abstraction called <em>IRequestHandlerProvider</em> which internally may use an IoC container capable of resolving the request handler associated to a request type. Then, the service delegates the execution to an handler by passing the request to it, and finally it returns a typed response to the client.</p>
<h4>Enter MEF</h4>
<p>Now we could need a IoC container to resolve and create the instances of the request handlers. As shown in this <a href="http://davybrion.com/blog/2008/07/the-request-response-service-layer/">post</a>, you can use the <a href="http://docs.castleproject.org/Windsor.MainPage.ashx">Castle Windsor</a> IoC container to use <a href="http://davybrion.com/blog/2007/07/introduction-to-dependency-injection/">dependency injection</a>. That basically allows you to register each valid request handler that is present, for example, in a given assembly. Even my purpose was to find a simple way to plug in request handlers defined in external assemblies, getting everything registered automatically in a centralized request handler provider when the application starts up. So, I was focused on <a href="http://mef.codeplex.com/wikipage?title=Overview">MEF</a>. What I tried to do is to treat each request handler as an extension, because in my project each tuple “Request-Response-Handler” represents an extension unit. Moreover,</p>
<ul>
<li>MEF is an integral part of the .NET Framework 4</li>
<li>MEF<em> </em>offers a set of discovery approaches for locating and loading available extensions even in a “lazy” fashion</li>
<li>MEF allows tagging extensions with additonal metadata which facilitates rich querying and filtering so an extensibility element can provide metadata to exported items.</li>
</ul>
<p>Following this philosophy, beyond the classic <a href="http://mef.codeplex.com/wikipage?title=Declaring%20Exports&amp;referringTitle=Overview">Export</a> attribute I introduced a <em>RequestHandlerMetadataAttribute</em> useful for simplifying the process of resolving an handler related to a specific request type. So, the <em>LoginRequestHandler</em> defined before could be decorated as the following&#8230;</p>
<div style="font-size:11px;">
<pre class="code">[<span style="color:#2b91af;">Export</span>(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">IRequestHandler</span>))] <span style="color:green;">// I am a request handler!!!</span>
[<span style="color:#2b91af;">RequestHandlerMetadata</span>(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">LoginRequest</span>))] <span style="color:green;">// I can handle Login requests!!!</span>
<span style="color:blue;">public class </span><span style="color:#2b91af;">LoginRequestHandler </span>: <span style="color:#2b91af;">RequestHandlerBase</span>&lt;<span style="color:#2b91af;">LoginRequest</span>, <span style="color:#2b91af;">LoginResponse</span>&gt;
{
  <span style="color:blue;">... </span>
}</pre>
</div>
<p>And here is the <em>RequestHandlerMetadataAttribute</em> definition.</p>
<div style="font-size:11px;">
<pre class="code"><span style="color:blue;">public interface </span><span style="color:#2b91af;">IRequestHandlerMetadata </span>
{
    <span style="color:#2b91af;">Type </span>RequestType { <span style="color:blue;">get</span>; }
}

[<span style="color:#2b91af;">MetadataAttribute</span>]
[<span style="color:#2b91af;">AttributeUsage</span>(<span style="color:#2b91af;">AttributeTargets</span>.Class, AllowMultiple = <span style="color:blue;">false</span>)]
<span style="color:blue;">public class </span><span style="color:#2b91af;">RequestHandlerMetadataAttribute </span>: <span style="color:#2b91af;">ExportAttribute </span>
{
    <span style="color:blue;">public </span><span style="color:#2b91af;">Type </span>RequestType { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }

    <span style="color:blue;">public </span>RequestHandlerMetadataAttribute(<span style="color:#2b91af;">Type </span>requestType)
        : <span style="color:blue;">base</span>(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">IRequestHandlerMetadata</span>))
    {
        RequestType = requestType;
    }
}</pre>
</div>
<p>In order to allow us to access the metadata, MEF introduces a special kind of <a href="http://msdn.microsoft.com/en-us/library/dd986615(VS.96).aspx">Lazy&lt;T,M&gt;</a> that has attached metadata. <em>M</em> in this case is an interface (called “metadata view”) that contains only getter properties. <span style="text-decoration:underline;">MEF automatically generates a proxy class that implements this interface and it plugs all the metadata in for us</span>. This is very cool! What is happening behind the scenes is that MEF is using reflection emit in order to construct the typed metadata view.</p>
<p>As result, I&#8217;ve used the metadata view <em>IRequestHandlerMetadata</em> to easily find the right handler for a request of a given type, as shown in the <em>GetRequestHandler()</em> method of the following <em>MefRequestHandlerProvider</em>.</p>
<div style="font-size:11px;">
<pre class="code" style="overflow:auto;"><span style="color:blue;">public class </span><span style="color:#2b91af;">MefRequestHandlerProvider </span>: <span style="color:#2b91af;">IRequestHandlerProvider </span>
{
    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IRequestHandler</span>, <span style="color:#2b91af;">IRequestHandlerMetadata</span>&gt;&gt; _registeredHandlers =
                                              <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Lazy</span>&lt;<span style="color:#2b91af;">IRequestHandler</span>, <span style="color:#2b91af;">IRequestHandlerMetadata</span>&gt;&gt;();

    <span style="color:blue;">public </span>MefRequestHandlerProvider(<span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">ComposablePartCatalog</span>&gt; catalogs)
    {
        <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>catalog <span style="color:blue;">in </span>catalogs)
        {
            <span style="color:blue;">var </span>container = <span style="color:blue;">new </span><span style="color:#2b91af;">CompositionContainer</span>(catalog);
            <span style="color:blue;">var </span>exportedHandlers = container.GetExports&lt;<span style="color:#2b91af;">IRequestHandler</span>, <span style="color:#2b91af;">IRequestHandlerMetadata</span>&gt;();

            <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>exportedHandler <span style="color:blue;">in </span>exportedHandlers)
            {
                <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>registeredHandler <span style="color:blue;">in </span>_registeredHandlers)
                {
                    <span style="color:blue;">if </span>(registeredHandler.Metadata.RequestType == exportedHandler.Metadata.RequestType)
                        <span style="color:blue;">throw new </span><span style="color:#2b91af;">NotSupportedException</span>(<span style="color:blue;">string</span>.Format(<span style="color:#a31515;">"A request handler for type </span><span style="color:#3cb371;">{0} </span><span style="color:#a31515;">is already registered."</span>,
                                                                      exportedHandler.Metadata.RequestType));
                }
            }

            _registeredHandlers.AddRange(exportedHandlers);
        }
    }

    <span style="color:blue;">public </span><span style="color:#2b91af;">IRequestHandler </span>GetRequestHandler(<span style="color:#2b91af;">Type </span>requestType)
    {
        <span style="color:blue;">var </span>handler = _registeredHandlers.SingleOrDefault(r =&gt; r.Metadata.RequestType == requestType);
        <span style="color:blue;">if </span>(handler != <span style="color:blue;">null</span>) <span style="color:blue;">return </span>handler.Value;
        <span style="color:blue;">throw new </span><span style="color:#2b91af;">RequestHandlerNotFoundException</span>(<span style="color:blue;">string</span>.Format(<span style="color:#a31515;">"No request handler has been found for type </span><span style="color:#3cb371;">{0}</span><span style="color:#a31515;">"</span>, requestType));
    }
}</pre>
</div>
<p>Putting all together, in the application startup I placed the following initialization code which uses the <em>MefRequestHandlerProvider</em>. As you may know, request handlers can be located inside catalogs (e.g. <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.assemblycatalog.aspx">AssemblyCatalog</a>, <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.aggregatecatalog.aspx">AggregateCatalog</a> etc.). When using a client proxy, I need to expose just one method which never needs to be updated. That’s a good advantage!</p>
<div style="font-size:11px;">
<pre class="code"><span style="color:green;">// Server-Side </span>
<span style="color:blue;">var </span>catalog = <span style="color:blue;">new </span><span style="color:#2b91af;">AssemblyCatalog</span>(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">IRequestHandler</span>).Assembly);
<span style="color:blue;">var </span>mefRequestHandlerProvider = <span style="color:blue;">new </span><span style="color:#2b91af;">MefRequestHandlerProvider</span>(<span style="color:blue;">new</span>[] { catalog });
<span style="color:#2b91af;">MyService </span>service = <span style="color:blue;">new </span><span style="color:#2b91af;">MyService</span>(mefRequestHandlerProvider);

<span style="color:green;">// Client-Side (when using a proxy)</span>
<span style="color:#2b91af;">LoginResponse </span>response = (<span style="color:#2b91af;">LoginResponse</span>)serviceProxy.HandleRequest(<span style="color:blue;">new </span><span style="color:#2b91af;">LoginRequest</span>(<span style="color:#a31515;">"username"</span>, <span style="color:#a31515;">"password"</span>));
<span style="color:#2b91af;">Console</span>.WriteLine(response.AccessToken);</pre>
</div>
<h4>Conclusion</h4>
<p>In this post I’ve tried to show how I used MEF to plug request handlers in a request/response service layer similar to <a href="http://davybrion.github.com/Agatha/">Agatha</a>. I have not written anything about serialization issues when exposing the service layer through WCF. Moreover, I haven&#8217;t treated any aspects about request handlers such as objects lifecycles or error management. I think that any question about these service layer insights can find good answers after reading the <a href="http://davybrion.com/blog/2009/11/requestresponse-service-layer-series/">Davy Brion’s Request/Response Service Layer Series</a>.</p>
<p>HTH</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2011/12/30/using-mef-in-a-requestresponse-service-layer/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>[Entity Framework v4] Identity map pattern</title>
		<link>https://dariosantarelli.wordpress.com/2011/11/26/entity-framework-v4-identity-map-pattern/</link>
					<comments>https://dariosantarelli.wordpress.com/2011/11/26/entity-framework-v4-identity-map-pattern/#respond</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sat, 26 Nov 2011 12:07:51 +0000</pubDate>
				<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[EntityFramework]]></category>
		<category><![CDATA[IdentityMap]]></category>
		<category><![CDATA[Pattern]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=271</guid>

					<description><![CDATA[One of the most important pattern that a good ORM technology should support in order to face the object-relational impedance mismatch is the Identity Map pattern. It’s just one of a set of conceptual and technical difficulties emerging when objects or class definitions are mapped in a straightforward way to database tables or relational schemas. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>One of the most important pattern that a good <a href="http://en.wikipedia.org/wiki/Object-relational_mapping" target="_blank">ORM</a> technology should support in order to face the <a href="http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch" target="_blank">object-relational impedance mismatch</a> is the <a href="http://en.wikipedia.org/wiki/Identity_map" target="_blank">Identity Map</a> pattern. It’s just one of a set of conceptual and technical difficulties emerging when objects or class definitions are mapped in a straightforward way to database tables or relational schemas.</p>
<h3>What’s Identity Map?</h3>
<p>In Martin Fowler’s book “<a href="http://books.google.com/books/about/Patterns_of_enterprise_application_archi.html?id=FyWZt5DdvFkC" target="_blank">Patterns of Enterprise Application Architecture</a>”, the <em>Identity Map</em> is defined as a way of ensuring <em>“that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them.”</em>  If the requested data has already been loaded from the database, the identity map has to return the same instance of the already instantiated object and if it has not been loaded yet, it should load it and stores the new object in the map. In this way, it follows a similar principle to <a href="http://en.wikipedia.org/wiki/Lazy_loading">lazy loading</a>. As result, the <em>Identity Map</em> design pattern introduces a consistent way of querying and persisting objects (e.g. through a context-specific in-memory cache) which prevents applications from duplicate retrievals of the same object data from the database.</p>
<p>Ok, in order to better understand this concept, let’s start from a non-Identity Map example. If we have an application that uses a simple persistence layer that performs a database query and then materializes one or more objects, we might see code that creates different instances of the same logical entity:</p>
<div style="font-size:1.2em;">
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>Non_IdentityMap_Solution_Provides_Different_Copies_Of_The_Same_Customer()
{
    <span style="color:#2b91af;">Customer </span>customer1 = DAL.<span style="color:#2b91af;">Customers</span>.GetCustomerById(<span style="color:#a31515;">"dsantarelli"</span>);
    <span style="color:#2b91af;">Customer </span>customer2 = DAL.<span style="color:#2b91af;">Customers</span>.GetCustomerById(<span style="color:#a31515;">"dsantarelli"</span>);

    <span style="color:green;">// customer1 and customer2 should represent the same customer...</span>        <span style="color:#2b91af;"> </span>
    <span style="color:#2b91af;">Assert</span>.AreEqual(customer1.CustomerId, customer2.CustomerId);
    <span style="color:#2b91af;">Assert</span>.AreEqual(customer1.Email, customer2.Email);

    <span style="color:green;">// ... but they are two separate instances! </span><span style="color:#2b91af;">  </span><span style="color:#2b91af;">  </span>
    <span style="color:#2b91af;">Assert</span>.IsFalse(customer1 == customer2);

    <span style="color:green;">// If we change a property of customer1... </span>
    customer1.Email = <span style="color:#a31515;">"xxx@yyy.zzz"</span>;

    <span style="color:green;">// ... then, which instance should be valid? </span><span style="color:#2b91af;"> </span>
    <span style="color:#2b91af;">Assert</span>.AreNotEqual(customer1.Email, customer2.Email);
}</pre>
</div>
<p>In this example, <em>customer1</em> and <em>customer2</em> both contain separate copies of the data for the same customer. If we change the data in <em>customer1</em>, the change has no effect on <em>customer2</em>. If we make changes to both and then save them back to the database, one just overwrites the changes of the other. That’s because our persistence framework <span style="text-decoration:underline;">just doesn’t know</span> that <em>customer1</em> and <em>customer2</em> both contain data for the same logical entity.</p>
<p><em>Conclusion</em>: <strong><em><span style="text-decoration:underline;">multiple objects containing data for the same entity, lead to concurrency problems when it’s time to save data</span>.</em></strong></p>
<h3>How does Entity Framework approach the Identity Map pattern?</h3>
<p>Now let’s have a look at the Identity Map way! In the unit test below, we have some Entity Framework code in which three different object queries are executed in order to get data for the same customer:</p>
<div style="font-size:1.2em;">
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>EF_IdentityMap_Solution_Provides_References_To_The_Same_Instance_Of_Customer()
{
    <span style="color:blue;">using </span>(<span style="color:#2b91af;">EFContext </span>context = <span style="color:blue;">new </span><span style="color:#2b91af;">EFContext</span>())
    {
        <span style="color:#2b91af;">Customer </span>customer1 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);
        <span style="color:#2b91af;">Customer </span>customer2 = context.Customers.Single(c =&gt; c.Email == <span style="color:#a31515;">"dario@santarelli.com"</span>);
        <span style="color:#2b91af;">Customer </span>customer3 = context.Customers.First(c =&gt; c.ContactName == <span style="color:#a31515;">"Dario Santarelli"</span>);

        <span style="color:green;">// The three queries above should return the same customer. </span><span style="color:green;"> </span>
        <span style="color:green;"> // So, </span><span style="color:green;">customer 1,2 and 3 are references to the same instance of Customer. </span>
       <span style="color:#2b91af;"> Assert</span>.IsTrue(customer1 == customer2);
        <span style="color:#2b91af;">Assert</span>.IsTrue(customer2 == customer3);

        <span style="color:green;">// Now if we change a property of customer1... </span>
        customer1.Email = <span style="color:#a31515;">"xxx@yyy.zzz"</span>;

        <span style="color:green;">// ... then customer 1,2 and 3 still remain valid references to the same instance of Customer. </span>
        <span style="color:#2b91af;"> Assert</span>.AreEqual(customer1.Email, customer2.Email);
        <span style="color:#2b91af;">Assert</span>.AreEqual(customer2.Email, customer3.Email);
    }
}</pre>
</div>
<p>How you can see, now all 3 customers are equal. Moreover, when we change a property on <em>customer1</em>, we get that same change on <em>customer2 </em>and<em> customer3</em>. In fact, they’re all references to a single object that is managed by the EF’s <strong><a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspx" target="_blank">ObjectContext</a></strong>. Behind the scenes EF ensures that only one entity object is created and the multiple entities that we try to load are just multiple references to that one object, regardless of how many times or how many different are the ways we load an entity. This is a behavior compliant with the Identity Map pattern!</p>
<p><strong>The key is EntityKey</strong></p>
<p>So how does this work?  First of all, every entity type has a key that uniquely identifies that entity.</p>
<p>If your Customer entity inherits from <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.dataclasses.entityobject.aspx">EntityObject</a> (which is the base class for all data classes generated by the <a href="http://msdn.microsoft.com/en-us/library/ee382825.aspx" target="_blank">Entity Data Model</a> tools) or simply implements the <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.dataclasses.ientitywithkey.aspx">IEntityWithKey</a> interface, in the debugger you&#8217;ll notice that Customer has a property that EF created for you named <a href="http://msdn.microsoft.com/en-us/library/dd283139.aspx" target="_blank">EntityKey</a> (which corresponds to the primary key in the database). EntityKey contains data about all the information ObjectContext needs in order to maintain an Identity Map. You could think of the map as a “cache” that contains only one instance of each object identified by its EntityKey.</p>
<p>REMEMBER: <em>Entity Framework v4 does not require you to implement <strong>IEntityWithKey</strong> in a custom data class especially if you use </em><a href="http://msdn.microsoft.com/en-us/library/dd456853.aspx" target="_blank"><em>POCO entities</em></a><em>.</em></p>
<p>In the previous example, when we get <em>customer1</em> from our context, by default EF runs the query, creates an instance of Customer (uniquely identified by its key <em>CustomerId</em>), stores that object in the cache, and gives us back a reference to it. When we get <em>customer2</em> from the context, the context <span style="text-decoration:underline;">does run the query again</span> and pulls data from our database, but then it sees that it already has a customer entity with the same EntityKey in the cache so it throws out the data and returns a reference to the entity that’s already in cache. The same thing happens for <em>customer3</em>.</p>
<p>So how many database queries EF will perform if we write something like this?</p>
<div style="font-size:1.2em;">
<pre class="code"><span style="color:#2b91af;">Customer </span>customer1 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);
<span style="color:#2b91af;">Customer </span>customer2 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);
<span style="color:#2b91af;">Customer </span>customer3 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);</pre>
</div>
<p>The answer is: three.</p>
<p>Wait&#8230; if there’s a cache, why is it performing three queries? The second part of Martin Fowler’s definition of Identity map says “&#8230; l<em>ooks up objects using the map when referring to them</em>”. An obvious question is: if I’m loading an object that already exists in my cache, and EF is just going to return a reference to that cached object and throw away any changes it gets from the database query, can’t I just get the object directly from my cache and skip the database query altogether? That could really reduce database load.</p>
<p>The answer is: <span style="text-decoration:underline;">you could explicitly get an entity directly from the cache without hitting the database</span>, but only if you use a special method to get the entity by its EntityKey. Here an example:</p>
<div style="font-size:1.2em;">
<pre class="code"><span style="color:#2b91af;">EntityKey </span>entityKey = <span style="color:blue;">new </span><span style="color:#2b91af;">EntityKey</span>(<span style="color:#a31515;">"EFContext.Customers"</span>, <span style="color:#a31515;">"CustomerId"</span>, <span style="color:#a31515;">"dsantarelli"</span>);</pre>
<pre class="code"><span style="color:blue;">object </span>customerObj;
<span style="color:blue;">if </span>(context.TryGetObjectByKey(entityKey, <span style="color:blue;">out </span>customerObj))
{
    <span style="color:green;">// the customer has been found in the cache </span><span style="color:#2b91af;">Customer </span>customer = (<span style="color:#2b91af;">Customer</span>)customerObj;
}</pre>
</div>
<p>What about if we don’t know the actual value of an EntityKey? Well, we can’t use this feature.</p>
<p>In fact, having to use the EntityKey is a big limitation since most of the time you want to look up data by some other field and not by a primary key which could be a Guid or another data type impossible to know.</p>
<h3>Identity Map and MergeOptions</h3>
<p>Now two interesting questions:</p>
<p>Can I customize the strategy that EF uses to compare the datasource values and the cache entities values?<br />
What happens to cached entities when the underlying database rows change?</p>
<p>Suppose to have the following code:</p>
<div style="font-size:1.2em;">
<pre class="code"><span style="color:#2b91af;">Customer </span>customer1 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);
<span style="color:green;">// Now someone changes the customer1 record in the DB!!! </span>
<span style="color:#2b91af;">Customer </span>customer2 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);</pre>
</div>
<p>After <em>customer1</em> is loaded, someone changes the record in the DB. Will <em>customer2</em> have the original values, or the new values? Remember that <em>customer1</em> and <em>customer2</em> are references to the same entity object in the cache, and our first db hit when we got <em>customer1</em> did pull the original value, but then the query for <em>customer2</em> also hit the database and pulled data. How does EF handle that? The answer is: it depends on the <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption.aspx" target="_blank">MergeOption</a> enumeration. The possible options are:</p>
<p><strong>AppendOnly</strong> (default) : It simply throws the new data out. If an object is already in the context, the current and original values of object&#8217;s properties in the entry are not overwritten with data source values. The state of the object&#8217;s entry and state of properties of the object in the entry do not change and Identity Map is guaranteed. Here&#8217;s a test example:</p>
<div style="font-size:1.2em;">
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>EF_AppendOnly_MergeOption_Throws_NewData_Away()
{
    <span style="color:blue;">using </span>(<span style="color:#2b91af;">EFContext </span>context = <span style="color:blue;">new </span><span style="color:#2b91af;">EFContext</span>())
    {
        <strong>context.Customers.MergeOption = <span style="color:#2b91af;">MergeOption</span>.AppendOnly;</strong>

        <span style="color:#2b91af;">Customer </span>customer1 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);
        <span style="color:#2b91af;">Assert</span>.AreEqual(customer1.ContactName, <span style="color:#a31515;">"Dario Santarelli"</span>);

        <span style="color:green;">// Now someone changes the customer1 record in the DB</span>
        <span style="color:green;">// by setting ContactName = "Luigi Santarelli" !!!</span>
        ChangeDBRecord(<span style="color:#a31515;">"dsantarelli" , <span style="color:#a31515;">"Luigi Santarelli"</span></span>);

        <span style="color:#2b91af;">Customer </span>customer2 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);

        <span style="color:#2b91af;">Assert</span>.IsTrue(customer1 == customer2); <span style="color:green;">// They are references to the same Customer instance (Identity Map)</span>
        <span style="color:#2b91af;">Assert</span>.AreEqual(customer2.ContactName, <span style="color:#a31515;">"Dario Santarelli"</span>);  <span style="color:green;">// Original values win! </span>}
}</pre>
</div>
<p><strong>OverwriteChanges:</strong> Unlike the <em>AppendOnly</em> option, it applies new data. If an object is already in the context, the current and original values of object&#8217;s properties in the entry are overwritten with data source values, ignoring every changes we make in the meanwhile. Identity Map principle is still preserved.</p>
<div style="font-size:1.2em;">
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>EF_OverwriteChanges_MergeOption_Applies_NewData()
{
    <span style="color:blue;">using </span>(<span style="color:#2b91af;">EFContext </span>context = <span style="color:blue;">new </span><span style="color:#2b91af;">EFContext</span>())
    {
       <strong> context.Customers.MergeOption = <span style="color:#2b91af;">MergeOption</span>.OverwriteChanges;</strong>

        <span style="color:#2b91af;">Customer </span>customer1 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);
        <span style="color:#2b91af;">Assert</span>.AreEqual(customer1.ContactName, <span style="color:#a31515;">"Dario Santarelli"</span>);

        <span style="color:green;">// Now someone changes the customer1 record in the DB </span>
        <span style="color:green;">// by setting ContactName = "Luigi Santarelli" !!! </span>
        ChangeDBRecord(<span style="color:#a31515;">"dsantarelli" , <span style="color:#a31515;">"Luigi Santarelli"</span></span>);

        customer2 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);

        <span style="color:#2b91af;">Assert</span>.IsTrue(customer1 == customer2); <span style="color:green;">// They are references to the same instance (Identity Map) </span>
        <span style="color:#2b91af;">Assert</span>.AreEqual(customer2.ContactName, <span style="color:#a31515;">"Luigi Santarelli"</span>); <span style="color:green;">// New values win </span>}
}</pre>
</div>
<p><strong>NoTracking</strong> : In this scenario, objects are not tracked in the <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectstatemanager.aspx">ObjectStateManager</a>. Each time we hit the DB for getting a customer, the EF provides a new instance of the Customer class. So, in this case, the Identity Map principle is broken (we can find some analogies with the non-Identity Map solution presented at the beginning of this post).</p>
<div style="font-size:1.2em;">
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>EF_NoTracking_MergeOption_Applies_NewData_And_Provides_Different_Copies_Of_The_Same_Customer()
{
    <span style="color:blue;">using </span>(<span style="color:#2b91af;">EFContext </span>context = <span style="color:blue;">new </span><span style="color:#2b91af;">EFContext</span>())
    {
        <strong>context.Customers.MergeOption = <span style="color:#2b91af;">MergeOption</span>.NoTracking;</strong>

        <span style="color:#2b91af;">Customer </span>customer1 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);
        <span style="color:#2b91af;">Assert</span>.AreEqual(customer1.ContactName, <span style="color:#a31515;">"Dario Santarelli"</span>);

        <span style="color:green;">// Now someone changes the customer1 record in the DB</span>
        <span style="color:green;">// by setting ContactName = "Luigi Santarelli" !!!</span>
        ChangeDBRecord(<span style="color:#a31515;">"dsantarelli"</span>, <span style="color:#a31515;">"Luigi Santarelli"</span>);

        <span style="color:#2b91af;">Customer </span>customer2 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);

        <span style="color:#2b91af;">Assert</span>.<strong>IsFalse</strong>(customer1 == customer2); <span style="color:green;">// They are NOT references to the same instance (NO Identity Map) </span>
        <span style="color:#2b91af;">Assert</span>.AreEqual(customer1.ContactName, <span style="color:#a31515;">"Dario Santarelli"</span>); <span style="color:green;">// customer1 has original values </span>
        <span style="color:#2b91af;">Assert</span>.AreEqual(customer2.ContactName, <span style="color:#a31515;">"Luigi Santarelli"</span>); <span style="color:green;">// customer2 has new values </span>}
}</pre>
</div>
<p><strong>PreserveChanges</strong> : this option is quite a compromise between the <em>AppendOnly</em> and the <em>OverwriteChanges</em> options.</p>
<ul>
<li>If we don’t change any property of our entity (i.e. the state of the entity is <a href="http://msdn.microsoft.com/en-us/library/system.data.entitystate.aspx">Unchanged</a>), the current and original values in the entry are overwritten with data source values. The state of the entity remains <a href="http://msdn.microsoft.com/en-us/library/system.data.entitystate.aspx">Unchanged</a> and no properties are marked as modified.</li>
<li>If we change a property of our entity (i.e. the state of the entity is <a href="http://msdn.microsoft.com/en-us/library/system.data.entitystate.aspx">Modified</a>), the current values of modified properties are not overwritten with data source values. The original values of unmodified properties are overwritten with the values from the data source.</li>
<li>Entity Framework v4 compares the current values of unmodified properties with the values that were returned from the data source. If the values are not the same, the property is marked as modified.</li>
</ul>
<p>So, let’s see this behavior in a test&#8230;</p>
<div style="font-size:1.2em;">
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>EF_PreserveChanges_MergeOption_Preserves_Client_Changes()
{
    <span style="color:blue;">using </span>(<span style="color:#2b91af;">EFContext </span>context = <span style="color:blue;">new </span><span style="color:#2b91af;">EFContext</span>())
    {
        <strong>context.Customers.MergeOption = <span style="color:#2b91af;">MergeOption</span>.PreserveChanges;</strong>

        <span style="color:#2b91af;">Customer </span>customer1 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);
        <span style="color:#2b91af;">Assert</span>.AreEqual(customer1.ContactName, <span style="color:#a31515;">"Dario Santarelli"</span>);

        customer1.ContactName = <span style="color:#a31515;">"Carlo Santarelli"</span>; <span style="color:green;">// We change the ContactName in memory</span>

        <span style="color:green;">// Now someone changes the customer1 record in the DB</span>
        <span style="color:green;">// by setting ContactName = "Luigi Santarelli" !!!</span>
        ChangeDBRecord(<span style="color:#a31515;">"dsantarelli"</span>, <span style="color:#a31515;">"Luigi Santarelli"</span>);

        <span style="color:#2b91af;">Customer </span>customer2 = context.Customers.Single(c =&gt; c.CustomerId == <span style="color:#a31515;">"dsantarelli"</span>);

        <span style="color:#2b91af;">Assert</span>.IsTrue(customer1 == customer2); <span style="color:green;">// They are references to the same instance (Identity Map) </span>
        <span style="color:#2b91af;">Assert</span>.AreEqual(customer2.ContactName, <span style="color:#a31515;">"Carlo Santarelli"</span>); <span style="color:green;">// Our changes are preserved! </span>}
}</pre>
</div>
<p>HTH</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2011/11/26/entity-framework-v4-identity-map-pattern/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] Registering the “pack://” scheme in unit tests</title>
		<link>https://dariosantarelli.wordpress.com/2011/08/26/wpf-registering-the-%e2%80%9cpack%e2%80%9d-scheme-in-unit-tests/</link>
					<comments>https://dariosantarelli.wordpress.com/2011/08/26/wpf-registering-the-%e2%80%9cpack%e2%80%9d-scheme-in-unit-tests/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Fri, 26 Aug 2011 17:26:43 +0000</pubDate>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[WPF]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=250</guid>

					<description><![CDATA[A while ago I tried to test some WPF resources stored in an assembly (BAML). When I tried to execute the following code in a unit test… [TestMethod] public void MyStyle_Should_Be_Loaded() {              ResourceDictionary dictionary = new ResourceDictionary();   dictionary.Source = new Uri(&#8220;pack://application:,,,/TestClassLibrary;component/ResourceDictionary.xaml&#8221;,                               [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>A while ago I tried to test some WPF resources stored in an assembly (BAML). When I tried to execute the following code in a unit test…</p>
<p style="line-height:normal;background:white;margin:0;"><span style="font-family:'Courier New';"><span style="color:#000000;"><span style="font-size:8.5pt;">[</span></span><span style="font-size:8.5pt;"><span style="color:#2b91af;">TestMethod</span></span><span style="font-size:8.5pt;color:#000000;">]</span></span></p>
<p style="line-height:normal;background:white;margin:0;"><span style="font-family:'Courier New';"><span style="font-size:8.5pt;"><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">void</span></span><span style="font-size:8.5pt;color:#000000;"> MyStyle_Should_Be_Loaded()</span></span></p>
<p style="line-height:normal;background:white;margin:0;"><span style="font-family:'Courier New';"><span style="font-size:8.5pt;color:#000000;">{            </span></span></p>
<p style="line-height:normal;background:white;margin:0;"><span style="font-family:'Courier New';"><span style="color:#000000;"><span style="font-size:8.5pt;">  </span></span><span style="font-size:8.5pt;"><span style="color:#2b91af;">ResourceDictionary</span><span style="color:#000000;"> dictionary = </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">ResourceDictionary</span></span><span style="font-size:8.5pt;color:#000000;">();</span></span></p>
<p style="line-height:normal;background:white;margin:0;"><span style="font-family:'Courier New';"><span style="color:#000000;"><span style="font-size:8.5pt;">  dictionary.Source = </span></span><span style="font-size:8.5pt;"><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">Uri</span><span style="color:#000000;">(</span><span style="color:#a31515;">&#8220;pack://application:,,,/TestClassLibrary;component/ResourceDictionary.xaml&#8221;</span><span style="color:#000000;">,</span></span></span></p>
<p style="line-height:normal;background:white;margin:0;"><span style="font-family:'Courier New';"><span style="font-size:8.5pt;"><span style="color:#2b91af;">                              UriKind</span></span><span style="font-size:8.5pt;color:#000000;">.RelativeOrAbsolute);</span></span></p>
<p style="line-height:normal;background:white;margin:0;"><span style="font-family:'Courier New';"><span style="color:#000000;"><span style="font-size:8.5pt;">  </span></span><span style="font-size:8.5pt;"><span style="color:#0000ff;">object</span><span style="color:#000000;"> style = dictionary[</span><span style="color:#a31515;">&#8220;myStyle&#8221;</span></span><span style="font-size:8.5pt;color:#000000;">];</span></span></p>
<p style="line-height:normal;background:white;margin:0;"><span style="font-family:'Courier New';"><span style="font-size:8.5pt;color:#000000;"> </span></span></p>
<p style="line-height:normal;background:white;margin:0;"><span style="font-family:'Courier New';"><span style="color:#000000;"><span style="font-size:8.5pt;">  </span></span><span style="font-size:8.5pt;"><span style="color:#2b91af;">Assert</span></span><span style="font-size:8.5pt;color:#000000;">.IsNotNull(style);</span></span></p>
<p style="line-height:normal;background:white;margin:0;"><span style="font-family:'Courier New';"><span style="color:#000000;"><span style="font-size:8.5pt;">  </span></span><span style="font-size:8.5pt;"><span style="color:#2b91af;">Assert</span><span style="color:#000000;">.IsTrue(style </span><span style="color:#0000ff;">is</span><span style="color:#000000;"> </span><span style="color:#2b91af;">Style</span></span><span style="font-size:8.5pt;color:#000000;">);<br />
&#8230;</span></span></p>
<p style="line-height:normal;background:white;margin:0;"><span style="font-family:'Courier New';"><span style="color:#000000;"><span style="font-size:8.5pt;">}<br />
</span></span></span></p>
<p>… I received the following strange error while trying to instantiate the <em>Uri</em> class…</p>
<p><em>System.UriFormatException: Invalid URI: Invalid port specified.</em></p>
<p>But why?<br />
The answer is not so obviuos. That&#8217;s because I was executing that code while the <em>pack://</em> scheme wasn’t yet registered. In fact, this scheme is registered when the <a href="http://msdn.microsoft.com/en-us/library/system.windows.application.aspx" target="_blank">Application</a> object is created. The very simple solution is to execute the following code just before executing the test…</p>
<pre style="background:white;margin:0;"><span style="color:#000000;"><span style="font-size:8.5pt;">[</span></span><span style="color:#2b91af;font-family:Courier New;font-size:11px;line-height:19px;white-space:normal;">TestInitialize</span><span style="font-size:11px;">] </span></pre>
<pre style="background:white;margin:0;"><span style="font-family:Courier New;font-size:13px;line-height:19px;white-space:normal;"><span style="font-size:8.5pt;"><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">void</span></span></span><span style="font-family:Courier New;font-size:13px;line-height:19px;white-space:normal;"><span style="font-family:Consolas, Monaco, monospace;font-size:11px;line-height:18px;white-space:pre;background-color:#ffffff;"> OnTestInitialize() </span></span></pre>
<pre style="background:white;margin:0;"><span style="font-size:11px;">{ </span><span style="font-family:Courier New;font-size:11px;line-height:19px;white-space:normal;"><span style="color:#0000ff;">  </span></span></pre>
<pre style="background:white;margin:0;"><span style="font-family:Courier New;font-size:11px;line-height:19px;white-space:normal;"><span style="color:#0000ff;">   if</span><span style="color:#000000;"> (!</span><span style="color:#2b91af;">UriParser</span><span style="color:#000000;">.IsKnownScheme(</span><span style="color:#a31515;">"pack"</span><span style="color:#000000;">)) </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> System.Windows.</span><span style="color:#2b91af;">Application</span></span><span style="font-size:11px;">();</span></pre>
<pre style="background:white;margin:0;"><span style="font-family:Courier New;font-size:11px;line-height:19px;white-space:normal;">} </span></pre>
<pre style="background:white;margin:0;"><span style="font-family:Courier New;font-size:11px;line-height:19px;white-space:normal;"> </span></pre>
<p>HTH</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2011/08/26/wpf-registering-the-%e2%80%9cpack%e2%80%9d-scheme-in-unit-tests/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>[WPF] Inheritance and DataTemplates</title>
		<link>https://dariosantarelli.wordpress.com/2011/07/28/wpf-inheritance-and-datatemplates/</link>
					<comments>https://dariosantarelli.wordpress.com/2011/07/28/wpf-inheritance-and-datatemplates/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Thu, 28 Jul 2011 20:15:37 +0000</pubDate>
				<category><![CDATA[WPF]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=168</guid>

					<description><![CDATA[In this post I will show how different DataTemplates related to a hierarchy of classes can be nested and, therefore, reused. The concept is very simple, but its applications in a real scenario could be not so trivial! Let’s assume to have a base ViewModel useful for editing and saving an object of your model. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post I will show how different DataTemplates related to a hierarchy of classes can be nested and, therefore, reused. The concept is very simple, but its applications in a real scenario could be not so trivial!</p>
<p>Let’s assume to have a base ViewModel useful for editing and saving an object of your model. If the object class is subject to some derivations, maybe you’d like to derive your base ViewModel too in order to fulfill the model inheritance hierarchy. Moreover, most probably you have to define different editing views taking into account the whole inheritance hierarchy. In that case, maybe you&#8217;d like to reuse more XAML as possible.</p>
<p>So, let&#8217;s assume to have a base abstract<em> Customer</em> class and some concrete specializations, like <em>EducationCustomer</em> and <em>GovernmentCustomer</em> (see image below).   <a href="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/customers.jpg"><img   data-attachment-id="169" data-permalink="https://dariosantarelli.wordpress.com/2011/07/28/wpf-inheritance-and-datatemplates/immagine/" data-orig-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine.jpg" data-orig-size="428,419" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="Customer class hierarchy" data-image-description="" data-image-caption="" data-medium-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine.jpg?w=300" data-large-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine.jpg?w=428" class="size-medium wp-image-169 aligncenter" style="display:block;float:none;margin:5px auto;" title="Customer class hierarchy" src="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine.jpg?w=300&#038;h=293" alt="Customer class hierarchy" srcset="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine.jpg?w=400 400w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine.jpg?w=150 150w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine.jpg?w=300 300w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine.jpg 428w" sizes="(max-width: 400px) 100vw, 400px" /></a>Then, we design ViewModels in order to edit concrete instances of Customer class. In the class diagram below you can see a base <em>ItemEditViewModel&lt;T&gt;</em> which consists in a simple generic ViewModel which exposes a generic <em>Item</em> to be modified and a <em>SaveCommand</em> to persist it somewhere. The class also defines an abstract method <em>OnCanSaveItem()</em> which a concrete implementation must override in order to specify its own validation rules.   <img   data-attachment-id="170" data-permalink="https://dariosantarelli.wordpress.com/2011/07/28/wpf-inheritance-and-datatemplates/immagine-2/" data-orig-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine1.jpg" data-orig-size="767,614" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="ViewModel hierarchy" data-image-description="" data-image-caption="" data-medium-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine1.jpg?w=300" data-large-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine1.jpg?w=767" class="size-medium wp-image-170 aligncenter" style="display:block;float:none;margin:5px auto;" title="ViewModel hierarchy" src="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine1.jpg?w=300&#038;h=240" alt="ViewModel hierarchy" srcset="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine1.jpg?w=700 700w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine1.jpg?w=150 150w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine1.jpg?w=300 300w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine1.jpg 767w" sizes="(max-width: 700px) 100vw, 700px" /></p>
<pre style="font-size:8.5pt;"><span style="color:#0000ff;">public</span><span style="color:#0000ff;"> abstract </span><span style="color:#0000ff;">class</span><span style="color:#2b91af;"> CustomerEditViewModel</span><span style="color:#000000;">&lt;T&gt; : </span><span style="color:#2b91af;">ItemEditViewModel</span><span style="color:#000000;">&lt;T&gt; </span><span style="color:#0000ff;">where</span><span style="color:#000000;"> T : </span><span style="color:#2b91af;">Customer</span>
<span style="color:#000000;">{</span>
<span style="color:#0000ff;"> public</span><span style="color:#000000;"> CustomerEditViewModel(T customer) : </span><span style="color:#0000ff;">base</span><span style="color:#000000;">(customer) { }</span>
<span style="color:#0000ff;"> public</span><span style="color:#000000;"> CustomerEditViewModel() { } </span>

<span style="color:#0000ff;"> protected</span><span style="color:#0000ff;"> override </span><span style="color:#0000ff;">bool</span><span style="color:#000000;"> OnCanSaveItem() </span>
<span style="color:#000000;"> {</span>
<span style="color:#0000ff;"> if</span><span style="color:#000000;"> (Item == </span><span style="color:#0000ff;">null</span><span style="color:#000000;">) </span><span style="color:#0000ff;"> return</span><span style="color:#0000ff;"> false</span><span style="color:#000000;">; </span>
<span style="color:#0000ff;"> return</span><span style="color:#000000;"> (!</span><span style="color:#0000ff;">string</span><span style="color:#000000;">.IsNullOrWhiteSpace(Item.Name) &amp;&amp; !</span><span style="color:#0000ff;">string</span><span style="color:#000000;">.IsNullOrWhiteSpace(Item.Email)); </span>
<span style="color:#000000;"> } </span>
<span style="color:#000000;">}</span>

<span style="color:#0000ff;">public </span><span style="color:#0000ff;">class </span><span style="color:#2b91af;">EducationCustomerEditViewModel</span><span style="color:#000000;"> : </span><span style="color:#2b91af;">CustomerEditViewModel</span><span style="color:#000000;">&lt;</span><span style="color:#2b91af;">EducationCustomer</span><span style="color:#000000;">&gt; </span>
<span style="color:#000000;">{</span>
<span style="color:#0000ff;"> public</span><span style="color:#000000;"> EducationCustomerEditViewModel() : </span><span style="color:#0000ff;">base</span><span style="color:#000000;">() { }</span>
<span style="color:#0000ff;"> public</span><span style="color:#000000;"> EducationCustomerEditViewModel(</span><span style="color:#2b91af;">EducationCustomer</span><span style="color:#000000;"> customer) : </span><span style="color:#0000ff;">base</span><span style="color:#000000;">(customer) { }</span> 

 <span style="color:#0000ff;">protected </span><span style="color:#0000ff;">override </span><span style="color:#0000ff;">bool</span><span style="color:#000000;"> OnCanSaveItem() </span>
<span style="color:#000000;"> {</span>
<span style="color:#0000ff;"> if</span><span style="color:#000000;"> (!</span><span style="color:#0000ff;">base</span><span style="color:#000000;">.OnCanSaveItem()) </span><span style="color:#0000ff;">return</span><span style="color:#0000ff;"> false</span><span style="color:#000000;">;</span>
<span style="color:#0000ff;"> else </span><span style="color:#0000ff;">return</span><span style="color:#000000;"> (!</span><span style="color:#0000ff;">string</span><span style="color:#000000;">.IsNullOrWhiteSpace(Item.SchoolName)); </span>
<span style="color:#000000;"> } </span>
<span style="color:#000000;">} </span> 

<span style="color:#0000ff;">public </span><span style="color:#0000ff;">class </span><span style="color:#2b91af;">GovernmentCustomerEditViewModel</span><span style="color:#000000;"> : </span><span style="color:#2b91af;">CustomerEditViewModel</span><span style="color:#000000;">&lt;</span><span style="color:#2b91af;">GovernmentCustomer</span><span style="color:#000000;">&gt;</span>
<span style="color:#000000;">{</span>
  <span style="color:#0000ff;">public</span><span style="color:#000000;"> GovernmentCustomerEditViewModel() : </span><span style="color:#0000ff;">base</span><span style="color:#000000;">() { }</span>
  <span style="color:#0000ff;">public</span><span style="color:#000000;"> GovernmentCustomerEditViewModel(</span><span style="color:#2b91af;">GovernmentCustomer</span><span style="color:#000000;"> customer) : </span><span style="color:#0000ff;">base</span><span style="color:#000000;">(customer) { }</span>

  <span style="color:#0000ff;">protected</span><span style="color:#0000ff;"> override </span><span style="color:#0000ff;">bool</span><span style="color:#000000;"> OnCanSaveItem()</span>
  <span style="color:#000000;">{</span>
   <span style="color:#0000ff;">if</span><span style="color:#000000;"> (!</span><span style="color:#0000ff;">base</span><span style="color:#000000;">.OnCanSaveItem()) </span><span style="color:#0000ff;">return</span><span style="color:#0000ff;"> false</span><span style="color:#000000;">;</span>
   <span style="color:#0000ff;">else</span><span style="color:#0000ff;"> return</span><span style="color:#000000;"> (!</span><span style="color:#0000ff;">string</span><span style="color:#000000;">.IsNullOrWhiteSpace(Item.AgencyName));</span>
  <span style="color:#000000;">}</span>
<span style="color:#000000;">}</span></pre>
<p>Ok, we have just defined model and viewmodels. Now the interesting part! Our datatemplates could share some portions of XAML (e.g. the edit DataTemplate of the <em>GovernmentCustomer</em> is quite identical to the DataTemplate of the <em>EducationCustomer</em>, but it differs from the former just for a field). So, how can we reuse DataTemplates? First, we can define the edit DataTemplate for the base Customer class…</p>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">DataTemplate</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Key</span>=<span style="color:#0000ff;">"customerEditTemplate"</span> <span style="color:#ff0000;">DataType</span>=<span style="color:#0000ff;">"{x:Type m:Customer}"</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">  <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Grid</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    ...</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">TextBlock</span> <span style="color:#ff0000;">Text</span>=<span style="color:#0000ff;">"Name"</span> ... <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">TextBox</span> <span style="color:#ff0000;">Text</span>=<span style="color:#0000ff;">"{Binding Path=Name, Mode=TwoWay}"</span> ... <span style="color:#ff0000;">Background</span>=<span style="color:#0000ff;">"AliceBlue"</span> <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">TextBlock</span> <span style="color:#ff0000;">Text</span>=<span style="color:#0000ff;">"Email"</span> ... <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">TextBox</span> <span style="color:#ff0000;">Text</span>=<span style="color:#0000ff;">"{Binding Path=Email, Mode=TwoWay}"</span> ... <span style="color:#ff0000;">Background</span>=<span style="color:#0000ff;">"AliceBlue"</span> <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">  <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Grid</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;"><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">DataTemplate</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;"></pre>
<p>&nbsp;<br />
and then, we can reuse the XAML above in the edit DataTemplate for the <em>GovernmentCustomer</em> and the <em>EducationCustomer.</em></p>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">DataTemplate</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Key</span>=<span style="color:#0000ff;">"governmentCustomerEditTemplate"</span> <span style="color:#ff0000;">DataType</span>=<span style="color:#0000ff;">"{x:Type m:GovernmentCustomer}"</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">  <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">StackPanel</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <strong><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">ContentPresenter</span> <span style="color:#ff0000;">ContentTemplate</span>=<span style="color:#0000ff;">"{StaticResource customerEditTemplate}"</span> <span style="color:#0000ff;">/&gt;</span></strong></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Grid</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    ...</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">     <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">TextBlock</span> <span style="color:#ff0000;">Text</span>=<span style="color:#0000ff;">"Agency"</span> ... <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">     <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">TextBox</span> <span style="color:#ff0000;">Text</span>=<span style="color:#0000ff;">"{Binding Path=AgencyName, Mode=TwoWay}"</span> ... <span style="color:#ff0000;">Background</span>=<span style="color:#0000ff;">"LightPink"</span> <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">   <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Grid</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">  <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">StackPanel</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;"><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">DataTemplate</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;"></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">DataTemplate</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Key</span>=<span style="color:#0000ff;">"educationCustomerEditTemplate"</span> <span style="color:#ff0000;">DataType</span>=<span style="color:#0000ff;">"{x:Type m:EducationCustomer}"</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">  <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">StackPanel</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <strong><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">ContentPresenter</span> <span style="color:#ff0000;">ContentTemplate</span>=<span style="color:#0000ff;">"{StaticResource customerEditTemplate}"</span> <span style="color:#0000ff;">/&gt;</span></strong></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Grid</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">      ...</pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">      <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">TextBlock</span> <span style="color:#ff0000;">Text</span>=<span style="color:#0000ff;">"School"</span> ... <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">      <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">TextBox</span> <span style="color:#ff0000;">Text</span>=<span style="color:#0000ff;">"{Binding Path=SchoolName, Mode=TwoWay}"</span> ... <span style="color:#ff0000;">Background</span>=<span style="color:#0000ff;">"Yellow"</span> <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Grid</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">  <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">StackPanel</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;"><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">DataTemplate</span><span style="color:#0000ff;">&gt;</span></pre>
<p>&nbsp;<br />
OK, that&#8217;s all. Finally, a simple view can be implemented as below&#8230;</p>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Window</span> ...<span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">  <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Window.Resources</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">m</span>:<span style="color:#800000;">GovernmentCustomer</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Key</span>=<span style="color:#0000ff;">"governmentCustomer"</span> <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">m</span>:<span style="color:#800000;">EducationCustomer</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Key</span>=<span style="color:#0000ff;">"educationCustomer"</span> <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">vm</span>:<span style="color:#800000;">GovernmentCustomerEditViewModel</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Key</span>=<span style="color:#0000ff;">"governmentCustomerEditVM"</span> <span style="color:#ff0000;">Item</span>=<span style="color:#0000ff;">"{StaticResource governmentCustomer}"</span> <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">vm</span>:<span style="color:#800000;">EducationCustomerEditViewModel</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Key</span>=<span style="color:#0000ff;">"educationCustomerEditVM"</span> <span style="color:#ff0000;">Item</span>=<span style="color:#0000ff;">"{StaticResource educationCustomer}"</span> <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">  <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Window.Resources</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;"></pre>
<p>&nbsp;</p>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">  <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">StackPanel</span> <span style="color:#ff0000;">DataContext</span>=<span style="color:#0000ff;">"{StaticResource governmentCustomerEditVM}"</span> <span style="color:#ff0000;">Margin</span>=<span style="color:#0000ff;">"10"</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">ContentPresenter</span> <span style="color:#ff0000;">Content</span>=<span style="color:#0000ff;">"{Binding Path=Item}"</span> <span style="color:#ff0000;">ContentTemplate</span>=<span style="color:#0000ff;">"{StaticResource governmentCustomerEditTemplate}"</span> <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Button</span> <span style="color:#ff0000;">Content</span>=<span style="color:#0000ff;">"Save"</span><span style="color:#ff0000;">Command</span>=<span style="color:#0000ff;">"{Binding Path=SaveItemCommand}"</span>... <span style="color:#0000ff;">/&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;">  <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">StackPanel</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;"><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Window</span><span style="color:#0000ff;">&gt;</span></pre>
<pre style="background-color:#ffffff;width:100%;font-family:consolas,'Courier New',courier,monospace;font-size:12px;margin:0;"></pre>
<p>&nbsp;<br />
As you can see, in this example the edit DataTemplate is referenced by key, but in a real scenario you can define your own mechanism to bind the right ViewModel to a DataTemplate for the Item to be edited and saved. In this example, the output result is the following</p>
<p><a href="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine11.jpg"><img width="300" height="181" data-attachment-id="177" data-permalink="https://dariosantarelli.wordpress.com/2011/07/28/wpf-inheritance-and-datatemplates/immagine1/" data-orig-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine11.jpg" data-orig-size="334,202" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="EducationCustomer edit Window" data-image-description="" data-image-caption="" data-medium-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine11.jpg?w=300" data-large-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine11.jpg?w=334" class="alignnone size-medium wp-image-177" title="EducationCustomer edit Window" src="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine11.jpg?w=300&#038;h=181" alt="EducationCustomer edit Window" srcset="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine11.jpg?w=300 300w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine11.jpg?w=150 150w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine11.jpg 334w" sizes="(max-width: 300px) 100vw, 300px" /></a><a href="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine21.jpg"><img loading="lazy" width="300" height="180" data-attachment-id="180" data-permalink="https://dariosantarelli.wordpress.com/2011/07/28/wpf-inheritance-and-datatemplates/immagine2-2/" data-orig-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine21.jpg" data-orig-size="335,201" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="GovernmentCustomer edit window" data-image-description="" data-image-caption="" data-medium-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine21.jpg?w=300" data-large-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine21.jpg?w=335" class="alignnone size-medium wp-image-180" title="GovernmentCustomer edit Window" src="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine21.jpg?w=300&#038;h=180" alt="GovernmentCustomer edit Window" srcset="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine21.jpg?w=300 300w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine21.jpg?w=150 150w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine21.jpg 335w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>HTH</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2011/07/28/wpf-inheritance-and-datatemplates/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>

		<media:content url="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine.jpg?w=400" medium="image">
			<media:title type="html">Customer class hierarchy</media:title>
		</media:content>

		<media:content url="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine1.jpg?w=700" medium="image">
			<media:title type="html">ViewModel hierarchy</media:title>
		</media:content>

		<media:content url="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine11.jpg?w=300" medium="image">
			<media:title type="html">EducationCustomer edit Window</media:title>
		</media:content>

		<media:content url="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/07/immagine21.jpg?w=300" medium="image">
			<media:title type="html">GovernmentCustomer edit Window</media:title>
		</media:content>
	</item>
		<item>
		<title>[.NET Compact Framework] Working with Point-to-Point Message Queues</title>
		<link>https://dariosantarelli.wordpress.com/2011/06/11/net-compact-framework-working-with-point-to-point-message-queues/</link>
					<comments>https://dariosantarelli.wordpress.com/2011/06/11/net-compact-framework-working-with-point-to-point-message-queues/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sat, 11 Jun 2011 14:45:56 +0000</pubDate>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Compact Framework]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=132</guid>

					<description><![CDATA[While working on a project of mine, I’ve got to face an interprocess communication (IPC) on a Windows CE device. In my scenario, the device vendor uses the Message Queue Point-To-Point infrastructure so that native processes can communicate with managed processes through IPC. On other Windows platforms, IPC can be achieved through named pipes (native) or remoting [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>While working on a project of mine, I’ve got to face an interprocess communication (IPC) on a Windows CE device. In my scenario, the device vendor uses the Message Queue Point-To-Point infrastructure so that native processes can communicate with managed processes through IPC. On other Windows platforms, IPC can be achieved through named pipes (native) or remoting (managed), but none of these options are available to Windows CE. Point-to-point represents a little-known IPC mechanism that is efficient, flexible, and unique to Windows CE version 4.0 and later. Moreover it can interact with the operating system, for example, for getting power information.</p>
<p>If you don’t know this feature of Windows CE, first of all you should read this MSDN article:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa446556.aspx">Point-to-Point Message Queues with the .NET Compact Framework</a>.</p>
<p>After analyzing the managed wrapper proposed by the article, I’ve started to refactor the source code in order to make it more suitable for my needs. So, I’d like to share my design and implementation :).</p>
<p><a href="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/cd.jpg"><img loading="lazy" data-attachment-id="135" data-permalink="https://dariosantarelli.wordpress.com/2011/06/11/net-compact-framework-working-with-point-to-point-message-queues/cd/" data-orig-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/cd.jpg" data-orig-size="1317,598" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="Class Diagram" data-image-description="" data-image-caption="" data-medium-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/cd.jpg?w=300" data-large-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/cd.jpg?w=1024" class="alignnone size-medium wp-image-135" title="Class Diagram" src="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/cd.jpg?w=300&#038;h=136" alt="" width="300" height="136" srcset="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/cd.jpg?w=300 300w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/cd.jpg?w=600 600w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/cd.jpg?w=150 150w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>Let’s explain some key concepts:</p>
<ul>
<li>A message queue can be addressed by a name or, generally, by an handle. The handle is the only data you can refer to if the queue has no name (NULL). Note that the empty string is considered a valid, non-null name.</li>
<li>A message queue can be <em>read-only</em> or <em>write-only</em>: it means that a process can get an handle to a message queue just for reading or writing messages. If you want to read from and write to the same queue, you should create two handles pointing to the same queue.</li>
<li>Message queues are FIFO. Writers can write messages in a queue until it’s full and readers can read messages from a queue until it’s empty. When a reader process invokes a read operation on a message queue, the first unread message is removed from the queue and delivered to the reading process.</li>
</ul>
<p>As you can see in the class diagram above, I’ve defined an abstract <em>MessageQueue</em> class which holds the queue info ( e.g. the max length, the max message length, the current readers/writers count and so on&#8230; ) and exposes a generic factory method for creating concrete implementations.</p>
<p><span lang="EN-US" style="color:blue;line-height:115%;font-family:'Courier New';font-size:8pt;">public</span><span lang="EN-US" style="line-height:115%;font-family:'Courier New';font-size:8pt;"> <span style="color:blue;">static </span>T Create&lt;T&gt;(<span style="color:blue;">string</span> name) <span style="color:blue;">where</span> T : <span style="color:#2b91af;">MessageQueue</span></span><span lang="EN-US" style="line-height:115%;font-family:'Courier New';font-size:8pt;"><span style="color:#2b91af;"><br />
</span></span><span lang="EN-US" style="color:blue;line-height:115%;font-family:'Courier New';font-size:8pt;">public</span><span lang="EN-US" style="line-height:115%;font-family:'Courier New';font-size:8pt;"> <span style="color:blue;">static </span>T Create&lt;T&gt;(<span style="color:blue;">string</span> name, <span style="color:blue;">int</span> length) <span style="color:blue;">where</span> T : <span style="color:#2b91af;">MessageQueue</span></span><span lang="EN-US" style="line-height:115%;font-family:'Courier New';font-size:8pt;"><span style="color:#2b91af;"><br />
</span></span><span lang="EN-US" style="color:blue;line-height:115%;font-family:'Courier New';font-size:8pt;">public</span><span lang="EN-US" style="line-height:115%;font-family:'Courier New';font-size:8pt;"> <span style="color:blue;">static </span>T Create&lt;T&gt;(<span style="color:blue;">string</span> name, <span style="color:blue;">int</span> length, <span style="color:blue;">int</span> maxMessageLength) <span style="color:blue;">where</span> T : <span style="color:#2b91af;">MessageQueue</span></span><span lang="EN-US" style="line-height:115%;font-family:'Courier New';font-size:8pt;"><span style="color:#2b91af;"><br />
</span></span></p>
<p>Let&#8217;s have a look to them:</p>
<h3><strong>WriteOnlyMessageQueue</strong></h3>
<p>It&#8217;s a concrete class for writing messages in a queue. The class exposes some overloads of the <em>Write()</em> method in order to write a message in a queue and choose whether to block the calling thread until the message is written in the queue (that is the queue is not full).</p>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;"><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:green;">// Create or open an infinite user-defined write-only MessageQueue<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:#2b91af;">WriteOnlyMessageQueue</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';"> writeOnlyMessageQueue = <span style="color:#2b91af;">MessageQueue</span>.Create&lt;<span style="color:#2b91af;">WriteOnlyMessageQueue</span>&gt;(<span style="color:#a31515;">&#8220;MyQueueName&#8221;</span>);</span></p>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;"><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:#2b91af;">Message</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';"> message = <span style="color:blue;">new</span> <span style="color:#2b91af;">Message</span>(<span style="color:#2b91af;">UTF8Encoding</span>.UTF8.GetBytes(<span style="color:#a31515;">&#8220;Hello world!&#8221;</span>));</span></p>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;"><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';"><br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:green;">// WRITE OPTIONS<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:green;">// 1. block the current thread until a message can be written into the queue (that is the queue is not full).<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';">writeOnlyMessageQueue.Write(message, <span style="color:blue;">true</span>);</span></p>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;"><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:green;"><br />
// 2. block the current thread for a max of 200 ms. If the message can&#8217;t be written during this interval, throw an exception.<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:blue;">try</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';"> { writeOnlyMessageQueue.Write(message, 200); } <span style="color:blue;">catch </span>(<span style="color:#2b91af;">Exception</span> ex) { }</span></p>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;"><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:green;"><br />
// 3. don&#8217;t block the current thread. If a message can&#8217;t be written immediately, throw an exception.<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:blue;">try</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';"> { writeOnlyMessageQueue.Write(message, <span style="color:blue;">false</span>); } <span style="color:blue;">catch</span> (<span style="color:#2b91af;">Exception</span> ex) { }</span></p>
<h3><strong><strong>ReadOnlyMessageQueue</strong></strong></h3>
<p>It&#8217;s a concrete class for reading messages from a queue. The class exposes some overloads of the <em>Read()</em> method in order read a message from a queue and choose whether to block the calling thread until a message can be read from the queue (that is the queue is not empty).</p>
<p><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:green;">// Create or open an infinite user-defined read-only MessageQueue<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:#2b91af;">ReadOnlyMessageQueue</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';"> readOnlyMessageQueue = <span style="color:#2b91af;">MessageQueue</span>.Create&lt;<span style="color:#2b91af;">ReadOnlyMessageQueue</span>&gt;(<span style="color:#a31515;">&#8220;MyQueueName&#8221;</span>);<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:#2b91af;">Message</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';"> message = <span style="color:blue;">null</span>;</span></p>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;"><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:green;">// READ OPTIONS<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:green;">// 1. block the current thread until a message can be read from the queue.<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';">message = readOnlyMessageQueue.Read(<span style="color:blue;">true</span>);</span></p>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;"><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:green;">// 2. block the current thread for a max of 200 ms. If no message has been read during this interval, throw an exception.<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:blue;">try</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';"> { message = readOnlyMessageQueue.Read(200); } <span style="color:blue;">catch</span> (<span style="color:#2b91af;">Exception</span> ex) { &#8230; }</span></p>
<p class="MsoNormal" style="line-height:normal;margin-bottom:0;"><span lang="EN-US" style="color:green;font-family:'Courier New';font-size:8pt;">// 3. don&#8217;t block the current thread. If a message can&#8217;t be read immediately, throw an exception.<br />
</span><span lang="EN-US" style="color:blue;font-family:'Courier New';font-size:8pt;">try</span><span lang="EN-US" style="font-family:'Courier New';font-size:8pt;"> { message = readOnlyMessageQueue.Read(<span style="color:blue;">false</span>); } <span style="color:blue;">catch</span> (<span style="color:#2b91af;">Exception</span> ex) { &#8230; }</span><span lang="EN-US" style="color:black;font-family:'Segoe UI', sans-serif;font-size:9.5pt;"><br />
</span></p>
<h3><strong>AutoReadOnlyMessageQueue</strong></h3>
<p>It&#8217;s a concrete class derived from <em>ReadOnlyMessageQueue.</em> It uses a monitoring thread useful to automatically read messages after they are written in the queue. So, the class exposes a <em>MessageRead</em> event which is fired for each message read from the queue.</p>
<p class="MsoNormal" style="line-height:normal;margin-bottom:0;"><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:green;">// Create or open an infinite user-defined read-only MessageQueue<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:#2b91af;">AutoReadOnlyMessageQueue</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';"> autoReadOnlyMessageQueue = <span style="color:#2b91af;">MessageQueue</span>.Create&lt;<span style="color:#2b91af;">AutoReadOnlyMessageQueue</span>&gt;(<span style="color:#a31515;">&#8220;MyQueueName&#8221;</span>);</span></p>
<p class="MsoNormal" style="line-height:normal;margin-bottom:0;"><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:green;">// Starts monitoring the queue.<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';color:green;">// New messages will be read automatically and notified through the MessageRead event.<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';">autoReadOnlyMessageQueue.Start();<br />
</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';">autoReadOnlyMessageQueue.MessageRead += (s, e) =&gt; </span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';">{</span><span lang="EN-US" style="font-size:8pt;font-family:'Courier New';"> <span style="color:blue;">byte</span>[] messageBytes = e.Message.Bytes; };  </span></p>
<p class="MsoNormal">Another static method exposed by the <em>MessageQueue</em> class is <em>OpenByHandle()</em>.  It allows you to open a  MessageQueue by using its handle. This method is suitable to open unnamed queues.</p>
<p><span lang="EN-US" style="font-size:8pt;line-height:115%;font-family:'Courier New';color:blue;">public</span><span lang="EN-US" style="font-size:8pt;line-height:115%;font-family:'Courier New';"> <span style="color:blue;">static </span>T OpenByHandle&lt;T&gt;(<span style="color:#2b91af;">IntPtr</span> queueHandle) <span style="color:blue;">where</span> T : <span style="color:#2b91af;">MessageQueue<br />
</span><span style="color:blue;">public</span> <span style="color:blue;">static </span>T OpenByHandle&lt;T&gt;(<span style="color:#2b91af;">IntPtr</span> queueHandle, <span style="color:#2b91af;">IntPtr</span> processHandle) <span style="color:blue;">where </span>T : <span style="color:#2b91af;">MessageQueue</span></span></p>
<p>As you can see, in this case you need an handle to a source process that owns the message queue, while the queue handle is the same returned by the <em>Create()</em> method.<br />
Finally I&#8217;ve created a simple smart device project for testing this class library (Visual Studio 2008 / Framework 2.0 or 3.5) just refactoring the example proposed by the author of the MSDN article mentioned above.</p>
<p>You can <a href="https://drive.google.com/uc?id=0B1K9CT6hPsRAa212NER0UWdNVDg&amp;export=download">download source code here</a>.</p>
<p>Here’s a screenshot:</p>
<p class="MsoNormal"><a href="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/ss1.jpg"><img loading="lazy" data-attachment-id="136" data-permalink="https://dariosantarelli.wordpress.com/2011/06/11/net-compact-framework-working-with-point-to-point-message-queues/ss-2/" data-orig-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/ss1.jpg" data-orig-size="578,326" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="Message Queue Point-To-Point Test Application" data-image-description="" data-image-caption="" data-medium-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/ss1.jpg?w=300" data-large-file="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/ss1.jpg?w=578" class="alignnone size-medium wp-image-136" title="Message Queue Point-To-Point Test Application" src="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/ss1.jpg?w=300&#038;h=169" alt="" width="300" height="169" srcset="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/ss1.jpg?w=300 300w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/ss1.jpg?w=150 150w, https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/ss1.jpg 578w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p class="MsoNormal">HTH</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2011/06/11/net-compact-framework-working-with-point-to-point-message-queues/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>

		<media:content url="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/cd.jpg?w=300" medium="image">
			<media:title type="html">Class Diagram</media:title>
		</media:content>

		<media:content url="https://dariosantarelli.wordpress.com/wp-content/uploads/2011/06/ss1.jpg?w=300" medium="image">
			<media:title type="html">Message Queue Point-To-Point Test Application</media:title>
		</media:content>
	</item>
		<item>
		<title>[ASP.NET MVC 2] Splitting DateTime in drop-down lists and model binding</title>
		<link>https://dariosantarelli.wordpress.com/2010/12/26/asp-net-mvc-2-splitting-datetime-in-drop-down-lists-and-model-binding/</link>
					<comments>https://dariosantarelli.wordpress.com/2010/12/26/asp-net-mvc-2-splitting-datetime-in-drop-down-lists-and-model-binding/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sun, 26 Dec 2010 16:33:27 +0000</pubDate>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Binding]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/?p=112</guid>

					<description><![CDATA[OK this is not the classic DateTime picker bound to a textbox… with a jQuery calendar ;). If you need a custom datetime editor template that splits the datetime parts in drop-down lists like this… &#60;%= Html.EditorFor(model =&#62; model.BirthDate, &#8220;Date&#8221;) %&#62; …or like this… &#160; &#60;%= Html.EditorFor(model =&#62; model.EventDateTime, &#8220;DateTime&#8221;) %&#62; …then this post may [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>OK this is not the classic DateTime picker bound to a textbox… with a jQuery calendar ;).<br />
If you need a custom datetime editor template that splits the datetime parts in drop-down lists like this…</p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;"><span style="background-color:#ffff00;color:#000000;"><span style="font-size:10pt;">&lt;%</span></span><span style="font-size:10pt;"><span style="color:#0000ff;">=</span></span><span style="font-size:10pt;"><span style="color:#000000;"> Html.EditorFor(model =&gt; model.BirthDate, </span><span style="color:#a31515;">&#8220;Date&#8221;</span><span style="color:#000000;">) </span></span><span style="font-size:10pt;background-color:#ffff00;color:#000000;">%&gt;</span></span><br />
<img style="margin:5px;" src="https://i0.wp.com/img269.imageshack.us/img269/9956/immaginewv.jpg" alt="" /></p>
<p>…or like this…</p>
<p class="MsoNormal" style="line-height:normal;margin:0;">&nbsp;</p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;"><span style="background-color:#ffff00;color:#000000;"><span style="font-size:10pt;">&lt;%</span></span><span style="font-size:10pt;"><span style="color:#0000ff;">=</span></span><span style="font-size:10pt;"><span style="color:#000000;"> Html.EditorFor(model =&gt; model.EventDateTime, </span><span style="color:#a31515;">&#8220;DateTime&#8221;</span><span style="color:#000000;">) </span></span><span style="font-size:10pt;background-color:#ffff00;color:#000000;">%&gt;</span></span></p>
<p><img style="margin:5px;" src="https://i0.wp.com/img547.imageshack.us/img547/5513/immagine1fj.jpg" alt="" /></p>
<p>…then this post may help you. As you should know, in ASP.NET MVC 2 the default model binder has some difficulties to combine splitted datetime parts in the View. So, if you need to define a DateTime property in your model and make a custom editor template that splits the DateTime parts in different controls (e.g. TextBox and/or DropDownList), first <span style="text-decoration:underline;">you should read </span><a href="http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx"><span style="text-decoration:underline;">this smart solution</span></a><span style="text-decoration:underline;"> by </span><a href="http://www.hanselman.com/"><span style="text-decoration:underline;">Scott Hanselman</span></a>. The idea is to separate the way we render the month field, the day field, the year field etc. from the mechanism that will assemble them back in a DateTime structure for model binding.<br />
Starting from the <strong>Global.asax, </strong>the first thing to do is to register the Scott’s Custom Model Binder and then specify all the available options (the strings there are the suffixes of the fields in your View that will be holding the Date, the Time, the Day etc.)</p>
<pre><span style="color:#2b91af;font-family:Consolas;">ModelBinders</span><span style="font-family:Consolas;"><span style="color:#000000;">.Binders[</span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(</span><span style="color:#2b91af;">DateTime</span><span style="color:#000000;">)]  = </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">DateTimeModelBinder</span></span><span style="font-family:Consolas;"><span style="color:#000000;">()
{
  Date = </span><span style="color:#a31515;">"Date"</span></span><span style="font-family:Consolas;"><span style="color:#000000;">, </span></span><span style="font-family:Consolas;"><span style="color:#008000;">// Date parts are not splitted in the View
                 // (e.g. the whole date is held by a TextBox  with id “xxx_Date”)</span></span><span style="font-family:Consolas;"><span style="color:#000000;">
  Time = </span><span style="color:#a31515;">"Time"</span></span><span style="font-family:Consolas;"><span style="color:#000000;">, <span style="font-family:Consolas;"><span style="color:#008000;">// Time parts are not  splitted in the View
                 // (e.g. the whole time  is held by a TextBox with id “xxx_Time”)</span></span>
 <strong> Day = </strong></span><span style="color:#a31515;"><strong>"Day"</strong></span></span><span style="font-family:Consolas;"><strong><span style="color:#000000;">, <span style="font-family:Consolas;"><span style="color:#008000;"> </span></span>
  Month = </span><span style="color:#a31515;">"Month"</span></strong></span><span style="font-family:Consolas;"><strong><span style="color:#000000;">,
  Year = </span><span style="color:#a31515;">"Year"</span></strong></span><span style="font-family:Consolas;"><strong><span style="color:#000000;">,
  Hour = </span><span style="color:#a31515;">"Hour"</span></strong></span><span style="font-family:Consolas;"><strong><span style="color:#000000;">,
  Minute = </span><span style="color:#a31515;">"Minute"</span></strong></span><span style="font-family:Consolas;"><strong><span style="color:#000000;">,
  Second = </span><span style="color:#a31515;">"Second"</span>
</strong><span style="color:#000000;">};</span></span></pre>
<p><span style="font-family:Consolas;"><span style="color:#000000;"><br />
</span></span></p>
<p>Now, let’s have a look to template editors. In <strong>Views\Shared\EditorTemplates</strong> directory we can put two simple templates: <em><strong>Date.ascx</strong></em> and <em><strong>DateTime.ascx</strong></em>. The former renders only the drop-down lists for the date part of the DateTime structure (Month, Day, Year), while the latter renders the time part too. Here the code for <em>Date.ascx</em>:</p>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="background-color:#ffff00;color:#000000;"><span style="font-size:10pt;">&lt;%</span></span><span style="font-size:10pt;"><span style="color:#0000ff;">@</span></span></span><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;"> </span><span style="color:#800000;">Control</span><span style="color:#000000;"> </span><span style="color:#ff0000;">Language</span><span style="color:#0000ff;">="C#"</span><span style="color:#000000;"> </span><span style="color:#ff0000;">Inherits</span><span style="color:#0000ff;">="System.Web.Mvc.ViewUserControl&lt;System.DateTime&gt;"</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> <span style="background-color:#ffff00;">%&gt;</span>
<span style="background-color:#ffff00;">&lt;%</span></span><span style="color:#0000ff;">@</span><span style="color:#000000;"> </span><span style="color:#800000;">Import</span><span style="color:#000000;"> </span><span style="color:#ff0000;">Namespace</span><span style="color:#0000ff;">="System.Threading"</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> <span style="background-color:#ffff00;">%&gt;</span></span></span></span></pre>
<pre style="margin:0;"><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;"><span style="background-color:#ffff00;">
</span></span></span></span></pre>
<pre style="margin:0;"><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;"><span style="background-color:#ffff00;">&lt;%</span></span><span style="color:#0000ff;">=</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> Html.DropDownListFor(dateTime =&gt; dateTime.Month, </span><span style="color:#2b91af;">Enumerable</span><span style="color:#000000;">.Range(1, 12).Select(i =&gt; </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">SelectListItem</span></span><span style="font-family:Consolas;"><span style="color:#000000;">                          
{                              
  Value = i.ToString(),                              
  Text = </span><span style="color:#2b91af;">Thread</span></span><span style="color:#000000;font-family:Consolas;">.CurrentThread.CurrentUICulture.DateTimeFormat.GetMonthName(i),                             
  Selected = (i == Model.Month &amp;&amp; Model != </span><span style="color:#2b91af;font-family:Consolas;">DateTime</span></span><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;">.MinValue &amp;&amp; Model != </span><span style="color:#2b91af;">DateTime</span></span><span style="font-family:Consolas;"><span style="color:#000000;">.MaxValue)                         
}),</span><span style="color:#a31515;">"-- Month --"</span></span><span style="font-family:Consolas;"><span style="color:#000000;">)<span style="background-color:#ffff00;">%&gt;</span><span style="background-color:#ffffff;"> </span> /</span></span></span></pre>
<pre style="margin:0;"><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;">
<span style="background-color:#ffff00;">&lt;%</span></span><span style="color:#0000ff;">=</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> Html.DropDownListFor(dateTime =&gt; dateTime.Day, </span><span style="color:#2b91af;">Enumerable</span><span style="color:#000000;">.Range(1, 31).Select(i =&gt; </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">SelectListItem</span></span><span style="font-family:Consolas;"><span style="color:#000000;">                          
{                              
  Value = i.ToString(),                              
  Text = i.ToString(),                             
  Selected = (i == Model.Day &amp;&amp; Model != </span><span style="color:#2b91af;">DateTime</span><span style="color:#000000;">.MinValue &amp;&amp; Model != </span><span style="color:#2b91af;">DateTime</span></span><span style="font-family:Consolas;"><span style="color:#000000;">.MaxValue)                         
}), </span><span style="color:#a31515;">"-- Day --"</span></span><span style="font-family:Consolas;"><span style="color:#000000;">)<span style="background-color:#ffff00;">%&gt;</span> /</span></span></span></pre>
<pre style="margin:0;"><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;">
<span style="background-color:#ffff00;">&lt;%</span></span><span style="color:#0000ff;">=</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> Html.DropDownListFor(dateTime =&gt; dateTime.Year, </span><span style="color:#2b91af;">Enumerable</span><span style="color:#000000;">.Range(</span><span style="color:#2b91af;">DateTime</span><span style="color:#000000;">.Now.Year-110, 110).Select(i =&gt; </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">SelectListItem</span></span><span style="font-family:Consolas;"><span style="color:#000000;">                           
{                                                             
  Value = i.ToString(),                               
  Text = i.ToString(),                              
  Selected = (i == Model.Year &amp;&amp; Model != </span><span style="color:#2b91af;">DateTime</span><span style="color:#000000;">.MinValue &amp;&amp; Model != </span><span style="color:#2b91af;">DateTime</span></span><span style="font-family:Consolas;"><span style="color:#000000;">.MaxValue)                          
}), </span><span style="color:#a31515;">"-- Year --"</span></span><span style="font-family:Consolas;"><span style="color:#000000;">)<span style="background-color:#ffff00;">%&gt;</span></span></span></span></pre>
<pre style="margin:0;"><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;"><span style="background-color:#ffff00;">
</span></span></span></span></pre>
<pre style="margin:0;"><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;"><span style="background-color:#ffff00;">&lt;%</span></span><span style="color:#0000ff;">=</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> Html.HiddenFor(dateTime =&gt; dateTime.Hour)<span style="background-color:#ffff00;">%&gt;</span>
<span style="background-color:#ffff00;">&lt;%</span></span><span style="color:#0000ff;">=</span></span></span><span style="font-family:Consolas;"><span style="font-size:10pt;"><span style="color:#000000;"> Html.HiddenFor(dateTime =&gt; dateTime.Minute)<span style="background-color:#ffff00;">%&gt;</span>
<span style="background-color:#ffff00;">&lt;%</span></span><span style="color:#0000ff;">=</span><span style="color:#000000;"> Html.HiddenFor(dateTime =&gt; dateTime.Second)</span></span><span style="font-size:10pt;background-color:#ffff00;color:#000000;">%&gt;</span></span></pre>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="font-size:10pt;background-color:#ffff00;color:#000000;">
</span></span></pre>
<p>That’s all!<br />
Note that in the template editor above, the Hour, Minute and Second parts are rendered as HTML hidden fileds, because the Scott’s <em>DateTimeModelBinder</em> configured in the Global.asax expects a value for all the six parts of the splitted DateTime structure. It’s just a clean workaround to make the Scott’s model binder work without any change to the original code. In a real implementation hidden fields should be not required ;).</p>
<p>Now, what about validation? Well, both client-side and server-side validations are quite trivial: the server-side validation can be obtained through a custom <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx">ValidationAttribute</a><em> </em>that checks if the DateTime value is correct <em>(e.g.</em> the value should be not equal to <em>DateTime.MinValue</em> or <em>DateTime.MaxValue).</em></p>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="color:#000000;"><span style="font-size:10pt;">[</span></span><span style="font-size:10pt;"><span style="color:#2b91af;">AttributeUsage</span><span style="color:#000000;">(</span><span style="color:#2b91af;">AttributeTargets</span><span style="color:#000000;">.Field | </span><span style="color:#2b91af;">AttributeTargets</span><span style="color:#000000;">.Property, AllowMultiple = </span><span style="color:#0000ff;">false</span><span style="color:#000000;">, Inherited = </span><span style="color:#0000ff;">true</span></span></span><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;">)]
</span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">sealed</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> </span><span style="color:#2b91af;">DateRequiredAttribute</span><span style="color:#000000;"> : </span><span style="color:#2b91af;">ValidationAttribute</span>
</span><span style="font-family:Consolas;"><span style="color:#000000;">{       
</span><span style="color:#0000ff;">   public</span><span style="color:#000000;"> DateRequiredAttribute() : </span><span style="color:#0000ff;">base</span></span><span style="font-family:Consolas;"><span style="color:#000000;">() { }
</span><span style="color:#0000ff;">
   public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">override</span><span style="color:#000000;"> </span><span style="color:#0000ff;">string</span><span style="color:#000000;"> FormatErrorMessage(</span><span style="color:#0000ff;">string</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> name)
   {
     </span><span style="color:#0000ff;">return</span><span style="color:#000000;"> </span><span style="color:#0000ff;">string</span><span style="color:#000000;">.Format(</span><span style="color:#2b91af;">CultureInfo</span></span><span style="font-family:Consolas;"><span style="color:#000000;">.CurrentUICulture, ErrorMessageString, name);
   }
  </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">override</span><span style="color:#000000;"> </span><span style="color:#0000ff;">bool</span><span style="color:#000000;"> IsValid(</span><span style="color:#0000ff;">object</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> value)
   {
</span><span style="color:#2b91af;">     DateTime</span><span style="color:#000000;"> dateTime = (</span><span style="color:#2b91af;">DateTime</span></span><span style="font-family:Consolas;"><span style="color:#000000;">)value;
     </span><span style="color:#0000ff;">return</span><span style="color:#000000;"> (dateTime != </span></span></span><span style="font-size:10pt;"><span style="color:#2b91af;font-family:Consolas;">DateTime</span></span><span style="font-family:Consolas;"><span style="font-size:10pt;"><span style="color:#000000;">.MinValue &amp;&amp; dateTime != </span><span style="color:#2b91af;">DateTime</span><span style="color:#000000;">.MaxValue);           
   }
}</span></span></span></pre>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="font-size:10pt;"><span style="color:#000000;">
</span></span></span></pre>
<p>The corresponding client-side validation adapter can be implemented by deriving the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.dataannotationsmodelvalidator(VS.98).aspx">DataAnnotationsModelValidator</a> class. It allows us to specify a remote validation rule from the client. In this scenario, the part of the DateTime structure that could be validated is the Date part.<br />
So, we can create a <em>SplittedDateRequiredValidator </em>in order to check if each drop-down is holding a valid value. To accomplish this requirement, a simple solution is to make the client-side validator aware of the IDs of the &lt;<em>select&gt;</em> elements holding the DateTime’s Month, Day and Year values.</p>
<pre style="margin:0;"><span style="color:#0000ff;font-family:Consolas;"><span style="font-size:10pt;">public</span></span><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;"> </span><span style="color:#0000ff;">sealed</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> </span><span style="color:#2b91af;">SplittedDateRequiredValidator</span><span style="color:#000000;"> : </span><span style="color:#2b91af;">DataAnnotationsModelValidator</span><span style="color:#000000;">&lt;</span><span style="color:#2b91af;">DateRequiredAttribute</span></span><span style="font-family:Consolas;"><span style="color:#000000;">&gt;
{
</span><span style="color:#0000ff;">   private</span><span style="color:#000000;"> </span><span style="color:#0000ff;">string</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> _message;
   </span><span style="color:#0000ff;">private</span><span style="color:#000000;"> </span><span style="color:#0000ff;">string</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> _dayField;
   </span><span style="color:#0000ff;">private</span><span style="color:#000000;"> </span><span style="color:#0000ff;">string</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> _monthField;
   </span><span style="color:#0000ff;">private</span><span style="color:#000000;"> </span><span style="color:#0000ff;">string</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> _yearField;</span></span></span><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;">

</span></span></span></pre>
<pre style="margin:0;"><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;">   </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> SplittedDateRequiredValidator(</span><span style="color:#2b91af;">ModelMetadata</span><span style="color:#000000;"> metadata, </span><span style="color:#2b91af;">ControllerContext</span><span style="color:#000000;"> context, </span><span style="color:#2b91af;">DateRequiredAttribute</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> attribute)
                                        : </span><span style="color:#0000ff;">base</span></span><span style="font-family:Consolas;"><span style="color:#000000;">(metadata, context, attribute)
   {
      _message = attribute.ErrorMessage;
       _dayField = metadata.PropertyName + </span><span style="color:#a31515;">"_Day"</span></span><span style="font-family:Consolas;"><span style="color:#000000;">;
       _monthField = metadata.PropertyName + </span><span style="color:#a31515;">"_Month"</span></span><span style="font-family:Consolas;"><span style="color:#000000;">;
       _yearField = metadata.PropertyName + </span><span style="color:#a31515;">"_Year"</span></span><span style="font-family:Consolas;"><span style="color:#000000;">;           
   }

   </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">override</span><span style="color:#000000;"> </span><span style="color:#2b91af;">IEnumerable</span><span style="color:#000000;">&lt;</span><span style="color:#2b91af;">ModelClientValidationRule</span></span><span style="font-family:Consolas;"><span style="color:#000000;">&gt; GetClientValidationRules()
   {
      </span><span style="color:#2b91af;">ModelClientValidationRule</span><span style="color:#000000;"> rule = </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">ModelClientValidationRule
      </span></span><span style="font-family:Consolas;"><span style="color:#000000;">{
         ErrorMessage = _message,
         ValidationType = </span><span style="color:#a31515;">"splittedDateRequiredValidator"</span></span><span style="font-family:Consolas;"><span style="color:#000000;">               
      };

      rule.ValidationParameters.Add(</span><span style="color:#a31515;">"dayFieldId"</span></span><span style="font-family:Consolas;"><span style="color:#000000;">, _dayField);
      rule.ValidationParameters.Add(</span><span style="color:#a31515;">"monthFieldId"</span></span><span style="font-family:Consolas;"><span style="color:#000000;">, _monthField);
      rule.ValidationParameters.Add(</span><span style="color:#a31515;">"yearFieldId"</span></span></span><span style="font-family:Consolas;"><span style="font-size:10pt;"><span style="color:#000000;">, _yearField);

      </span><span style="color:#0000ff;">return</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;">[] { rule };
   }
}</span></span></span></pre>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="font-size:10pt;"><span style="color:#000000;">
</span></span></span></pre>
<p>Before looking at javascript validator code, let’s register the <em>SplittedDateRequiredValidator</em> as the client-side validation adapter for all model properties decorated with the <em>DateRequiredAttribute</em>. To accomplish that, we have to put the following line of code in the Global.asax…</p>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="color:#2b91af;"><span style="font-size:10pt;">DataAnnotationsModelValidatorProvider</span></span><span style="font-size:10pt;"><span style="color:#000000;">.RegisterAdapter(</span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(</span><span style="color:#2b91af;">DateRequiredAttribute</span><span style="color:#000000;">), </span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(</span><span style="color:#2b91af;">SplittedDateRequiredValidator</span><span style="color:#000000;">));</span></span></span></pre>
<p>&nbsp;</p>
<p>Finally, the client-side validator will evaluate the selected index of the drop-down lists in order to ensure that the user has selected a valid date (note that the <em>isValidDate</em> function simply checks if the users has specified an existing date).</p>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="color:#000000;"><span style="font-size:10pt;">Sys.Mvc.ValidatorRegistry.validators.splittedDateRequiredValidator = </span></span><span style="font-size:10pt;"><span style="color:#0000ff;">function</span></span></span><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;"> (rule) {        
</span><span style="color:#0000ff;">  var</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> dayFieldId = rule.ValidationParameters.dayFieldId;    
</span><span style="color:#0000ff;">  var</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> monthFieldId = rule.ValidationParameters.monthFieldId;    
</span><span style="color:#0000ff;">  var</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> yearFieldId = rule.ValidationParameters.yearFieldId;    
</span><span style="color:#0000ff;">  return</span><span style="color:#000000;"> </span><span style="color:#0000ff;">function</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> (value, context) {                
</span><span style="color:#0000ff;">    var</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> dayIdx = $get(dayFieldId).selectedIndex;        
</span><span style="color:#0000ff;">    var</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> monthIdx = $get(monthFieldId).selectedIndex;        
</span><span style="color:#0000ff;">    var</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> yearIdx = $get(yearFieldId).selectedIndex;        
</span><span style="color:#0000ff;">    if</span><span style="color:#000000;"> (dayIdx === 0 || monthIdx === 0 || yearIdx === 0) </span><span style="color:#0000ff;">return</span><span style="color:#000000;"> </span><span style="color:#0000ff;">false</span></span><span style="font-family:Consolas;"><span style="color:#000000;">;        
</span><span style="color:#0000ff;">    else</span><span style="color:#000000;"> </span><span style="color:#0000ff;">return</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> isValidDate(parseInt($get(yearFieldId).value), monthIdx, dayIdx);     </span></span></span></pre>
<pre style="margin:0;"><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;">  }</span></span></span><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;">;
</span></span></span><span style="font-family:Consolas;line-height:19px;white-space:normal;font-size:13px;">};</span></pre>
<p><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;"><br />
</span><span style="color:#0000ff;">function</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> isValidDate(y, m, d) {<br />
</span><span style="color:#0000ff;"> var</span><span style="color:#000000;"> date = </span><span style="color:#0000ff;">new</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> Date(y, m &#8211; 1, d);<br />
</span><span style="color:#0000ff;"> var</span><span style="color:#000000;"> convertedDate = </span><span style="color:#800000;">&#8220;&#8221;</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> + date.getFullYear() + (date.getMonth() + 1) + date.getDate();<br />
</span><span style="color:#0000ff;"> var</span><span style="color:#000000;"> givenDate = </span><span style="color:#800000;">&#8220;&#8221;</span></span></span><span style="font-family:Consolas;"><span style="font-size:10pt;"><span style="color:#000000;"> + y + m + d;<br />
</span><span style="color:#0000ff;"> return</span><span style="color:#000000;"> (givenDate == convertedDate);<br />
}<br />
</span></span></span></p>
<p>Ok let’s put everything together!<br />
Assuming that our model defines a property ”BirthDate” like this…</p>
<p><span style="font-family:Consolas;"><span style="color:#000000;"><span style="font-size:10pt;">[</span></span><span style="font-size:10pt;"><span style="color:#2b91af;">DateRequired</span><span style="color:#000000;">(ErrorMessage = </span><span style="color:#a31515;">&#8220;Invalid date. Please specify valid values!&#8221;</span></span></span><span style="font-size:10pt;"><span style="color:#000000;font-family:Consolas;">)]<br />
</span></span><span style="font-size:10pt;"><span style="font-family:Consolas;"><span style="color:#000000;">[</span><span style="color:#2b91af;">DataType</span><span style="color:#000000;">(</span><span style="color:#2b91af;">DataType</span></span><span style="font-family:Consolas;"><span style="color:#000000;">.Date)]<br />
[</span><span style="color:#2b91af;">DisplayName</span><span style="color:#000000;">(</span><span style="color:#a31515;">&#8220;Birthdate&#8221;</span></span></span><span style="font-family:Consolas;"><span style="font-size:10pt;"><span style="color:#000000;">)]<br />
</span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#2b91af;">DateTime</span><span style="color:#000000;"> BirthDate { </span><span style="color:#0000ff;">get</span><span style="color:#000000;">; </span><span style="color:#0000ff;">set</span><span style="color:#000000;">; }</span></span></span></p>
<p>… if we put the following code in our View…</p>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="color:#000000;"><span style="background-color:#ffff00;"><span style="font-size:10pt;">&lt;%</span></span><span style="font-size:10pt;"> Html.EnableClientValidation(); </span><span style="font-size:10pt;background-color:#ffff00;">%&gt;</span></span></span></pre>
<p>&#8230;<br />
<span style="font-family:Consolas;"><span style="background-color:#ffff00;color:#000000;"><span style="font-size:10pt;">&lt;%</span></span><span style="font-size:10pt;"><span style="color:#0000ff;">=</span></span></span><span style="font-family:Consolas;"><span style="font-size:10pt;"><span style="color:#000000;"> Html.EditorFor(m =&gt; m.BirthDate, </span><span style="color:#a31515;">&#8220;Date&#8221;</span><span style="color:#000000;">) <span style="background-color:#ffff00;">%&gt;</span></span><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">br</span><span style="color:#000000;"> </span><span style="color:#0000ff;">/&gt;</span><br />
<span style="color:#000000;"><span style="background-color:#ffff00;">&lt;%</span></span><span style="color:#0000ff;">=</span><span style="color:#000000;"> Html.ValidationMessageFor(m =&gt; m.BirthDate) </span></span><span style="font-size:10pt;background-color:#ffff00;color:#000000;">%&gt;</span></span></p>
<p>…the output would be, for example, the following…</p>
<p><img style="margin:5px;" src="https://i0.wp.com/img140.imageshack.us/img140/9660/immagineguc.jpg" alt="" /></p>
<p>HTH</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2010/12/26/asp-net-mvc-2-splitting-datetime-in-drop-down-lists-and-model-binding/feed/</wfw:commentRss>
			<slash:comments>11</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>

		<media:content url="http://img269.imageshack.us/img269/9956/immaginewv.jpg" medium="image" />

		<media:content url="http://img547.imageshack.us/img547/5513/immagine1fj.jpg" medium="image" />

		<media:content url="http://img140.imageshack.us/img140/9660/immagineguc.jpg" medium="image" />
	</item>
		<item>
		<title>[WPF] Binding multiple command parameters using MultiBinding</title>
		<link>https://dariosantarelli.wordpress.com/2010/11/07/wpf-binding-multiple-command-parameters-using-multibinding/</link>
					<comments>https://dariosantarelli.wordpress.com/2010/11/07/wpf-binding-multiple-command-parameters-using-multibinding/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sun, 07 Nov 2010 13:59:51 +0000</pubDate>
				<category><![CDATA[WPF]]></category>
		<category><![CDATA[Binding]]></category>
		<category><![CDATA[IMultiValueConverter]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/2010/11/07/wpf-binding-multiple-command-parameters-using-multibinding/</guid>

					<description><![CDATA[In this post, I’d like to show how we can pass multiple values into an ICommand implementation by using the CommandParameter property of an input control. This is useful especially in MVVM architectures, so that the View can interact with the ViewModel in a clean way, facing the fact that the Execute method of the [&#8230;]]]></description>
										<content:encoded><![CDATA[<div>In this post, I’d like to show how we can pass multiple values into an ICommand implementation by using the <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommandsource.commandparameter.aspx">CommandParameter</a> property of an input control. This is useful especially in MVVM architectures, so that the View can interact with the ViewModel in a clean way, facing the fact that the Execute method of the ICommand interface allows only a single object.<br />
A solution is to use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.multibinding.aspx">MultiBinding</a> class which allows us to define a collection of <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.binding.aspx">Binding</a> objects attached to the target <em>CommandParameter</em> property of our input control. In a concrete example, let’s consider a simple search box with an OK button and a checkbox &#8220;ignore case&#8221;. The OK button is bound to a custom FindCommand defined in the ViewModel.</div>
<div>
<div>When the user clicks on the OK button, we want two parameters to be passed to the command: the string to be searched and the “ignorecase” option. How can we bind these two parameters to the Button’s CommandParameter?<br />
Well, first we have to create a class to hold the parameters.</div>
<pre style="margin:0;"><span style="color:#0000ff;font-family:Consolas;">
</span></pre>
<pre style="margin:0;"><span style="color:#0000ff;font-family:Consolas;">public</span><span style="font-family:Consolas;"><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> </span><span style="color:#2b91af;">FindCommandParameters
</span></span><span style="font-family:Consolas;"><span style="color:#000000;">{</span><span style="color:#0000ff;">
  public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">string</span><span style="color:#000000;"> Text { </span><span style="color:#0000ff;">get</span><span style="color:#000000;">; </span><span style="color:#0000ff;">set</span></span><span style="font-family:Consolas;"><span style="color:#000000;">; }</span><span style="color:#0000ff;">
  public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">bool</span><span style="color:#000000;"> IgnoreCase { </span><span style="color:#0000ff;">get</span><span style="color:#000000;">; </span><span style="color:#0000ff;">set</span><span style="color:#000000;">; }
}</span></span></pre>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="color:#000000;">
</span></span></pre>
<div>After that, we have to create a class that implements the <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.imultivalueconverter.aspx">IMultiValueConverter</a> interface. This simply converts our multiple parameters into the class that we have defined before.</div>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="color:#0000ff;">
public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> </span><span style="color:#2b91af;">FindCommandParametersConverter</span><span style="color:#000000;"> : </span><span style="color:#2b91af;">IMultiValueConverter</span></span><span style="font-family:Consolas;"><span style="color:#000000;">
{ </span><span style="color:#0000ff;">
  public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">object</span><span style="color:#000000;"> Convert(</span><span style="color:#0000ff;">object</span><span style="color:#000000;">[] values, </span><span style="color:#2b91af;">Type</span><span style="color:#000000;"> targetType, </span><span style="color:#0000ff;">object</span><span style="color:#000000;"> parameter, System.Globalization.</span><span style="color:#2b91af;">CultureInfo</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> culture)
  {</span><span style="color:#2b91af;">
    FindCommandParameters</span><span style="color:#000000;"> parameters = </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">FindCommandParameters</span></span><span style="font-family:Consolas;"><span style="color:#000000;">(); </span><span style="color:#0000ff;">
    foreach</span><span style="color:#000000;"> (</span><span style="color:#0000ff;">var</span><span style="color:#000000;"> obj </span><span style="color:#0000ff;">in</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> values)
    { </span><span style="color:#0000ff;">
       if</span><span style="color:#000000;"> (obj </span><span style="color:#0000ff;">is</span><span style="color:#000000;"> </span><span style="color:#0000ff;">string</span><span style="color:#000000;">) parameters.Text = (</span><span style="color:#0000ff;">string</span></span><span style="font-family:Consolas;"><span style="color:#000000;">)obj;                </span><span style="color:#0000ff;">
       else if</span><span style="color:#000000;"> (obj </span><span style="color:#0000ff;">is</span><span style="color:#000000;"> </span><span style="color:#0000ff;">bool</span><span style="color:#000000;">) parameters.IgnoreCase = (</span><span style="color:#0000ff;">bool</span></span><span style="font-family:Consolas;"><span style="color:#000000;">)obj;
    } </span><span style="color:#0000ff;">
    return</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> parameters;
  }
</span><span style="color:#0000ff;">  public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">object</span><span style="color:#000000;">[] ConvertBack(</span><span style="color:#0000ff;">object</span><span style="color:#000000;"> value, </span><span style="color:#2b91af;">Type</span><span style="color:#000000;">[] targetTypes, </span><span style="color:#0000ff;">object</span><span style="color:#000000;"> parameter, System.Globalization.</span><span style="color:#2b91af;">CultureInfo</span></span><span style="font-family:Consolas;"><span style="color:#000000;"> culture)
  {</span><span style="color:#0000ff;">
    throw</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> </span><span style="color:#2b91af;">NotImplementedException</span><span style="color:#000000;">();
  }
}
</span></span></pre>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="color:#000000;">
</span></span></pre>
<div>As you can see in the code above, we can iterate through the list of input values of the <em>Convert</em> method, checking their type, and then correctly assign the properties of the parameter class. Obviously you can implement different solutions (you always know the order of the parameters set in the XAML), but the most important thing at this point is that the return value of the <em>Convert</em> method is what will be passed as argument to the <em>Execute</em> method of our FindCommand.</div>
<div>To wire up the XAML to take advantage of this class, we have to include the <em>&lt;Button.CommandParameter&gt;</em> element.  This contains the <em>&lt;MultiBinding&gt;</em> element, which has the “Converter” attribute. In the code below, the converter type is added as a resource to the button to make this post easier to read, but convention usually dictates resources are added at the Window level to allow reuse and readability.<br />
Under the <em>MultiBinding.Bindings</em> element, we add a <em>&lt;Binding&gt;</em> element for each parameter that we need to pass into the command.</div>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="color:#0000ff;">
</span></span></pre>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="color:#0000ff;">&lt;</span><span style="color:#a31515;">TextBox</span><span style="color:#ff0000;"> x</span><span style="color:#0000ff;">:</span><span style="color:#ff0000;">Name</span><span style="color:#0000ff;">="txtFind"</span><span style="color:#0000ff;"> /&gt;</span></span></pre>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="font-size:x-small;"><span style="line-height:13pt;white-space:normal;" lang="EN-US"><span style="color:#0000ff;">&lt;</span></span><span style="line-height:13pt;white-space:normal;" lang="EN-US"><span style="color:#a31515;">CheckBox</span></span><span style="line-height:13pt;white-space:normal;" lang="EN-US"><span style="color:#ff0000;"> x</span></span><span style="line-height:13pt;white-space:normal;" lang="EN-US"><span style="color:#0000ff;">:</span></span><span style="line-height:13pt;white-space:normal;" lang="EN-US"><span style="color:#ff0000;">Name</span></span><span style="line-height:13pt;white-space:normal;" lang="EN-US"><span style="color:#0000ff;">="chkFindIgnoreCase"</span></span><span style="line-height:13pt;white-space:normal;" lang="EN-US"><span style="color:#ff0000;"> Content</span></span><span style="line-height:13pt;white-space:normal;" lang="EN-US"><span style="color:#0000ff;">="Ignore case" /&gt;</span></span></span></span></pre>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="font-size:x-small;"><span style="line-height:13pt;white-space:normal;" lang="EN-US"><span style="color:#0000ff;"> </span></span></span></span><span style="font-family:Consolas;"><span style="color:#0000ff;">&lt;</span><span style="color:#a31515;">Button</span><span style="color:#ff0000;"> Command</span><span style="color:#0000ff;">="{</span><span style="color:#a31515;">Binding</span><span style="color:#ff0000;"> </span><span style="color:#0000ff;">FindCommand}"</span><span style="color:#ff0000;"> Content</span><span style="color:#0000ff;">="OK"&gt;</span><span style="color:#0000ff;">
  &lt;</span><span style="color:#a31515;">Button.Resources</span><span style="color:#0000ff;">&gt;</span><span style="color:#0000ff;">
    &lt;</span><span style="color:#a31515;">ui</span><span style="color:#0000ff;">:</span><span style="color:#a31515;">FindCommandParametersConverter</span><span style="color:#ff0000;"> x</span><span style="color:#0000ff;">:</span><span style="color:#ff0000;">Key</span><span style="color:#0000ff;">="findCommandParametersConverter" /&gt;</span><span style="color:#0000ff;">
  &lt;/</span><span style="color:#a31515;">Button.Resources</span><span style="color:#0000ff;">&gt;</span><span style="color:#0000ff;">
  &lt;</span><span style="color:#a31515;">Button.CommandParameter</span><span style="color:#0000ff;">&gt;</span><span style="color:#0000ff;">
    &lt;</span><span style="color:#a31515;">MultiBinding</span><span style="color:#ff0000;"> Converter</span><span style="color:#0000ff;">="{</span><span style="color:#a31515;">StaticResource</span><span style="color:#ff0000;"> findCommandParametersConverter</span><span style="color:#0000ff;">}"&gt;</span><span style="color:#0000ff;">
      &lt;</span><span style="color:#a31515;">MultiBinding.Bindings</span><span style="color:#0000ff;">&gt;</span><span style="color:#0000ff;">
        &lt;</span><span style="color:#a31515;">Binding</span><span style="color:#ff0000;"> ElementName</span><span style="color:#0000ff;">="txtFind"</span><span style="color:#ff0000;"> Path</span><span style="color:#0000ff;">="Text" /&gt;</span><span style="color:#0000ff;">
        &lt;</span><span style="color:#a31515;">Binding</span><span style="color:#ff0000;"> ElementName</span><span style="color:#0000ff;">="chkFindIgnoreCase"</span><span style="color:#ff0000;"> Path</span><span style="color:#0000ff;">="IsChecked" /&gt;</span><span style="color:#0000ff;">
      &lt;/</span><span style="color:#a31515;">MultiBinding.Bindings</span><span style="color:#0000ff;">&gt;</span><span style="color:#0000ff;">
    &lt;/</span><span style="color:#a31515;">MultiBinding</span><span style="color:#0000ff;">&gt;</span><span style="color:#0000ff;">
  &lt;/</span><span style="color:#a31515;">Button.CommandParameter</span><span style="color:#0000ff;">&gt;
</span><span style="color:#0000ff;">&lt;/</span><span style="color:#a31515;">Button</span><span style="color:#0000ff;">&gt;</span></span></pre>
<pre style="margin:0;"><span style="font-family:Consolas;"><span style="color:#0000ff;">
</span></span></pre>
<div>
<div>The final step is to consume the <em>FindCommandParameters</em> object instance in our FindCommand’s <em>CanExecute</em> and <em>Execute</em> methods.</p>
</div>
</div>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2010/11/07/wpf-binding-multiple-command-parameters-using-multibinding/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>[C#] How to programmatically find a COM port by friendly name</title>
		<link>https://dariosantarelli.wordpress.com/2010/10/18/c-how-to-programmatically-find-a-com-port-by-friendly-name/</link>
					<comments>https://dariosantarelli.wordpress.com/2010/10/18/c-how-to-programmatically-find-a-com-port-by-friendly-name/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Mon, 18 Oct 2010 20:16:19 +0000</pubDate>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WMI]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/2010/10/18/c-how-to-programmatically-find-a-com-port-by-friendly-name/</guid>

					<description><![CDATA[When using the SerialPort.GetPortNames() method, you are querying the current computer for a list of valid serial port names. For example, you can use this method to determine whether “COM1” and “COM2” are valid serial ports in your computer. The port names are obtained from the system registry (if the registry contains stale or otherwise [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>When using the <em><a href="http://msdn.microsoft.com/en-US/library/system.io.ports.serialport.getportnames.aspx" target="_blank">SerialPort.GetPortNames()</a></em> method, you are querying the current computer for a list of valid serial port names. For example, you can use this method to determine whether “COM1” and “COM2” are valid serial ports in your computer. The port names are obtained from the system registry (if the registry contains stale or otherwise incorrect data then this method will return incorrect data). The limit of this approach is that you get just an array of port names (e.g. { “COM1”,”COM2” … }) and nothing else! If the com ports are physical, there’s no problem but what about virtual ports connected for example through an USB adapter? Well, you can determine if a port is valid but you don&#8217;t know exactly which COM number was assigned to your device. So you need more information! In the system Device Manager, you can see the COM port friendly name under the &quot;Ports (COM &amp; LPT)&quot; heading. This means that the right COM port number can be found by using <a href="http://msdn.microsoft.com/en-us/library/aa394582(VS.85).aspx" target="_blank">WMI</a> <img src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" />     <br />A solution to this need comes from <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=2cc30a64-ea15-4661-8da4-55bbc145c30e&amp;displaylang=en" target="_blank">WMI Code Creator tool</a> which allows you to generate VBScript, C#, and VB .NET code that uses WMI to complete a management task such as querying for management data, executing a method from a WMI class, or receiving event notifications using WMI.     <br />A suitable WMI query is “<em>SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0</em>”.     <br />Here is a code example showing how to enumerate the information of the COM ports currently available on your system (including the friendly name of course) by executing the query above.</p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><font face="Courier New"><span style="line-height:9pt;"><font color="#0000ff"><font>using</font></font></span><span style="line-height:9pt;"><font color="#000000"> System.Management;          </p>
<p></font></span></font><span lang="EN-US"><font face="Courier New"><font><span><font color="#0000ff">internal</font></span><font color="#000000"> </font><span><font color="#0000ff">class</font></span><font color="#000000"> </font></font><span><font color="#2b91af">ProcessConnection </font></span></font></span><span lang="EN-US"><font face="Courier New"><font color="#000000"><font>{           <br /></font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160; </font></font></span><font><span><font color="#0000ff">public</font></span><font color="#000000"> </font><span><font color="#0000ff">static</font></span><font color="#000000"> </font><span><font color="#2b91af">ConnectionOptions</font></span><font color="#000000"> ProcessConnectionOptions()</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160; </font></span><font>{</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#2b91af">ConnectionOptions</font></span><font color="#000000"> options = </font><span><font color="#0000ff">new</font></span><font color="#000000"> </font><span><font color="#2b91af">ConnectionOptions</font></span><font color="#000000">();</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160; </font></span><font>options.Impersonation = </font></font><font><span><font color="#2b91af">ImpersonationLevel</font></span><font color="#000000">.Impersonate;</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160; </font></span><font>options.Authentication = </font></font><font><span><font color="#2b91af">AuthenticationLevel</font></span><font color="#000000">.Default;</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160; </font></span><font>options.EnablePrivileges = </font></font><font><span><font color="#0000ff">true</font></span><font color="#000000">;</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#0000ff">return</font></span><font color="#000000"> options;</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160; </font></span><font>}</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000">&#160;</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160; </font></font></span><font><span><font color="#0000ff">public</font></span><font color="#000000"> </font><span><font color="#0000ff">static</font></span><font color="#000000"> </font><span><font color="#2b91af">ManagementScope</font></span><font color="#000000"> ConnectionScope(</font><span><font color="#0000ff">string</font></span><font color="#000000"> machineName, </font><span><font color="#2b91af">ConnectionOptions</font></span><font color="#000000"> options, </font><span><font color="#0000ff">string</font></span><font color="#000000"> path)</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160; </font></span><font>{</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#2b91af">ManagementScope</font></span><font color="#000000"> connectScope = </font><span><font color="#0000ff">new</font></span><font color="#000000"> </font><span><font color="#2b91af">ManagementScope</font></span><font color="#000000">();</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160; </font></span><font>connectScope.Path = </font></font><font><span><font color="#0000ff">new</font></span><font color="#000000"> </font><span><font color="#2b91af">ManagementPath</font></span><font color="#000000">(</font><span><font color="#a31515">@&quot;\\&quot;</font></span><font color="#000000"> + machineName + path);</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160; </font></span><font>connectScope.Options = options;</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160; </font></span><font>connectScope.Connect();</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#0000ff">return</font></span><font color="#000000"> connectScope;</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160; </font></span><font>}</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><font>}</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000">&#160;</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font><span><font color="#0000ff">public</font></span><font color="#000000"> </font><span><font color="#0000ff">class</font></span><font color="#000000"> </font></font><span><font color="#2b91af">COMPortInfo</font></span></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><font>{</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160; </font></font></span><font><span><font color="#0000ff">public</font></span><font color="#000000"> </font><span><font color="#0000ff">string</font></span><font color="#000000"> Name { </font><span><font color="#0000ff">get</font></span><font color="#000000">; </font><span><font color="#0000ff">set</font></span><font color="#000000">; }</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160; </font></font></span><font><span><font color="#0000ff">public</font></span><font color="#000000"> </font><span><font color="#0000ff">string</font></span><font color="#000000"> Description { </font><span><font color="#0000ff">get</font></span><font color="#000000">; </font><span><font color="#0000ff">set</font></span><font color="#000000">; }</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000">&#160;</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160; </font></font></span><font><span><font color="#0000ff">public</font></span><font color="#000000"> COMPortInfo() { }</font></font><span><font color="#000000">&#160;&#160;&#160;&#160;&#160; </font></span></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000">&#160;</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160; </font></font></span><font><span><font color="#0000ff">public</font></span><font color="#000000"> </font><span><font color="#0000ff">static</font></span><font color="#000000"> </font><span><font color="#2b91af">List</font></span><font color="#000000">&lt;</font><span><font color="#2b91af">COMPortInfo</font></span><font color="#000000">&gt; GetCOMPortsInfo()</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160; </font></span><font>{</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#2b91af">List</font></span><font color="#000000">&lt;</font><span><font color="#2b91af">COMPortInfo</font></span><font color="#000000">&gt; comPortInfoList = </font><span><font color="#0000ff">new</font></span><font color="#000000"> </font><span><font color="#2b91af">List</font></span><font color="#000000">&lt;</font><span><font color="#2b91af">COMPortInfo</font></span><font color="#000000">&gt;();</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000">&#160;</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#2b91af">ConnectionOptions</font></span><font color="#000000"> options = </font><span><font color="#2b91af">ProcessConnection</font></span><font color="#000000">.ProcessConnectionOptions();</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#2b91af">ManagementScope</font></span><font color="#000000"> connectionScope = </font><span><font color="#2b91af">ProcessConnection</font></span><font color="#000000">.ConnectionScope(</font><span><font color="#2b91af">Environment</font></span><font color="#000000">.MachineName, options, </font><span><font color="#a31515">@&quot;\root\CIMV2&quot;</font></span><font color="#000000">);</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000">&#160;</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#2b91af">ObjectQuery</font></span><font color="#000000"> objectQuery = </font><span><font color="#0000ff">new</font></span><font color="#000000"> </font><span><font color="#2b91af">ObjectQuery</font></span><font color="#000000">(</font><span><font color="#a31515">&quot;SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0&quot;</font></span><font color="#000000">);</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#2b91af">ManagementObjectSearcher</font></span><font color="#000000"> comPortSearcher = </font><span><font color="#0000ff">new</font></span><font color="#000000"> </font><span><font color="#2b91af">ManagementObjectSearcher</font></span><font color="#000000">(connectionScope, objectQuery);</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000">&#160;</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#0000ff">using</font></span><font color="#000000"> (comPortSearcher)</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160; </font></span><font>{</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#0000ff">string</font></span><font color="#000000"> caption = </font><span><font color="#0000ff">null</font></span><font color="#000000">;</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#0000ff">foreach</font></span><font color="#000000"> (</font><span><font color="#2b91af">ManagementObject</font></span><font color="#000000"> obj </font><span><font color="#0000ff">in</font></span><font color="#000000"> comPortSearcher.Get())</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>{</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span></font><font><span><font color="#0000ff">if</font></span><font color="#000000"> (obj != </font><span><font color="#0000ff">null</font></span><font color="#000000">)</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>{</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#0000ff">object</font></span><font color="#000000"> captionObj = obj[</font><span><font color="#a31515">&quot;Caption&quot;</font></span><font color="#000000">];</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#0000ff">if</font></span><font color="#000000"> (captionObj != </font><span><font color="#0000ff">null</font></span><font color="#000000">)</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>{</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>caption = captionObj.ToString();</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span></font><font><span><font color="#0000ff">if</font></span><font color="#000000"> (caption.Contains(</font><span><font color="#a31515">&quot;(COM&quot;</font></span><font color="#000000">))</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>{</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></font></span><font><span><font color="#2b91af">COMPortInfo</font></span><font color="#000000"> comPortInfo = </font><span><font color="#0000ff">new</font></span><font color="#000000"> </font><span><font color="#2b91af">COMPortInfo</font></span><font color="#000000">();</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>comPortInfo.Name = caption.Substring(caption.LastIndexOf(</font></font><font><span><font color="#a31515">&quot;(COM&quot;</font></span><font color="#000000">)).Replace(</font><span><font color="#a31515">&quot;(&quot;</font></span><font color="#000000">, </font><span><font color="#0000ff">string</font></span><font color="#000000">.Empty).Replace(</font><span><font color="#a31515">&quot;)&quot;</font></span><font color="#000000">,</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font><font color="#000000">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font><span><font color="#0000ff">string</font></span><font color="#000000">.Empty);</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><font face="Courier New"><font color="#000000"><span lang="EN-US"><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span></span><span><font>comPortInfo.Description = caption;</font></span></font></font></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>comPortInfoList.Add(comPortInfo);</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>}</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>}</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>}</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>}</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span><font face="Courier New"><font color="#000000"><span><font>&#160;&#160;&#160;&#160; </font></span><font>}</font></font></font></span><span><font face="Courier New"><font color="#000000">&#160;</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span><font face="Courier New"><span><font color="#000000"><font>&#160;&#160;&#160;&#160; </font></font></span></font></span><span><font face="Courier New"><font><span><font color="#0000ff">return</font></span><font color="#000000"> comPortInfoList;</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span><font face="Courier New"><font color="#000000"><span><font>&#160;&#160; </font></span><font>}            <br /></font></font></font></span><span><font face="Courier New"><font color="#000000"><font>}</font></font></font></span></p>
<p>Finally you can easily get the com port list in this way…</p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span><font face="Courier New"><font><span><font color="#0000ff">foreach</font></span><font color="#000000"> (</font><span><font color="#2b91af">COMPortInfo</font></span><font color="#000000"> comPort </font><span><font color="#0000ff">in</font></span><font color="#000000"> </font><span><font color="#2b91af">COMPortInfo</font></span><font color="#000000">.GetCOMPortsInfo())</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span><font face="Courier New"><font color="#000000"><font>{</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span><font face="Courier New"><font><span><font color="#2b91af"><font color="#000000">&#160; </font>Console</font></span><font color="#000000">.WriteLine(</font><span><font color="#0000ff">string</font></span><font color="#000000">.Format(</font><span><font color="#a31515">&quot;{0} &#8211; {1}&quot;</font></span><font color="#000000">, comPort.Name, comPort.Description));</font></font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span><font face="Courier New"><font color="#000000"><font>}</font></font></font></span></p>
<p>Other solutions?</p>
<ul>
<li>A first alternative is <a href="http://msdn.microsoft.com/en-us/library/cc185682(VS.85).aspx" target="_blank">SetupAPI</a>. You can find a complete example <a href="http://stackoverflow.com/questions/2937585/how-to-open-a-serial-port-by-friendly-name" target="_blank">here</a>. </li>
<li>Secondly, you can try to use <a href="http://support.microsoft.com/kb/311272" target="_blank">DevCon</a> (a Microsoft tool that allows &quot;device management&quot; from the command line): you could use the
<p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx" target="_blank">System.Diagnostics.Process</a> class to parse the standard output of the command line “<font face="Courier New">&gt;devcon find =ports”</font>.</p>
</li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2010/10/18/c-how-to-programmatically-find-a-com-port-by-friendly-name/feed/</wfw:commentRss>
			<slash:comments>36</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>[C#] Byte Array to Hex string</title>
		<link>https://dariosantarelli.wordpress.com/2010/10/16/c-byte-array-to-hex-string/</link>
					<comments>https://dariosantarelli.wordpress.com/2010/10/16/c-byte-array-to-hex-string/#respond</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sat, 16 Oct 2010 15:09:39 +0000</pubDate>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/2010/10/16/c-byte-array-to-hex-string/</guid>

					<description><![CDATA[There are a lot of ways of converting a byte array to the corresponding hexadecimal string. I usually adopt the BitConverter class in order to optimize the readibility of code, but starting from the .NET Framework 3.0 the same task can be obtained using a single line of code through extensions methods: [TestMethod] public void [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>There are a lot of ways of converting a byte array to the corresponding hexadecimal string. I usually adopt the <a href="http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx" target="_blank">BitConverter</a> class in order to optimize the readibility of code, but starting from the .NET Framework 3.0 the same task can be obtained using a single line of code through extensions methods:</p>
<p><span lang="EN-US"><font face="Courier New"><font color="#000000"><font>[</font></font><font><span><font color="#2b91af">TestMethod</font></span><font color="#000000">]            <br /></font></font></font></span><span lang="EN-US"><font face="Courier New"><font><span><font color="#0000ff">public</font></span><font color="#000000"> </font><span><font color="#0000ff">void</font></span><font color="#000000"> BitConverterVsStringConcatAndExtensionMethod()            <br /></font></font></font></span><span lang="EN-US"><font face="Courier New"><font color="#000000"><font>{            <br />&#160; </font></font></font></span><span lang="EN-US"><font face="Courier New"><font><span><font color="#0000ff">byte</font></span><font color="#000000">[] bytes = </font><span><font color="#0000ff">new</font></span><font color="#000000"> </font><span><font color="#0000ff">byte</font></span><font color="#000000">[] { 0x00,0xAA,0xB0,0xC8,0x99,0x11,0x01,0x02 &#8230; };            <br />&#160; </font></font></font></span><span lang="EN-US"><font face="Courier New"><font><span><font color="#0000ff">string</font></span><font color="#000000"> expectedResult = </font><span><font color="#a31515">&quot;00AAB0C899110102&#8230;&quot;</font></span><font color="#000000">;            <br />&#160; <br /><strong>&#160; </strong></font></font></font></span><span lang="EN-US"><font face="Courier New"><font><strong><span><font color="#0000ff">string</font></span><font color="#000000"> result1 = </font><span><font color="#2b91af">BitConverter</font></span><font color="#000000">.ToString(bytes).Replace(</font><span><font color="#a31515">&quot;-&quot;</font></span><font color="#000000">,</font><span><font color="#0000ff">string</font></span></strong><font color="#000000"><strong>.Empty);              <br />&#160; <br />&#160; </strong></font></font></font></span><span lang="EN-US"><font face="Courier New"><font><strong><span><font color="#0000ff">string</font></span><font color="#000000"> result2 = </font><span><font color="#0000ff">string</font></span><font color="#000000">.Concat(bytes.Select(b =&gt; b.ToString(</font><span><font color="#a31515">&quot;X2&quot;</font></span></strong><font color="#000000"><strong>)));              <br /></strong>            <br />&#160; </font></font></font></span><span lang="EN-US"><font face="Courier New"><font><span><font color="#2b91af">Assert</font></span><font color="#000000">.AreEqual(expectedResult, result1);            <br />&#160; </font></font></font></span><span lang="EN-US"><font face="Courier New"><font><span><font color="#2b91af">Assert</font></span><font color="#000000">.AreEqual(expectedResult, result2);            <br /></font></font></font></span><font face="Courier New"><font color="#000000"><span><font>}</font></span></font></font></p>
<p>OK no performance issue has been discussed. Aren’t you satisfied? Follow this <a href="http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/3928b8cb-3703-4672-8ccd-33718148d1e3/" target="_blank">thread</a> !!! (4 years of discussion :D)</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2010/10/16/c-byte-array-to-hex-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>[ASP.NET MVC 2] Handling timeouts in asynchronous controllers</title>
		<link>https://dariosantarelli.wordpress.com/2010/10/16/asp-net-mvc-2-handling-timeouts-in-asynchronous-controllers/</link>
					<comments>https://dariosantarelli.wordpress.com/2010/10/16/asp-net-mvc-2-handling-timeouts-in-asynchronous-controllers/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sat, 16 Oct 2010 13:41:45 +0000</pubDate>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/2010/10/16/asp-net-mvc-2-handling-timeouts-in-asynchronous-controllers/</guid>

					<description><![CDATA[An important feature of the ASP.NET MVC framework is the possibility of creating asynchronous controllers. As in Asynchronous Pages in ASP.NET 2.0, the aim is to avoid a “thread starvation” in your web application, preventing web clients to receive a bad 503 status code (Server too busy). In fact, when the Web Server receives a [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>An important feature of the ASP.NET MVC framework is the possibility of creating asynchronous controllers. As in <a href="http://msdn.microsoft.com/en-us/magazine/cc163725.aspx" target="_blank">Asynchronous Pages in ASP.NET 2.0</a>, the aim is to avoid a “thread starvation” in your web application, preventing web clients to receive a bad 503 status code (Server too busy). In fact, when the Web Server receives a request, a thread is taken from the application threadpool mantained by the .NET Framework. In a synchronous scenario, this thread lives (and can’t be reused) until all the operations complete. Well, asynchronous pipeline is better when the logic creates bottlenecks waiting for network-bound or I/O-bound operations. Considering that an asynchronous request takes the same amount of time to process as a synchronous request, minimizing the number of threads waiting for blocking operations is a good practice, particularly appreciated by your Web server when it’s bombarded by hundreds of concurrent requests. Now, have a look to this simple asynchronous controller:</p>
<p> <font face="Courier New">   </p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><font face="Courier New"><span style="font-family:courier new;" lang="EN-US"><font color="#0000ff"><font>public</font></font></span><span style="font-family:courier new;" lang="EN-US"><font> <span><font color="#0000ff">class</font></span> <span><font color="#2b91af">CustomersController</font></span> : </font><span><font color="#2b91af">AsyncController</font></span></span></font></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font>{</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160; </font></span></font></span><span lang="EN-US"><font face="Courier New"><font>[<span><font color="#2b91af">AsyncTimeout</font></span>(10000)]</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160; </font></span><font><span><font color="#0000ff">public</font></span> <span><font color="#0000ff">void</font></span> ListAsync()</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160; </font></span><font>{</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160; </font></span><font>AsyncManager.OutstandingOperations.Increment();</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160; </font></span><font><span><font color="#2b91af">Task</font></span>.Factory.StartNew(() =&gt;</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160; </font></span><font>{</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font><span><font color="#0000ff">try</font></span> { AsyncManager.Parameters[<span><font color="#a31515">&quot;result&quot;</font></span>] = <span><font color="#0000ff">new</font></span> <span><font color="#2b91af">MyServiceClient</font></span>().GetCustomers(); }</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font><span><font color="#0000ff">catch</font></span> (<span><font color="#2b91af">Exception</font></span> ex) { &#8230; }</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font><span><font color="#0000ff">finally</font></span> { AsyncManager.OutstandingOperations.Decrement(); }</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160; </font></span><font>);</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160; </font></span><font>}</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><font>&#160;</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160; </font></span><font><span><font color="#0000ff">public</font></span> <span><font color="#2b91af">ActionResult</font></span> ListCompleted(<span><font color="#2b91af">List</font></span>&lt;<span><font color="#2b91af">Customer</font></span>&gt; result)</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160; </font></span><font>{</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160; </font></span><font><span><font color="#0000ff">return</font></span> View(<span><font color="#a31515">&quot;List&quot;</font></span>, result);</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160; </font></span><font>}            </p>
<p>&#160;&#160; &#8230;</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><span><font face="Courier New"><font>&#160;&#160;&#160;&#160;&#160;&#160; </font></font></span></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160; </font></span><font><span><font color="#0000ff">protected</font></span> <span><font color="#0000ff">override</font></span> <span><font color="#0000ff">void</font></span> OnException(<span><font color="#2b91af">ExceptionContext</font></span> filterContext)</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160; </font></span><font>{</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160; </font></span><font><span><font color="#0000ff">if</font></span> (filterContext.Exception <span><font color="#0000ff">is</font></span> <span><font color="#2b91af">TimeoutException</font></span>)</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160; </font></span><font>{</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>filterContext.Result = RedirectToAction(<span><font color="#a31515">&quot;TryAgainLater&quot;</font></span>);</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160;&#160;&#160; </font></span><font>filterContext.ExceptionHandled = <span><font color="#0000ff">true</font></span>;</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160; </font></span><font>}</font><span><font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font></span></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160;&#160;&#160; </font></span><font><span><font color="#0000ff">base</font></span>.OnException(filterContext);</font></font></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><span lang="EN-US"><font face="Courier New"><span><font>&#160;&#160; </font></span><font>}</font></font></span><span lang="EN-US"><span><font face="Courier New"><font>&#160;&#160;&#160; </font></font></span></span></p>
<p style="line-height:normal;margin:0;" class="MsoNormal"><font face="Courier New"><span><font>}</font></span></font></p>
<p> </font>  </p>
<p>By default, ASP.NET MVC won’t call the <em>ListCompleted</em> method until the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.async.asyncmanager.aspx" target="_blank">AsyncManager</a> associated with the request says that there is no outstanding asynchronous operations. But it’s possible that one or more asynchronous operations might never complete!!! Moreover, if the callback for one of your asynchronous operations throws an exception before it calls the <em>AsyncManager.OutstandingOperations.Decrement() </em>method,<em> </em>the request will keep waiting a decrement until it times out! So, putting the <em>AsyncManager.OutstandingOperations.Decrement()</em> call inside a <em>finally</em> block would be fine :).    <br />The AsyncManager object has a built-in default timeout set to 45 seconds, so if the count of outstanding operations doesn’t reach zero after this long, the framework will throw a <em>System.TimeOutException</em> to abort the request. If you want to set a different timeout you can use the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.asynctimeoutattribute.aspx" target="_blank">AsyncTimeout</a> filter for specifying a different duration. If you want to allow asynchronous operations to run for an unlimited period, then use the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.noasynctimeoutattribute.aspx" target="_blank">NoAsyncTimeout</a> filter instead.</p>
<p>Finally, we have to say that most applications will have an ASP.NET global exception handler that will deal with timeout exceptions in the same way as other unhandled exceptions. But if you want to treat timeouts in a custom way, providing a different feedback to the user, you can create your own exception filter or you can override the controller’s <em><a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onexception.aspx" target="_blank">OnException()</a></em> method (e.g. to redirect users to a special “Try again later” page).</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2010/10/16/asp-net-mvc-2-handling-timeouts-in-asynchronous-controllers/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>Web Development Helper</title>
		<link>https://dariosantarelli.wordpress.com/2008/06/23/web-development-helper/</link>
					<comments>https://dariosantarelli.wordpress.com/2008/06/23/web-development-helper/#comments</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Mon, 23 Jun 2008 13:22:52 +0000</pubDate>
				<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/2008/06/23/web-development-helper/</guid>

					<description><![CDATA[Web Development Helper is a free browser extension for Internet Explorer that provides a set of tools and utilities for the Web developer, esp. Ajax and ASP.NET developers. The tool provides features such as a DOM inspector, an HTTP tracing tool, and script diagnostics and immediate window. Web Development Helper works against IE6+, and requires [&#8230;]]]></description>
										<content:encoded><![CDATA[<blockquote>
<p><a href="http://projects.nikhilk.net/WebDevHelper/Default.aspx" target="_blank"><strong>Web Development Helper</strong></a> is a free browser extension for Internet Explorer that provides a set of tools and utilities for the Web developer, esp. Ajax and ASP.NET developers. The tool provides features such as a <strong>DOM inspector</strong>, an <strong>HTTP tracing tool</strong>, and <strong>script diagnostics</strong> and <strong>immediate window</strong>. Web Development Helper works against <strong>IE6+</strong>, and <strong>requires the .NET Framework 2.0 or greater</strong> to be installed on the machine.</p>
</blockquote>
<p>Very cool <img src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2008/06/23/web-development-helper/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>Easyfrom Database Convert</title>
		<link>https://dariosantarelli.wordpress.com/2008/06/22/easyfrom-database-convert/</link>
					<comments>https://dariosantarelli.wordpress.com/2008/06/22/easyfrom-database-convert/#respond</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sun, 22 Jun 2008 18:10:04 +0000</pubDate>
				<category><![CDATA[Blogroll]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/2008/06/22/easyfrom-database-convert/</guid>

					<description><![CDATA[If you are migrating your database across different platforms or applications, then you know that it can not be done by simple copy-and-paste operations. To forget about difficulties associated with database conversion, you should try ESF Database Convert. This wizard-based tool addresses almost any database conversion need. Advanced converting mechanisms of the tool provide smooth [&#8230;]]]></description>
										<content:encoded><![CDATA[<blockquote>
<p>If you are <strong>migrating your database across different platforms or applications</strong>, then you know that it can not be done by simple copy-and-paste operations. To forget about difficulties associated with database conversion, you should try <strong><a href="http://www.easyfrom.net/" target="_blank">ESF Database Convert</a></strong>. This wizard-based tool addresses almost any database conversion need. Advanced converting mechanisms of the tool provide smooth conversion directly from/to any of the following database formats: <strong>Oracle, MySQL, SQL Server, PostgreSQL, Visual Foxpro, FireBird, InterBase, Access, Excel, Paradox, Lotus, dBase, Text and others(e.g.: Access to Oracle, Oracle to SQL Server, SQL Server to MySQL, MySQL to PostgreSQL&#8230;)</strong>. Also you can convert any format of a database with ODBC DSN. <br /><em>ESF Database Convert</em> includes the support of table CLOB/BLOB, Primary/Foreign Keys, Indexes, Auto-ID and maps table and field names/types in converting. It provides all the required conversion options, taking into account the peculiarities of both input and output database formats. You can convert data exactly the way you want it. <br />The tool comes with the batch conversion mode that can enhance productivity by speeding up the entire conversion process. Our users regularly convert multi-million records databases using our software.</p>
</blockquote>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2008/06/22/easyfrom-database-convert/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>
	</item>
		<item>
		<title>Programming languages history</title>
		<link>https://dariosantarelli.wordpress.com/2008/06/22/programming-languages-history/</link>
					<comments>https://dariosantarelli.wordpress.com/2008/06/22/programming-languages-history/#respond</comments>
		
		<dc:creator><![CDATA[dariosantarelli]]></dc:creator>
		<pubDate>Sun, 22 Jun 2008 17:55:39 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://dariosantarelli.wordpress.com/2008/06/22/programming-languages-history/</guid>

					<description><![CDATA[Here you can find an interesting diagram of programming languages history. Years go by, but surprisely you can see how apparently incompatible paths (OO and functional programming) are slowly fusing in time.&#160; For about 50 years, computer programmers have been writing code. New technologies continue to emerge, develop, and mature. Now there are more than [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a href="http://merd.sourceforge.net/pixel/language-study/diagram.html" target="_blank"><strong>Here</strong></a> you can find an interesting diagram of <strong>programming languages history</strong>. Years go by, but surprisely you can see how apparently incompatible paths (OO and functional programming) are slowly fusing in time.&nbsp; For about 50 years, computer programmers have been writing code. New technologies continue to emerge, develop, and mature. <strong>Now there are more than 2,500 documented programming languages!</strong> </p>
<p>Here a preview <img src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p><a href="http://people.mandriva.com/~prigaux/language-study/diagram.png"><img alt="diagram" src="https://i0.wp.com/people.mandriva.com/~prigaux/language-study/diagram-thumbnail.png"></a></p>
<p>Moreover, O&#8217;Reilly has produced a poster called <a href="http://www.oreilly.com/news/graphics/prog_lang_poster.pdf">History of Programming Languages</a>&nbsp; which plots over 50 programming languages on a multi-layered, color-coded timeline. </p>
]]></content:encoded>
					
					<wfw:commentRss>https://dariosantarelli.wordpress.com/2008/06/22/programming-languages-history/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://1.gravatar.com/avatar/4b726a2caa2dafe77a247b81c87e44b53257b500e14c779d85a60d9c4bb66ce2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dariosantarelli</media:title>
		</media:content>

		<media:content url="http://people.mandriva.com/~prigaux/language-study/diagram-thumbnail.png" medium="image">
			<media:title type="html">diagram</media:title>
		</media:content>
	</item>
	</channel>
</rss>
