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

<channel>
	<title>sharpreflections.net &#187; .Net Programming</title>
	<atom:link href="http://blog.sharpreflections.net/category/net-programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.sharpreflections.net</link>
	<description>Thoughts about .Net, programming and other more important stuffs.</description>
	<lastBuildDate>Fri, 20 Nov 2009 00:24:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Simple parallel programming</title>
		<link>http://blog.sharpreflections.net/2009/05/18/simple-parallel-programming/</link>
		<comments>http://blog.sharpreflections.net/2009/05/18/simple-parallel-programming/#comments</comments>
		<pubDate>Mon, 18 May 2009 22:59:40 +0000</pubDate>
		<dc:creator>matteosp</dc:creator>
				<category><![CDATA[.Net Programming]]></category>
		<category><![CDATA[ParallelProgramming]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[.Net;Threading;ParallelProgramming]]></category>

		<guid isPermaLink="false">http://blog.sharpreflections.net/?p=105</guid>
		<description><![CDATA[While waiting for Parallel Extensions (wikipedia), that will be shipped with next .Net Framework release, I designed a couple of class that allow to quickly (and easily!) write code that make use of multi-threading and, therefore, speed-up many tasks. What I show here is a simple class able to collect pieces of code (in form [...]]]></description>
			<content:encoded><![CDATA[<p>While waiting for <a title="Parallel Programming with .NET" href="http://blogs.msdn.com/pfxteam" target="_blank">Parallel Extensions</a> (<a title="Parallel Extensions" href="http://en.wikipedia.org/wiki/Parallel_FX_Library" target="_blank">wikipedia</a>), that will be shipped with next .Net Framework release, I designed a couple of class that allow to quickly (and easily!) write code that make use of multi-threading and, therefore, speed-up many tasks. What I show here is a simple class able to collect pieces of code (in form of delegate) to be executed concurrently, and parallelize and synchronize the execution. The main goals I kept in mind while realizing the solution were:</p>
<ul>
<li>Ease of use, minimal requirement in terms of multi-threading skills</li>
<li>Allowing single-threaded code to be ported to multi-threading with few changes</li>
<li>Code readability</li>
<li>Support for exception management</li>
</ul>
<p>Here what I came up with:</p>
<p>The API exposes one class, <span class="csharpcode">ParallelExecutor</span>, and one interface, <span class="csharpcode">IExecutionResult</span> (plus a generic specialization of the interface and the necessary implementations). Before seeing the internals of the solution, I want to show <strong>the ease of use of the API</strong>.<br />
Let&#8217;s start with this example:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">void</span> SerialExecution()</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>    Uri uri; <span class="kwrd">int</span> <span class="kwrd">value</span>;</pre>
<pre><span class="lnum">   4:  </span></pre>
<pre class="alt"><span class="lnum">   5:  </span>    CallWebService(uri);</pre>
<pre><span class="lnum">   6:  </span>    PerformComputation(<span class="kwrd">value</span>);</pre>
<pre class="alt"><span class="lnum">   7:  </span>}</pre>
</div>
<p><span class="csharpcode">CallWebService()</span> and <span class="csharpcode">PerformComputation()</span> represent the most classic example of methods that can (and should!) run in parallel as they perform respectively I/O and CPU computation. But usually programmers haven&#8217;t enough confidence with multi-threading execution and synchronization to do things in the right way. In any case they shouldn&#8217;t care about this stuff, they should focus on coding logic, and not on coding about how the logic get&#8217;s executed. Let&#8217;s see how <span class="csharpcode">ParallelExecutor</span> comes in help:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">void</span> ParallelExecution</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>  Uri uri; <span class="kwrd">int</span> <span class="kwrd">value</span>;</pre>
<pre><span class="lnum">   4:  </span></pre>
<pre class="alt"><span class="lnum">   5:  </span>  ParallelExecutor executor = <span class="kwrd">new</span> ParallelExecutor();</pre>
<pre><span class="lnum">   6:  </span></pre>
<pre class="alt"><span class="lnum">   7:  </span>  executor.Add(CallWebService, uri);</pre>
<pre><span class="lnum">   8:  </span>  executor.Add(PerformComputation, <span class="kwrd">value</span>);</pre>
<pre class="alt"><span class="lnum">   9:  </span></pre>
<pre><span class="lnum">  10:  </span>  executor.WaitAll();</pre>
<pre class="alt"><span class="lnum">  11:  </span>}</pre>
</div>
<p>Not too bad, right? With a couple of lines I got the two methods run concurrently. This is pretty simple: the Add() method takes as arguments the method to invoke and the arguments of that method. The WaitAll() causes the calling thread to wait for all the methods passed to Add() to complete. Take a (partial) look to the <span class="csharpcode">ParallelExecutor</span> definition:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> ParallelExecutor</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>  <span class="kwrd">public</span> IExecutionInfo&lt;<span class="kwrd">object</span>&gt; Add(Action workItem)</pre>
<pre><span class="lnum">   4:  </span>  <span class="kwrd">public</span> IExecutionInfo&lt;<span class="kwrd">object</span>&gt; Add&lt;T&gt;(Action&lt;T&gt; workItem, T arg)</pre>
<pre class="alt"><span class="lnum">   5:  </span>  <span class="rem">//overloads for other Action versions </span></pre>
<pre><span class="lnum">   6:  </span></pre>
<pre class="alt"><span class="lnum">   7:  </span>  <span class="kwrd">public</span> IExecutionInfo&lt;TResult&gt; Add&lt;TResult&gt;(Func&lt;TResult&gt; workItem)</pre>
<pre><span class="lnum">   8:  </span>  <span class="kwrd">public</span> IExecutionInfo&lt;TResult&gt; Add&lt;T, TResult&gt;(Func&lt;T, TResult&gt; workItem, T arg)</pre>
<pre class="alt"><span class="lnum">   9:  </span>  <span class="rem">//overloads for other Func versions </span></pre>
<pre><span class="lnum">  10:  </span></pre>
<pre class="alt"><span class="lnum">  11:  </span>  <span class="kwrd">public</span> <span class="kwrd">bool</span> WaitAll():</pre>
<pre><span class="lnum">  12:  </span>}</pre>
</div>
<p>As you can see, method to be parallelized are passed to Add() in form of variations of Action and Func generics delegate (there are also overloads that take <span class="csharpcode">MethodInfo</span> and the standard <span class="csharpcode">Delegate</span>). But what about the Add() return type, <span class="csharpcode">IExecutionResult</span>? Let&#8217;s see the interface declaration:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">interface</span> IExecutionInfo</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>  <span class="kwrd">object</span>[] Args { get; }</pre>
<pre><span class="lnum">   4:  </span></pre>
<pre class="alt"><span class="lnum">   5:  </span>  Exception Exception { get; }</pre>
<pre><span class="lnum">   6:  </span></pre>
<pre class="alt"><span class="lnum">   7:  </span>  <span class="kwrd">object</span> Result { get; }</pre>
<pre><span class="lnum">   8:  </span>}</pre>
<pre class="alt"><span class="lnum">   9:  </span></pre>
<pre><span class="lnum">  10:  </span><span class="kwrd">public</span> <span class="kwrd">interface</span> IExecutionInfo&lt;TResult&gt; : IExecutionInfo</pre>
<pre class="alt"><span class="lnum">  11:  </span>{</pre>
<pre><span class="lnum">  12:  </span>  TResult Result { get; }</pre>
<pre class="alt"><span class="lnum">  13:  </span>}</pre>
</div>
<p>At every invocation of the Add() method an instance of a class implementing <span class="csharpcode">IExecutionResult</span> is created, and its Args property is filled with method invocation arguments. After the invocation completes, the Result and Exception property are filled too (in both case, if any). <strong>And the magic of generics allow the code to be type safe</strong>. So, returning to the example, if CallWebService() has a return value and if you want to check for exceptions, you can write:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">void</span> ParallelExecution</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>  Uri uri; <span class="kwrd">int</span> <span class="kwrd">value</span>;</pre>
<pre><span class="lnum">   4:  </span></pre>
<pre class="alt"><span class="lnum">   5:  </span>  ParallelExecutor executor = <span class="kwrd">new</span> ParallelExecutor();</pre>
<pre><span class="lnum">   6:  </span></pre>
<pre class="alt"><span class="lnum">   7:  </span>  IExecutionInfo&lt;<span class="kwrd">int</span>&gt; execution = executor.Add&lt;Uri, <span class="kwrd">int</span>&gt;(CallWebService, uri);</pre>
<pre><span class="lnum">   8:  </span>  executor.Add(PerformComputation, <span class="kwrd">value</span>);</pre>
<pre class="alt"><span class="lnum">   9:  </span></pre>
<pre><span class="lnum">  10:  </span>  executor.WaitAll();</pre>
<pre class="alt"><span class="lnum">  11:  </span></pre>
<pre><span class="lnum">  12:  </span>  <span class="kwrd">if</span> (execution.Exception != <span class="kwrd">null</span>)</pre>
<pre class="alt"><span class="lnum">  13:  </span>      ManageException(execution.Exception);</pre>
<pre><span class="lnum">  14:  </span>  <span class="kwrd">else</span></pre>
<pre class="alt"><span class="lnum">  15:  </span>      Console.WriteLine(<span class="str">"Result: {0}"</span>, execution.Result);</pre>
<pre><span class="lnum">  16:  </span>}</pre>
</div>
<p>Another couple of properties exposed by <span class="csharpcode">ParallelExecutor</span> allow you to control when the execution starts (immediately after Add() or when WaitAll() gets called) and the aggressiveness of the threading policy (one new Thread for every method passed to Add() or threads got from ThreadPool).</p>
<p>Obviously this is a very simple implementation, far away from what Parallel Extensions will be. But its simplicity may suite well some implementation with no heavy requirements.</p>
<p><a title="Simple parallel programming (MSDN Code Gallery)" href="http://code.msdn.microsoft.com/SimpleParallelExt" target="_blank">Source Code</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sharpreflections.net/2009/05/18/simple-parallel-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamics CRM as development platform: transparent substitution of CrmService with Filtered Views.</title>
		<link>http://blog.sharpreflections.net/2007/04/06/dynamics-crm-as-development-platform-transparent-substitution-of-crmservice-with-filtered-views/</link>
		<comments>http://blog.sharpreflections.net/2007/04/06/dynamics-crm-as-development-platform-transparent-substitution-of-crmservice-with-filtered-views/#comments</comments>
		<pubDate>Fri, 06 Apr 2007 19:41:27 +0000</pubDate>
		<dc:creator>matteosp</dc:creator>
				<category><![CDATA[.Net Programming]]></category>
		<category><![CDATA[Microsoft CRM 3.0]]></category>
		<category><![CDATA[Sql Server]]></category>

		<guid isPermaLink="false">http://sharpreflections.wordpress.com/2007/04/06/dynamics-crm-as-development-platform-transparent-substitution-of-crmservice-with-filtered-views/</guid>
		<description><![CDATA[In my last post I suggested not to directly use, in your code, the CrmService proxy class. I quickly mentioned some enhancements you can gain from this, let&#8217;s focus on substituting web service calls with database access on filtered views. Even if limited to read operations, this can increase a lot the performances of your [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post I suggested not to directly use, in your code, the CrmService proxy class. I quickly mentioned some enhancements you can gain from this, let&#8217;s focus on <strong>substituting web service calls with database access on filtered views</strong>. Even if limited to read operations, this can increase a lot the performances of your system.</p>
<p>As we want the callers not to be aware of the way we retrieve data, we have to passing back data to them in the form they expect it: &#8220;BusinessEntity&#8221; derived classes or collection of them. This may seems hard, but it isn&#8217;t. You can build the statement in way that it will produce data in XML, in a format that can be directly deserialized in entity instances.</p>
<p>So, let&#8217;s view how we can:</p>
<ul>
<li>Compose the SQL statements in such a way the will produce the xml we need</li>
<li>Deserialize the data from xml to entities</li>
</ul>
<p>Take a look at this query:</p>
<pre><a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=WITH&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">WITH</a> XMLNAMESPACES
(
  '<span style="color:#8b0000;">http://www.w3.org/2001/XMLSchema</span>' <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> xsd
, '<span style="color:#8b0000;">http://www.w3.org/2001/XMLSchema-instance</span>' <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> xsi
, '<span style="color:#8b0000;">http://schemas.microsoft.com/crm/2006/WebServices</span>' <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> crm
)
<a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=SELECT&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">SELECT</a> name <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:name</span>'
     , accountid <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:accountid</span>'
     , donotphonename <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:donotphone/@name</span>'
     , donotphone <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:donotphone</span>'
     , address1_shippingmethodcodename <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:address1_shippingmethodcode/@name</span>'
     , address1_shippingmethodcode <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:address1_shippingmethodcode</span>'
     , modifiedbyname <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:modifiedby/@name</span>'
     , modifiedbydsc <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:modifiedby/@dsc</span>'
     , modifiedby <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:modifiedby</span>'
     , createdbyname <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:createdby/@name</span>'
     , createdbydsc <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:createdby/@dsc</span>'
     , createdby <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:createdby</span>'
     , statuscodename <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:statuscode/@name</span>'
     , statuscode <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:statuscode</span>'
     , statecodename <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:statecode/@formattedValue</span>'
     , statecode <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> '<span style="color:#8b0000;">crm:statecode</span>'
  <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=FROM&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">FROM</a> Filteredaccount
   <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=FOR&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">FOR</a> XML PATH ('<span style="color:#8b0000;">account</span>')</pre>
<p>The <strong>WITH XMLNAMESPACES</strong>, the field aliases and the <strong>FOR XML PATH</strong> do the magic, and we get data in this format:</p>
<pre><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">account</span> <span style="color:#ff0000;">xmlns</span>:<span style="color:#ff0000;">crm</span>=<span style="color:#0000ff;">"http://schemas.microsoft.com/crm/2006/WebServices"</span> <span style="color:#ff0000;">xmlns</span>:<span style="color:#ff0000;">xsi</span>=<span style="color:#0000ff;">"http://www.w3.org/2001/XMLSchema-instance"</span> <span style="color:#ff0000;">xmlns</span>:<span style="color:#ff0000;">xsd</span>=<span style="color:#0000ff;">"http://www.w3.org/2001/XMLSchema"</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">name</span><span style="color:#0000ff;">&gt;</span>Adventure Works Ltd.<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">name</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">accountid</span><span style="color:#0000ff;">&gt;</span>E85D1177-EE17-DB11-87E4-0000E2998A6B<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">accountid</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">modifiedby</span> <span style="color:#ff0000;">name</span>=<span style="color:#0000ff;">"CRM Administrator"</span> <span style="color:#ff0000;">dsc</span>=<span style="color:#0000ff;">"0"</span><span style="color:#0000ff;">&gt;</span>89A611D4-C7BD-DB11-A4E3-005056A80A71<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">modifiedby</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">createdby</span> <span style="color:#ff0000;">name</span>=<span style="color:#0000ff;">"CRM Administrator"</span> <span style="color:#ff0000;">dsc</span>=<span style="color:#0000ff;">"0"</span><span style="color:#0000ff;">&gt;</span>89A611D4-C7BD-DB11-A4E3-005056A80A71<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">createdby</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">statuscode</span> <span style="color:#ff0000;">name</span>=<span style="color:#0000ff;">"Active"</span><span style="color:#0000ff;">&gt;</span>1<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">statuscode</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">statecode</span> <span style="color:#ff0000;">formattedValue</span>=<span style="color:#0000ff;">"Active"</span><span style="color:#0000ff;">&gt;</span>Active<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">statecode</span><span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">account</span><span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">account</span> <span style="color:#ff0000;">xmlns</span>:<span style="color:#ff0000;">crm</span>=<span style="color:#0000ff;">"http://schemas.microsoft.com/crm/2006/WebServices"</span> <span style="color:#ff0000;">xmlns</span>:<span style="color:#ff0000;">xsi</span>=<span style="color:#0000ff;">"http://www.w3.org/2001/XMLSchema-instance"</span> <span style="color:#ff0000;">xmlns</span>:<span style="color:#ff0000;">xsd</span>=<span style="color:#0000ff;">"http://www.w3.org/2001/XMLSchema"</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">name</span><span style="color:#0000ff;">&gt;</span>Contoso Inc.<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">name</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">accountid</span><span style="color:#0000ff;">&gt;</span>A00ED7BB-9D0D-DB11-9073-000C293F9D57<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">accountid</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">donotphone</span> <span style="color:#ff0000;">name</span>=<span style="color:#0000ff;">"Allow"</span><span style="color:#0000ff;">&gt;</span>0<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">donotphone</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">modifiedby</span> <span style="color:#ff0000;">name</span>=<span style="color:#0000ff;">"CRM Administrator"</span> <span style="color:#ff0000;">dsc</span>=<span style="color:#0000ff;">"0"</span><span style="color:#0000ff;">&gt;</span>89A611D4-C7BD-DB11-A4E3-005056A80A71<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">modifiedby</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">createdby</span> <span style="color:#ff0000;">name</span>=<span style="color:#0000ff;">"CRM Administrator"</span> <span style="color:#ff0000;">dsc</span>=<span style="color:#0000ff;">"0"</span><span style="color:#0000ff;">&gt;</span>89A611D4-C7BD-DB11-A4E3-005056A80A71<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">createdby</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">statuscode</span> <span style="color:#ff0000;">name</span>=<span style="color:#0000ff;">"Active"</span><span style="color:#0000ff;">&gt;</span>1<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">statuscode</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">statecode</span> <span style="color:#ff0000;">formattedValue</span>=<span style="color:#0000ff;">"Active"</span><span style="color:#0000ff;">&gt;</span>Active<span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">crm</span>:<span style="color:#800000;">statecode</span><span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">account</span><span style="color:#0000ff;">&gt;</span></pre>
<p>That is exactly what you need to obtain, with the help of XmlSerializer, a collection of accounts:</p>
<pre>XmlReader xmlReader = cmd.ExecuteXmlReader();
xmlReader.Read();

<span style="color:#0000ff;">while</span> (xmlReader.ReadState != ReadState.EndOfFile)
{
    xml = xmlReader.ReadOuterXml();
    StringReader reader = <span style="color:#0000ff;">new</span> StringReader(xml);

    account acc = serializer.Deserialize(reader) <span style="color:#0000ff;">as</span> account;
    accounts.Add(acc);
}

<span style="color:#008000;">// convert accounts in a BusinessEntitesCollection...</span></pre>
<p><strong>Note that</strong>:<br />
- the standard SQL syntax for a property is:</p>
<p align="left">, property <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> &#8216;<span style="color:#8b0000;">crm:property</span>&#8216;</p>
<p>- properties expressed by CRM object model in form of &#8220;Lookup&#8221; are splitted, on the views, in three columns:</p>
<p>, property<font color="#ff0000">name</font> <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> &#8216;<span style="color:#8b0000;">crm:property/@name</span>&#8216;<br />
, property<font color="#ff0000">dsc</font> <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> &#8216;<span style="color:#8b0000;">crm:property/@dsc</span>&#8216;<br />
, property <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> &#8216;<span style="color:#8b0000;">crm:property</span>&#8216;</p>
<p>- properties expressed by CRM object model in form of &#8220;Picklist&#8221; and &#8220;CrmBoolean&#8221; are splitted, on the views, in two columns:</p>
<p>, property<font color="#ff0000">name</font> <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> &#8216;<span style="color:#8b0000;">crm:property/@name</span>&#8216;<br />
, property <a href="http://search.microsoft.com/default.asp?so=RECCNT&amp;siteid=us%2Fdev&amp;p=1&amp;nq=NEW&amp;qu=as&amp;IntlSearch=&amp;boolean=PHRASE&amp;ig=01&amp;i=09&amp;i=99">as</a> &#8216;<span style="color:#8b0000;">crm:property</span>&#8216;</p>
<p>- StatusCode and StateCode are the only further singularity.</p>
<p>Given these rules isn&#8217;t hard to build a class able to generate statements for any entity type. For an hard-core solution, add something able to translate a <strong>QueryExpression</strong> in SQL statements&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sharpreflections.net/2007/04/06/dynamics-crm-as-development-platform-transparent-substitution-of-crmservice-with-filtered-views/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Quiz #1</title>
		<link>http://blog.sharpreflections.net/2007/03/15/quiz-1/</link>
		<comments>http://blog.sharpreflections.net/2007/03/15/quiz-1/#comments</comments>
		<pubDate>Thu, 15 Mar 2007 20:19:25 +0000</pubDate>
		<dc:creator>matteosp</dc:creator>
				<category><![CDATA[.Net Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Quiz]]></category>

		<guid isPermaLink="false">http://sharpreflections.wordpress.com/2007/03/15/quiz-1/</guid>
		<description><![CDATA[Modify this apparently thread-safe event raiser in such a way it becomes truly thread-safe without changing signature nor implementation.
protected void OnMyEvent(MyEventArg e)
{
   MyEventHandler handler = MyEvent;

   if (handler != null)
      handler (this, e);
}
Inspired by this post by Pierre Greborio.
]]></description>
			<content:encoded><![CDATA[<p>Modify this <strong>apparently</strong> thread-safe event raiser in such a way it becomes <strong>truly</strong> thread-safe <font color="#ff0000">without changing signature nor implementation</font>.</p>
<pre><span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">void</span> OnMyEvent(MyEventArg e)
{
   MyEventHandler handler = MyEvent;

   <span style="color:#0000ff;">if</span> (handler != <span style="color:#0000ff;">null</span>)
      handler (<span style="color:#0000ff;">this</span>, e);
}</pre>
<p>Inspired by <a href="http://blogs.ugidotnet.org/pierregreborio/archive/2007/01/19/67679.aspx" title="Lanciare l'evento in modo sicuro" target="_blank" rel="Lanciare l'evento in modo sicuro">this post</a> by <a href="http://blogs.ugidotnet.org/pierregreborio/" title="UGbLog di Pierre Greborio" target="_blank">Pierre Greborio</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sharpreflections.net/2007/03/15/quiz-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quiz Sharp #0</title>
		<link>http://blog.sharpreflections.net/2007/03/09/quiz-sharp-1/</link>
		<comments>http://blog.sharpreflections.net/2007/03/09/quiz-sharp-1/#comments</comments>
		<pubDate>Fri, 09 Mar 2007 17:58:37 +0000</pubDate>
		<dc:creator>matteosp</dc:creator>
				<category><![CDATA[.Net Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Quiz]]></category>

		<guid isPermaLink="false">http://sharpreflections.wordpress.com/2007/03/09/quiz-sharp-1/</guid>
		<description><![CDATA[This is my first quiz, and is the result of a beatiful and long chat with my good friend Adrian Florea. Here the Italian version on his blog.
Look at this snippet:
struct Foo
{
	public static implicit operator bool(Foo value)
	{
		return value != null;
	}
}

static void Main(string[] args)
{
	if (new Foo())
	{
		Console.WriteLine("Hello word!");
	}
}
What will you get? And, first of all, why?
a) nothing
b) [...]]]></description>
			<content:encoded><![CDATA[<p>This is my first quiz, and is the result of a beatiful and long chat with my good friend <a href="http://blogs.ugidotnet.org/adrian/" target="_blank">Adrian Florea</a>. <a href="http://blogs.ugidotnet.org/adrian/archive/2007/03/09/72692.aspx" target="_blank">Here</a> the Italian version on his blog.</p>
<p>Look at this snippet:</p>
<pre><span style="color:#0000ff;">struct</span> Foo
{
	<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">implicit</span> <span style="color:#0000ff;">operator</span> <span style="color:#0000ff;">bool</span>(Foo <span style="color:#0000ff;">value</span>)
	{
		<span style="color:#0000ff;">return</span> <span style="color:#0000ff;">value</span> != <span style="color:#0000ff;">null</span>;
	}
}

<span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> Main(<span style="color:#0000ff;">string</span>[] args)
{
	<span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">new</span> Foo())
	{
		Console.WriteLine("<span style="color:#8b0000;">Hello word!</span>");
	}
}</pre>
<p>What will you get? And, first of all, why?</p>
<p>a) nothing</p>
<p>b) &#8220;Hello word!&#8221;</p>
<p>c) a compiler error</p>
<p>d) a runtime error</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sharpreflections.net/2007/03/09/quiz-sharp-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>System.Diagnostics.Trace is not safe.</title>
		<link>http://blog.sharpreflections.net/2006/02/22/systemdiagnosticstrace-is-not-safe/</link>
		<comments>http://blog.sharpreflections.net/2006/02/22/systemdiagnosticstrace-is-not-safe/#comments</comments>
		<pubDate>Wed, 22 Feb 2006 17:21:00 +0000</pubDate>
		<dc:creator>matteosp</dc:creator>
				<category><![CDATA[.Net Programming]]></category>

		<guid isPermaLink="false">https://sharpreflections.wordpress.com/2006/02/22/systemdiagnosticstrace-is-not-safe/</guid>
		<description><![CDATA[I always thought that methods exposed by System.Diagnostics.Trace class did something like  dispatching messages to the OS and/or to the trace listeners configured for the application. And by  dispatching I mean a sort of asynchronous and safe (from exceptions in the  listeners if any) delivering of messages.
I don&#8217;t know exactly why I [...]]]></description>
			<content:encoded><![CDATA[<p>I always thought that methods exposed by <a href="http://msdn2.microsoft.com/en-us/library/system.diagnostics.trace.aspx" title="Link to MSDN">System.Diagnostics.Trace</a> class did something like  dispatching messages to the OS and/or to the <a href="http://msdn2.microsoft.com/en-us/library/system.diagnostics.trace.listeners.aspx" title="Link to MSDN">trace listeners</a> configured for the application. And by  dispatching I mean a sort of asynchronous and safe (from exceptions in the  listeners if any) delivering of messages.</p>
<p>I don&#8217;t know exactly why I had  this idea in my mind, but in any case it was a wrong idea. The execution of  method like Trace.WriteLine(&#8221;my message&#8221;) is synchronous, and may generate an  exception if something goes wrong in one of the trace listeners currently  registered.<br />
I think that this can occurs easily because:<br />
- trace  listeners can be simply registered by editing the configuration file.<br />
-  you can pass to Trace class methods messages in form of objects, not only  strings.<br />
- if your are programming a component you may not have envision  of the environment in which your code will run.</p>
<p>I have to start enclose calls to those methods in try &#8211; catch blocks. I  would like to know: does someone (if there is someone that use this  class) already do it?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sharpreflections.net/2006/02/22/systemdiagnosticstrace-is-not-safe/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom collections and databinding, part 2: filtering.</title>
		<link>http://blog.sharpreflections.net/2005/11/08/custom-collections-and-databinding-part-2-filtering/</link>
		<comments>http://blog.sharpreflections.net/2005/11/08/custom-collections-and-databinding-part-2-filtering/#comments</comments>
		<pubDate>Tue, 08 Nov 2005 04:32:00 +0000</pubDate>
		<dc:creator>matteosp</dc:creator>
				<category><![CDATA[.Net Programming]]></category>

		<guid isPermaLink="false">https://sharpreflections.wordpress.com/2005/11/08/custom-collections-and-databinding-part-2-filtering/</guid>
		<description><![CDATA[Now I want to discuss the way I implemented the capability to filter data presented the consumers of my class. What I was looking for and I obtained is the possibility to apply a filter in the way of a complex filter expression like " AnyProperty = 'AnyValue' AND AnotherProperty <= 'AnotherValue' AND NOT ThirdProperty LIKE '%ThirdValue%' ".]]></description>
			<content:encoded><![CDATA[<p>In my last post I presented myimplementation of a class that incapsulates the<br />
logic for supporting the databing of a generic custom collection.</p>
<p>Now I want to discuss the way I implemented the capability to filter data presented the consumers of my class. What I was looking for and I obtained is the possibility to apply a filter in the way of a complex filter expression like &#8221; <font face="Courier">AnyProperty = &#8216;AnyValue&#8217; AND AnotherProperty &gt; = &#8216;AnotherValue&#8217; AND NOT ThirdProperty LIKE &#8216;%ThirdValue%&#8217; </font> &#8220;.</p>
<p>I&#8217;m going to present my solution and I hope to read your comments, opinions,<br />
and so on. Remember that my class, <font face="Courier New">CollectionView</font><br />
, accept as source any class that implements ICollection and that consequently<br />
I must be able to apply that kind of filter expression to any kinf of object.</p>
<p>Consider the example:</p>
<p><font face="Courier"> </font><font face="Courier">ArrayList list = new ArrayList();list.Add(new Blogger(&#8221;Albert Einstein&#8221;, &#8220;blogs.genies.org/albert&#8221;, 45));</font></p>
<p><font face="Courier">list.Add(new Blogger(&#8221;Jack Keruoac&#8221;, &#8220;blogs.beatfoundation.org/jk&#8221;, 24));</font></p>
<p><font face="Courier">list.Add(new Blogge(&#8221;Henry Miller&#8221;, &#8220;blogs.lesparisiennes.fr/henry&#8221;, 36));</font></p>
<p><font face="Courier">CollectionView view = new CollectionView(list);</font></p>
<p><font face="Courier">view.FilterExpression = &#8220;Age &gt;= &#8216;36&#8242; AND BlogUrl LIKE &#8216;blogs.beatfoundation%&#8217; AND NOT Name LIKE &#8216;Alb%&#8217;&#8221;;</font></p>
<p><font face="Courier"><br />
</font> in which Blogger is a very simple class with only 3 properties:<br />
<font face="Courier"> public int Age,<br />
public string BlogUrl and<br />
public string Name.</font></p>
<p>I divided the logic needed to apply the filter into 3 classes: <font face="Courier">CollectionViewFilter</font>,<br />
<font face="Courier">ConditionEvaluator</font>, <font face="Courier">ExpressionEvaluator</font>.<br />
All these 3 classes are declared internal in my class library as the only<br />
property <font face="Courier">CollectionView</font> exposes for applying the filter is a <font face="Courier">string FilterExpression {get; set;}</font>.<br />
Let&#8217;s examine these classes.</p>
<p><b><font face="Courier">CollectionViewFilter</font></b>.</p>
<p>This class is the entry point for the filtering process. It contains the<br />
routines needed to extract from the filter expression the tokens that represent<br />
the single conditions. The filter expression needs to be passed to constructor<br />
and the tokens extraction is done with the help of a regular expression. So<br />
considering the example above, it split that filter expression in these 3<br />
tokens:</p>
<ul>
<li>Age &gt;= &#8216;36&#8242;</li>
<li>BlogUrl LIKE &#8216;blogs.beatfoundation%&#8217;</li>
<li>Name LIKE &#8216;Alb%&#8217;</li>
</ul>
<p>The class exposes only one public method that is: <font face="Courier">public bool MatchObject(object obj)</font>. The purpose of this method is obviouisly returning a bool value that indicates if the object in argument meet all the conditions (expressed by the 3 tokens) or not. I do this by extracting from every token the property name (i.e.: BlogUrl), the operator (LIKE) and the property value (&#8217;blogs.beatfoundation%&#8217;). I delegate the process of verifying if the property BlogUrl of any instance of the Blogger class is LIKE &#8216;blogs.beatfoundation%&#8217; to the ConditionEvaluator class.</p>
<p><b><font face="Courier">ConditionEvaluator</font></b>.</p>
<p>This logical task accomplished by this class is quite simple, I will not discuss over it&#8217;s implementation. It accept in the constructor the property name, the operator and the property value that <font face="Courier">CollectionViewFilter</font> class extracts from each token, then it performs these steps:</p>
<ul>
<li>Discover via reflection the property descriptor for the specified property<br />
name.</li>
<li>Receive the instance of the object that needs to be matched with the condition<br />
(the same instance received by <font face="Courier">CollectionViewFilter</font><br />
in <font face="Courier">MatchObject()</font><br />
method, in the case of my example an instance of the Blogger class.)</li>
<li>Perform the necessary comparison based on: the property type, the specified<br />
operator and the jollychars if any in the value.</li>
<li>Returns a bool value indicating if the passed instance meets the condition<br />
(BlogUrl LIKE &#8216;blogs.beatfoundation%&#8217;).</li>
</ul>
<p>CollectionViewFilter repeats the operation for each token it extracted from the filter expression. So it use ConditionEvaluator for evaluate on the instance passed to <font face="Courier">MatchObject()</font> method all the conditions expressed by the 3 tokens. This will cause the original filter expression</p>
<p>&#8221; <font face="Courier">Age &gt;= &#8216;36&#8242; AND BlogUrl LIKE &#8216;blogs.beatfoundation%&#8217; AND<br />
NOT Name LIKE &#8216;Alb%&#8217;</font> &#8220;;</p>
<p>to be translated is a string like:</p>
<p>&#8220;<font face="Courier">true AND true AND NOT true</font>&#8221; (the case of <font face="Courier"><br />
new Blogger(&#8221;Albert Einstein&#8221;, &#8220;blogs.genies.org/albert&#8221;, 45)</font>).</p>
<p><b><font face="Courier">ExpressionEvaluator</font></b> .</p>
<p>Now, how can I simply translate a string like the one obove (or a more<br />
complex one) in single evalutaed bool value? Why the magic C# team didn&#8217;t<br />
implemented an Eval function like the one JScript has? And the I told to my<br />
self: &#8220;Hey! wait a moment. As I can compile some JScript statement I can get<br />
the Eval function in my C# runtime!!&#8221;</p>
<p>And I did it this way in my <font face="Courier">ExpressionEvaluator</font> class,<br />
look at this snippet:<br />
<font face="Courier"> private static object evaluator = null;private static Type evaluatorType = null;</font></p>
<p><font face="Courier">private static readonly string jsSource =</font></p>
<p><font face="Courier">@&#8221;package ExpressionEvaluator</font></p>
<p><font face="Courier">{</font></p>
<p><font face="Courier">class Evaluator</font></p>
<p><font face="Courier">{</font></p>
<p><font face="Courier">public function Eval(expr : String) : String</font></p>
<p><font face="Courier">{</font></p>
<p><font face="Courier">return eval(expr);</font></p>
<p><font face="Courier">}</font></p>
<p><font face="Courier">}</font></p>
<p><font face="Courier">}&#8221;;</font></p>
<p><font face="Courier">static ExpressionEvaluator()</font></p>
<p><font face="Courier">{</font></p>
<p><font face="Courier">ICodeCompiler compiler = new JScriptCodeProvider().CreateCompiler();</font></p>
<p><font face="Courier">CompilerParameters parameters = new CompilerParameters();</font></p>
<p><font face="Courier">parameters.GenerateInMemory = true;</font></p>
<p><font face="Courier">CompilerResults results = compiler.CompileAssemblyFromSource(parameters, jsSource);</font></p>
<p><font face="Courier">Assembly assembly = results.CompiledAssembly;</font></p>
<p><font face="Courier">evaluatorType = assembly.GetType(&#8221;ExpressionEvaluator.Evaluator&#8221;);</font></p>
<p><font face="Courier">evaluator = Activator.CreateInstance(evaluatorType);</font></p>
<p><font face="Courier">} </font><br />
The JScript statement contained in jsSource is compiled only once in the<br />
static constructor (need a reference to microsoft.jscript.dll) and is available<br />
for functions like:<br />
<font face="Courier"> public static bool EvalToBoolean(string statement){</font></p>
<p><font face="Courier">object o = EvalToObject(statement);</font></p>
<p><font face="Courier">return bool.Parse(o.ToString());</font></p>
<p><font face="Courier">}</font></p>
<p><font face="Courier">public static object EvalToObject(string statement)</font></p>
<p><font face="Courier">{</font></p>
<p><font face="Courier">BindingFlags flags = BindingFlags.InvokeMethod;</font></p>
<p><font face="Courier">object[] args = new object[] { statement };</font></p>
<p><font face="Courier">return evaluatorType.InvokeMember(&#8221;Eval&#8221;, flags, null, evaluator, args);</font></p>
<p><font face="Courier">}<br />
</font> This made my class <font face="Courier">CollectionViewFilter</font> able to<br />
simply resolve &#8220;true AND true AND NOT true&#8221; into &#8220;false&#8221;.The entire process is launched by <font face="Courier">CollectionView</font> whenever<br />
it has to build is inner source from the <font face="Courier">ICollection</font><br />
passed in his constructor or when is property <font face="Courier">FilterExpression</font><br />
changes to determine which of the elements in the source collection should be<br />
passed to the dataconsumer.</p>
<p><font color="red">UPDATE: I forgot a little thing: in order to make a string like<br />
&#8220;true AND true AND NOT true&#8221; evaluable by the JScript routine you have to<br />
replace the logical operators, in particular you must replace &#8220;AND&#8221; with<br />
&#8220;&amp;&amp;&#8221;, &#8220;OR&#8221; with &#8220;||&#8221;, &#8220;NOT&#8221; with &#8220;!&#8221;.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sharpreflections.net/2005/11/08/custom-collections-and-databinding-part-2-filtering/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom collections and databinding.</title>
		<link>http://blog.sharpreflections.net/2005/11/05/custom-collections-and-databinding/</link>
		<comments>http://blog.sharpreflections.net/2005/11/05/custom-collections-and-databinding/#comments</comments>
		<pubDate>Sat, 05 Nov 2005 04:09:00 +0000</pubDate>
		<dc:creator>matteosp</dc:creator>
				<category><![CDATA[.Net Programming]]></category>

		<guid isPermaLink="false">https://sharpreflections.wordpress.com/2005/11/05/custom-collections-and-databinding/</guid>
		<description><![CDATA[I always prefer custom business objects to .Net Datasets and Datatables when I
write data representation logic for my web apps. So data abstraction layers I
write are plenty of classes representing business entities and type-safe custom
collections for entities enlisting. While collecting instances in a custom
collection is not an hard task at all, provide to a collection functionalities
like complex databinding, sorting and filtering is a little bit harder. Furthermore incapsulating such as capibilities in only one generic class requires a bit of time...]]></description>
			<content:encoded><![CDATA[<p>I always prefer custom business objects to .Net Datasets and Datatables when I write data representation logic for my web apps. So data abstraction layers I write are plenty of classes representing business entities and type-safe custom collections for entities enlisting. While collecting instances in a custom collection is not an hard task at all, provide to a collection functionalities like complex databinding, sorting and filtering is a little bit harder. Furthermore incapsulating such as capibilities in only one generic class requires a bit of time&#8230; But now I got it! I have this generic class (I call it CollectionView) that:
<ul>
<li>accepts as source any class implementing ICollection interface
<li>generates a set of bindable columns based on the Type of the objects collected by the source.
<li>allows the manipulation of the columns set (reordering, visibility, etc)
<li>supports sorting and filtering
<li>is a valid datasource for .Net WebControls </li>
</ul>
<p>Let&#8217;s take a look to how I did this. First of all class signature and construtors: </p>
<div class="wlWriterSmartContent">
<pre>
<div><span>public</span><span> </span><span>class</span><span> CollectionView : ITypedList, IEnumerable, ICollection
{
    </span><span>public</span><span> CollectionView(ICollection collection)
    {
        m_collection </span><span>=</span><span> collection;
    }

    </span><span>public</span><span> CollectionView(ICollection collection, Type collectionItemsType)
    {
        m_collection </span><span>=</span><span> collection; m_collectionItemsType </span><span>=</span><span> collectionItemsType;
    }

    </span><span>//</span><span>…</span><span>
</span><span>}</span></div>
</pre>
</div>
<p>CollectionView implements 3 interfaces: ITypedList, IEnumerable, and ICollection. IEnumerable is obviously required for a complex databinding and ICollection (through Count property) allows operation such as paging. ITypedList allows to notify the dataconsumer (the web control that CollectionView will be bound to) which are the properties of the source collection items we want to be considered in the binding process. To be more precise: during the databinding process the dataconsumer invokes the GetItemProperties() method on ITypeList and receive the collection of property descriptors that it will use to bind it&#8217;s items (i.e: DataGrid items) to the collection items. Here ITypedList declaration: </p>
<div class="wlWriterSmartContent">
<pre>
<div><span>public</span><span> </span><span>interface</span><span> ITypedList
{
    PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors);

    </span><span>string</span><span> GetListName(PropertyDescriptor[] listAccessors);
}</span></div>
</pre>
</div>
<p>Looking at the constructors you can understand that as the source collection is referenced through ICollection is possible to specify as source almost all the kind of collection you can have in the Framework. Optionally, also the Type of objects the source contains can be explicitly declared. This optional declaration is important because influences the way CollectionView builds the set of bindable columns and in turn this columns set can influence the PropertyDescriptorCollection instance returned by the GetItemProperties() method we&#8217;ve just seen. It will soon be more clear as I&#8217;m going to explain it. The return value of GetItemProperties() could have been exactly the result of a query for the public properties exposed by items in the source collection. But I decided to add the possibility, for the caller of CollectionView, to reorder these properties or to hide some of them. So what I&#8217;ve done is: </p>
<ul>
<li>I created a class named CollectionViewColumnSet that is a type-safe collection (another one!) of CollectionViewColumn objects and that is exposed by CollectionView through the Columns property.
<li>This column set is generated (the first time the Columns property is accessed) querying the public properties of the items in the source collection and every CollectionViewColumn will map one of these properties.
<li>CollectionView callers are able to reorder the columns or hide some of them through properties such as Visible (bool) and Ordinal (double) exposed by CollectionViewColumn class.
<li>When the dataconsumer calls GetItemProperties() the PropertyDescriptorCollection to be returned is build reflecting the state of each column in the column set. </li>
</ul>
<p>Here the 2 routines I wrote to query the properties of the items in the source collection (DiscoverPropertyDescriptors) and to build the column set (EmitColumnsFromProperties): </p>
<div class="wlWriterSmartContent">
<pre>
<div><span>private</span><span> PropertyDescriptorCollection DiscoverPropertyDescriptors()
{
    </span><span>if</span><span> (m_collectionItemsType </span><span>!=</span><span> </span><span>null</span><span>)
        </span><span>return</span><span> TypeDescriptor.GetProperties(m_collectionItemsType);
    </span><span>else</span><span>
    {
        </span><span>//</span><span> if caller has not explict declared the Type of the items in the source collection
        </span><span>//</span><span> I try to discover if by my self:</span><span>
</span><span>
        </span><span>object</span><span> item </span><span>=</span><span> GetAnyItemFromTheSourceCollection();

        </span><span>if</span><span> (item </span><span>!=</span><span> </span><span>null</span><span>)
            </span><span>return</span><span> TypeDescriptor.GetProperties(item);
        </span><span>else</span><span>
        {
            </span><span>//</span><span> in this case the dataconsumer will not be able to complete the binding process
            </span><span>//</span><span> but I can’t do anything abount that. May be I should throw an exception…</span><span>
</span><span>
            PropertyDescriptor[] properties </span><span>=</span><span> </span><span>new</span><span> PropertyDescriptor[</span><span>0</span><span>];
            </span><span>return</span><span> </span><span>new</span><span> PropertyDescriptorCollection(properties);
        }
    }
}

</span><span>private</span><span> CollectionViewColumnSet EmitColumnsFromProperties()
{
    CollectionViewColumnSet cols </span><span>=</span><span> </span><span>new</span><span> CollectionViewColumnSet();
    PropertyDescriptorCollection descriptors </span><span>=</span><span> DiscoverPropertyDescriptors();

    </span><span>foreach</span><span> (PropertyDescriptor propertyDesc </span><span>in</span><span> descriptors)
    {
        CollectionViewColumn col </span><span>=</span><span> </span><span>new</span><span> CollectionViewColumn(propertyDesc.Name, propertyDesc);
        col.Ordinal </span><span>=</span><span> cols.Count;

        cols.Add(col);
    }

    </span><span>return</span><span> cols;
}</span></div>
</pre>
</div>
<p>Now you can understand what I meant when I was saying that the optional explicit declaration (with the second overload of the constructor) of the Type of the items in the source collection is important: in the case in which the Type is declared I call TypeDescriptor.GetProperties() passing it as argument, in the second case I have to try to find an item in the collection and use this as argument. Is important to know that: taken an instance of any class fooInstance the results of TypeDescriptor.GetProperties(fooInstance) and TypeDescriptor.GetProperties(fooInstance.GetType()) can be different. In fact, and I report what the Framework documentation says, <i>the properties for a component can differ from the properties of a class, because the site can add or remove properties if the component is sited</i>. </p>
<p>To complete the column set life-cycle, this is the implementation of ITypedList.GetItemProperties() method in which I reflect the column set state to the properties returned to the dataconsumer: </p>
<div class="wlWriterSmartContent">
<pre>
<div><span>public</span><span> PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
{
    </span><span>return</span><span> ReflectPropertiesFromColumns();
}

</span><span>private</span><span> PropertyDescriptorCollection ReflectPropertiesFromColumns()
{
    ArrayList descriptors </span><span>=</span><span> </span><span>new</span><span> ArrayList();

    </span><span>foreach</span><span> (CollectionViewColumn col </span><span>in</span><span> </span><span>this</span><span>.Columns)
    {
        </span><span>if</span><span> (col.Visible)
            descriptors.Add(col.PropertyDescriptor);
    }

    PropertyDescriptor[] properties </span><span>=</span><span> </span><span>new</span><span> PropertyDescriptor[descriptors.Count];
    descriptors.CopyTo(properties, </span><span>0</span><span>);

    </span><span>return</span><span> </span><span>new</span><span> PropertyDescriptorCollection(properties);
}</span></div>
</pre>
</div>
<p>I have another couple of interesting things to tell about managing the properties-columns and about filtering the source collection, but it&#8217;s 4.00 AM so: <i>to be continued&#8230;</i></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sharpreflections.net/2005/11/05/custom-collections-and-databinding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Provider model everywhere</title>
		<link>http://blog.sharpreflections.net/2005/10/22/provider-model-everywhere/</link>
		<comments>http://blog.sharpreflections.net/2005/10/22/provider-model-everywhere/#comments</comments>
		<pubDate>Sat, 22 Oct 2005 22:42:00 +0000</pubDate>
		<dc:creator>matteosp</dc:creator>
				<category><![CDATA[.Net Programming]]></category>

		<guid isPermaLink="false">https://sharpreflections.wordpress.com/2005/10/22/provider-model-everywhere/</guid>
		<description><![CDATA[Today I developed a small and simple web control (on1.1) that represents a navigation bar. The goal was realize this navigation bar with Microsoft CRM &#8220;look and feel&#8221; as it would to be inserted on a CRM integration project. 
I started with 3 classes: NavigationBar, NavigationBarItem and NavigationBarItemCollection. NavigationBar and NavigationBarItem inherit from WebControl. I [...]]]></description>
			<content:encoded><![CDATA[<p>Today I developed a small and simple web control (on1.1) that represents a navigation bar. The goal was realize this navigation bar with Microsoft CRM &#8220;look and feel&#8221; as it would to be inserted on a CRM integration project. </p>
<p>I started with 3 classes: NavigationBar, NavigationBarItem and NavigationBarItemCollection. NavigationBar and NavigationBarItem inherit from <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwebuiwebcontrolswebcontrolclasstopic.asp" target="_blank">WebControl</a>. I wrote all common properties and methods you usually have to implement (or to override) to manage the ViewState, the DataBinding process, ect. I think I wrote some nice code on <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemcollectionsienumerableclasstopic.asp" target="_blank">IEnumerable</a>,<a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemcomponentmodelilistsourceclasstopic.asp" target="_blank"> IListSource</a>,<a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemcollectionsilistclasstopic.asp" target="_blank"> IList</a> and <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemcomponentmodelitypedlistclasstopic.asp" target="_blank">ITypedList</a> interfaces to accept as datasource as many types as possible. But this is not what I want to talk about, may be I will do it in another post. </p>
<p>After that I reached the rendering phase and I realized: &#8220;I don&#8217;t want a control with a CRM look and feel. I want a control that is flexible enought for rendering its content in many ways, and sometimes in the CRM look and feel way.&#8221; And I proceeded this way: </p>
<p>1)I defined a new abstract class named NavigationBarRenderingProviderBase that requires an instance of NavigationBar (the control to be rendered) to be passed in the constructor, exposes this instance in a protected readonly property and defines 3 abstract methods. Here this class code: </p>
<div class="wlWriterSmartContent">
<pre>
<div><span>public</span><span> </span><span>abstract</span><span> </span><span>class</span><span> NavigationBarRenderingProviderBase
{
    </span><span>private</span><span> NavigationBar navigationBar;

    </span><span>protected</span><span> NavigationBarRenderingProviderBase(NavigationBar navigationBar)
    {
        </span><span>this</span><span>.navigationBar </span><span>=</span><span> navigationBar;
    }

    </span><span>protected</span><span> NavigationBar NavigationBar
    {
        </span><span>get</span><span> { </span><span>return</span><span> navigationBar; }
    }

    </span><span>public</span><span> </span><span>abstract</span><span> </span><span>void</span><span> RenderNavigationBarStart(HtmlTextWriter writer);
    </span><span>public</span><span> </span><span>abstract</span><span> </span><span>void</span><span> RenderNavigationBarEnd(HtmlTextWriter writer);
    </span><span>public</span><span> </span><span>abstract</span><span> </span><span>void</span><span> RenderNavigationBarItem(HtmlTextWriter writer, NavigationBarItem navigationBarItem);
}</span></div>
</pre>
</div>
<p>As their names say, the 3 abstract methods will handle the begin of the rendering process, the rendering of every item in the NavigationBar and the end of the process. </p>
<p>2) I developed a basic specialization of this class, named NavigationBarRenderingProvider. And I wrote the code needed for the standard rendering of my control. </p>
<p>3) I developed a further specialization of this class, named CrmNavigationBarRenderingProvider. And I wrote the code needed for rendering my control in the CRM look and feel. </p>
<p>4) I defined a property in NavigationBar throught which is possible to define the rendering provider to use. This property returns the standard rendering provider (NavigationBarRenderingProvider ) if no one has been set. </p>
</p>
<div class="wlWriterSmartContent">
<pre>
<div><span>public</span><span> NavigationBarRenderingProviderBase RenderingProvider
{
    </span><span>get</span><span>
    {
        </span><span>if</span><span> (m_RenderingProvider </span><span>==</span><span> </span><span>null</span><span>)
            m_RenderingProvider </span><span>=</span><span> </span><span>new</span><span> NavigationBarRenderingProvider(</span><span>this</span><span>);

        </span><span>return</span><span> m_RenderingProvider;
    }
    </span><span>set</span><span> { m_RenderingProvider </span><span>=</span><span> value; }
}</span></div>
</pre>
</div>
<p>5) I overrode the render method to obtain the delegation of the rendering process to the rendering provider. </p>
</p>
<div class="wlWriterSmartContent">
<pre>
<div><span>protected</span><span> </span><span>override</span><span> </span><span>void</span><span> Render(HtmlTextWriter writer)
{
    </span><span>this</span><span>.RenderingProvider.RenderNavigationBarStart(writer);

    </span><span>foreach</span><span> (NavigationBarItem item </span><span>in</span><span> </span><span>this</span><span>.Items)
    {
        </span><span>this</span><span>.RenderingProvider.RenderNavigationBarItem(writer, item);
    }

    </span><span>this</span><span>.RenderingProvider.RenderNavigationBarEnd(writer);
}</span></div>
</pre>
</div>
<p>Done. I have a WebControl that: &#8211; incapsulates all the logic needed to support DataBinding and to manage then ViewState. &#8211; exposes the rendering algorithm(s) trought a standard interface to allow different behaviours.I&#8217;m now thinking about making possible to configure the default rendering provider in web.config file. This will allow to easily change the rendering behaviour of my control in the entire web application. But I&#8217;m still not sure&#8230; </p>
<p>But, what about this implementation? Can I think to it as a to provider model implementation even if isn&#8217;t strictly related to data management? I think so, and you?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sharpreflections.net/2005/10/22/provider-model-everywhere/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
