<?xml version="1.0" encoding="utf-8"?>
<feed xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xml:lang="en-us" xmlns="http://www.w3.org/2005/Atom">
  <title>[Giagnocavo]Michael::Write()</title>
  <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/" />
  <link rel="self" href="http://www.atrevido.net/blog/SyndicationService.asmx/GetAtom" />
  <icon>favicon.ico</icon>
  <updated>2008-06-26T16:30:47.40625-04:00</updated>
  <author>
    <name>Michael Giagnocavo</name>
  </author>
  <subtitle>Something about .NET.</subtitle>
  <id>http://www.atrevido.net/blog/</id>
  <generator uri="http://www.dasblog.net" version="1.9.7174.0">DasBlog</generator>
  <entry>
    <title>I underestimated the power of query comprehensions</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2008/06/26/I+Underestimated+The+Power+Of+Query+Comprehensions.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,ae23e7f3-a43e-4bc5-90cc-12b2b74dff99.aspx</id>
    <published>2008-06-26T02:15:10.687-04:00</published>
    <updated>2008-06-26T02:25:29.796875-04:00</updated>
    <category term="Code" label="Code" scheme="http://www.atrevido.net/blog/CategoryView,category,Code.aspx" />
    <category term="F#" label="F#" scheme="http://www.atrevido.net/blog/CategoryView,category,F%23.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
In my <a href="http://www.atrevido.net/blog/2008/06/26/LINQ+To+The+CRUD+CreateTable+Generator+In+F.aspx">last
post</a>, I said I'd write the sample in C# to compare to F#. Well, I grossly underestimated
the power of query comprehensions. The C# version is almost the same length (formatting
differences, mainly). I'm surprised and impressed. (Or maybe I'm writing F# like I'd
write C#.) Edit: I think maybe sequence expressions could cut it down a bit...
</p>
        <p>
...But... C# still can't do discriminated unions efficiently or effectively ;). 
</p>
        <p>
          <hr />
        </p>
        <p>
        </p>
        <div style="FONT-SIZE: 11pt; BACKGROUND: white; COLOR: black; FONT-FAMILY: Consolas">
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    1</span> <span style="COLOR: green">//
crudcreatecompare.cs: Generates LINQ CRUD table fields using the horribly named DatabaseBase
code</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    2</span> <span style="COLOR: green">//</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    3</span> <span style="COLOR: green">//
Tables look like: [Table(Name="dbo.Accounts")]</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    4</span> <span style="COLOR: green">//
Columns look like this:</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    5</span> <span style="COLOR: green">// 
[Column(Storage="_AccountName", DbType="VarChar(128) NOT NULL", CanBeNull=false, IsPrimaryKey=true)]</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    6</span> <span style="COLOR: green">// 
[DataMember(Order=1)] // Exists if serialization is turned on; used to order key parameters</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    7</span> <span style="COLOR: green">//
Emits:</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    8</span> <span style="COLOR: green">// 
public static readonly TableHelper&lt;Account, String&gt; Accounts =</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    9</span> <span style="COLOR: green">//   
  CreateTable(dc =&gt; dc.Accounts, a =&gt; a.AccountName);</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   10</span> 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   11</span> <span style="COLOR: blue">using</span> System;
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   12</span> <span style="COLOR: blue">using</span> System.Collections.Generic;
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   13</span> <span style="COLOR: blue">using</span> System.Data.Linq.Mapping;
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   14</span> <span style="COLOR: blue">using</span> System.IO;
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   15</span> <span style="COLOR: blue">using</span> System.Linq;
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   16</span> <span style="COLOR: blue">using</span> System.Reflection;
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   17</span> <span style="COLOR: blue">using</span> System.Runtime.Serialization;
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   18</span> 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   19</span> <span style="COLOR: blue">class</span><span style="COLOR: #2b91af">Program</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   20</span> {
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   21</span>     <span style="COLOR: blue">static</span><span style="COLOR: blue">void</span> Main()
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   22</span>     {
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   23</span>         <span style="COLOR: #2b91af">Console</span>.WriteLine(
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   24</span>        
    <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">Program</span>().generate(
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   25</span>        
    <span style="COLOR: #a31515">"C:\\yourlinq.dll"</span>));
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   26</span>     }
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   27</span> 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   28</span>     <span style="COLOR: blue">string</span> generate(<span style="COLOR: blue">string</span> asmpath)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   29</span>     {
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   30</span>         <span style="COLOR: blue">var</span> asm
= <span style="COLOR: #2b91af">Assembly</span>.LoadFrom(asmpath);
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   31</span>         <span style="COLOR: blue">var</span> lines
= <span style="COLOR: blue">from</span> t <span style="COLOR: blue">in</span> asm.GetExportedTypes()
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   32</span>        
            <span style="COLOR: blue">let</span> ta
= getAttr&lt;<span style="COLOR: #2b91af">TableAttribute</span>&gt;(t)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   33</span>        
            <span style="COLOR: blue">where</span> ta
!= <span style="COLOR: blue">null</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   34</span>        
            <span style="COLOR: blue">let</span> name
= pluralize(ta.Name.Replace(<span style="COLOR: #a31515">"dbo."</span>, <span style="COLOR: #a31515">""</span>))
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   35</span>        
            <span style="COLOR: blue">orderby</span> name
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   36</span>        
            <span style="COLOR: blue">select</span> genTable(t,
name);
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   37</span>         <span style="COLOR: blue">return</span> joinStrings(<span style="COLOR: #a31515">""</span>,
lines);
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   38</span>     }
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   39</span> 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   40</span>     <span style="COLOR: blue">string</span> genTable(<span style="COLOR: #2b91af">Type</span> t, <span style="COLOR: blue">string</span> tableName)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   41</span>     {
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   42</span>         <span style="COLOR: blue">var</span> keyProps
=
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   43</span>        
    <span style="COLOR: blue">from</span> p <span style="COLOR: blue">in</span> t.GetProperties()
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   44</span>        
    <span style="COLOR: blue">let</span> c = getAttr&lt;<span style="COLOR: #2b91af">ColumnAttribute</span>&gt;(p)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   45</span>        
    <span style="COLOR: blue">where</span> c != <span style="COLOR: blue">null</span> &amp;&amp;
c.IsPrimaryKey
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   46</span>        
    <span style="COLOR: blue">let</span> dm = getAttr&lt;<span style="COLOR: #2b91af">DataMemberAttribute</span>&gt;(p)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   47</span>        
    <span style="COLOR: blue">orderby</span> dm == <span style="COLOR: blue">null</span> ?
0 : dm.Order
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   48</span>        
    <span style="COLOR: blue">select</span> p;
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   49</span>         <span style="COLOR: blue">var</span> tw
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">StringWriter</span>();
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   50</span>        
tw.WriteLine(<span style="COLOR: #a31515">"public static readonly TableHelper&lt;{0},
{1}&gt; {2} ="</span>,
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   51</span>        
    t.Name,
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   52</span>        
    joinStrings(<span style="COLOR: #a31515">", "</span>, keyProps.Select(p
=&gt; p.PropertyType.Name)),
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   53</span>        
    tableName);
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   54</span>        
tw.WriteLine(<span style="COLOR: #a31515">"\tCreateTable(dc =&gt; dc.{0}, {1});"</span>,
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   55</span>        
    tableName,
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   56</span>        
    joinStrings(<span style="COLOR: #a31515">", "</span>, keyProps.Select(p
=&gt; <span style="COLOR: #a31515">"a =&gt; a."</span> + p.Name)));
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   57</span>        
tw.WriteLine();
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   58</span>         <span style="COLOR: blue">return</span> tw.ToString();
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   59</span>     }
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   60</span> 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   61</span>     <span style="COLOR: blue">string</span> joinStrings(<span style="COLOR: blue">string</span> sep, <span style="COLOR: #2b91af">IEnumerable</span>&lt;<span style="COLOR: blue">string</span>&gt;
items)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   62</span>     {
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   63</span>         <span style="COLOR: blue">return</span><span style="COLOR: blue">string</span>.Join(sep,
items.ToArray());
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   64</span>     }
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   65</span>     <span style="COLOR: blue">string</span> pluralize(<span style="COLOR: blue">string</span> s)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   66</span>     {
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   67</span>         <span style="COLOR: blue">return</span> s.EndsWith(<span style="COLOR: #a31515">"s"</span>)
? s : s + <span style="COLOR: #a31515">"s"</span>;
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   68</span>     }
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   69</span> 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   70</span>     T
getAttr&lt;T&gt;(<span style="COLOR: #2b91af">ICustomAttributeProvider</span> icap)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   71</span>     {
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   72</span>         <span style="COLOR: blue">var</span> a
= icap.GetCustomAttributes(<span style="COLOR: blue">typeof</span>(T), <span style="COLOR: blue">true</span>);
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   73</span>         <span style="COLOR: blue">return</span> a.Length
== 0 ? <span style="COLOR: blue">default</span>(T) : (T)a[0];
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   74</span>     }
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   75</span> }
</p>
        </div>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=ae23e7f3-a43e-4bc5-90cc-12b2b74dff99" />
      </div>
    </content>
  </entry>
  <entry>
    <title>LINQ to the CRUD CreateTable generator in F#</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2008/06/26/LINQ+To+The+CRUD+CreateTable+Generator+In+F.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,d6d66155-c288-4984-b4ba-4e58285daf7f.aspx</id>
    <published>2008-06-26T01:13:44.078-04:00</published>
    <updated>2008-06-26T01:15:17.578125-04:00</updated>
    <category term="F#" label="F#" scheme="http://www.atrevido.net/blog/CategoryView,category,F%23.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
With the <a href="http://www.atrevido.net/blog/2008/06/26/LINQ+To+The+CRUD+RTM.aspx">DatabaseBase</a> and
TableHelper classes, you still have to generate a CreateTable field per table. Why
do it by hand? I wrote an F# script to generate the statements. I must say, I'm
loving F# more than I had hoped. The more I learn, the better it gets. I've noticed
(even in C#) that using a functional style generally means less errors. This script
worked without bugs the first time (i.e., as soon as it compiled), which is pretty
cool (granted, it's not big, but I'm sure if I had tons of for loops, I woulda messed
up somewhere). Maybe this weekend I'll try writing it in C# just to compare (pretty
sure it'll be more than 59 lines!). And I'll preempt comments about readability:
Yes, it may be difficult to read if you don't know F#, but more on that later...
</p>
        <p>
I'd love feedback as to making it more "functional"; years of imperative programming
don't die quickly. Also, I'm not very happy with the definition of chooseAttr, but
I can't seem to get it to infer the type I want otherwise.
</p>
        <p>
Anyways, here's the code. You'll need to specify the references when compiling:
-r "C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Linq.dll"
-r "C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\System.Runtime.Serialization.dll" 
</p>
        <p>
          <hr />
        </p>
        <p>
        </p>
        <div style="FONT-SIZE: 11pt; BACKGROUND: white; COLOR: black; FONT-FAMILY: Consolas">
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    1</span> <span style="COLOR: green">//
crudcreatetable.fsx: Generates LINQ CRUD table fields using the horribly named DatabaseBase
code</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    2</span> <span style="COLOR: green">//</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    3</span> <span style="COLOR: green">//
Tables look like: [Table(Name="dbo.Accounts")]</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    4</span> <span style="COLOR: green">//
Columns look like this:</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    5</span> <span style="COLOR: green">// 
[Column(Storage="_AccountName", DbType="VarChar(128) NOT NULL", CanBeNull=false, IsPrimaryKey=true)]</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    6</span> <span style="COLOR: green">// 
[DataMember(Order=1)] // Exists if serialization is turned on; used to order key parameters</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    7</span> <span style="COLOR: green">//
Emits:</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    8</span> <span style="COLOR: green">// 
public static readonly TableHelper&lt;Account, String&gt; Accounts =</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">    9</span> <span style="COLOR: green">//   
  CreateTable(dc =&gt; dc.Accounts, a =&gt; a.AccountName);</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   10</span> 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   11</span> #light
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   12</span> <span style="COLOR: blue">open</span> System
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   13</span> <span style="COLOR: blue">open</span> System.Reflection
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   14</span> <span style="COLOR: blue">open</span> System.Data.Linq.Mapping
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   15</span> <span style="COLOR: blue">open</span> System.Runtime.Serialization
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   16</span> 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   17</span> <span style="COLOR: blue">let</span> getAttr&lt;'target,
'a <span style="COLOR: blue">when</span> 'a :&gt; ICustomAttributeProvider&gt; (ty
: 'a) = 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   18</span>     <span style="COLOR: blue">match</span> List.of_array
(ty.GetCustomAttributes(typeof&lt;'target&gt;, <span style="COLOR: blue">true</span>)) <span style="COLOR: blue">with</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   19</span>        
| a::_ <span style="COLOR: blue">-&gt;</span> Some (a :?&gt; 'target)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   20</span>        
| [] <span style="COLOR: blue">-&gt;</span> None
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   21</span> <span style="COLOR: blue">let</span> chooseAttr&lt;'target,
'a <span style="COLOR: blue">when</span> 'a :&gt; ICustomAttributeProvider&gt; (ty
: 'a) = 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   22</span>     <span style="COLOR: blue">match</span> getAttr&lt;'target,_&gt;
ty <span style="COLOR: blue">with</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   23</span>        
| Some(a) <span style="COLOR: blue">-&gt;</span> Some(ty,a)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   24</span>        
| None <span style="COLOR: blue">-&gt;</span> None
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   25</span> 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   26</span> <span style="COLOR: blue">let</span> joinStrings
(sep:string) items = items |&gt; Seq.fold1 (<span style="COLOR: blue">fun</span> acc
x <span style="COLOR: blue">-&gt;</span> acc + sep + x) 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   27</span> <span style="COLOR: blue">let</span> pluralize
(name:string) = <span style="COLOR: blue">if</span> name.EndsWith(<span style="COLOR: #a31515">"s"</span>) <span style="COLOR: blue">then</span> name <span style="COLOR: blue">else</span> name
+ <span style="COLOR: #a31515">"s"</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   28</span> 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   29</span> <span style="COLOR: blue">let</span> generate(asmpath:string)
=
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   30</span>     <span style="COLOR: blue">let</span> genTable
(t:Type, tableName) =
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   31</span>         <span style="COLOR: blue">let</span> keyProps
= 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   32</span>        
    t.GetProperties() 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   33</span>        
    |&gt; Seq.choose (chooseAttr&lt;ColumnAttribute,_&gt;)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   34</span>        
    |&gt; Seq.filter(<span style="COLOR: blue">fun</span> (p,c) <span style="COLOR: blue">-&gt;</span> c.IsPrimaryKey)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   35</span>        
    |&gt; Seq.map(<span style="COLOR: blue">fun</span> (p,_) <span style="COLOR: blue">-&gt;</span> p,
getAttr&lt;DataMemberAttribute, _&gt; p)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   36</span>        
    |&gt; Seq.orderBy(<span style="COLOR: blue">function</span> | _,Some(dm) <span style="COLOR: blue">-&gt;</span> dm.Order
| _ <span style="COLOR: blue">-&gt;</span> 0)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   37</span>        
    |&gt; Seq.map (<span style="COLOR: blue">fun</span> (p,_) <span style="COLOR: blue">-&gt;</span> p)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   38</span>         <span style="COLOR: blue">let</span> tw
= <span style="COLOR: blue">new</span> IO.StringWriter()
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   39</span>         <span style="COLOR: blue">let</span> pn
fmt = Printf.twprintfn tw fmt
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   40</span>        
pn <span style="COLOR: #a31515">"public static readonly TableHelper&lt;%s, %s&gt;
%s ="</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   41</span>        
    t.Name 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   42</span>        
    (joinStrings <span style="COLOR: #a31515">", "</span> (keyProps
|&gt; Seq.map (<span style="COLOR: blue">fun</span> p <span style="COLOR: blue">-&gt;</span> p.PropertyType.Name)))
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   43</span>        
    tableName
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   44</span>        
pn <span style="COLOR: #a31515">"\tCreateTable(dc =&gt; dc.%s, %s);"</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   45</span>        
    tableName
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   46</span>        
    (joinStrings <span style="COLOR: #a31515">", "</span> (keyProps
|&gt; Seq.map (<span style="COLOR: blue">fun</span> p <span style="COLOR: blue">-&gt;</span><span style="COLOR: #a31515">"a
=&gt; a."</span> + p.Name)))
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   47</span>        
pn <span style="COLOR: #a31515">""</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   48</span>        
tw.ToString()
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   49</span> 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   50</span>     <span style="COLOR: blue">let</span> asm
= Assembly.LoadFrom asmpath <span style="COLOR: green">// Don't use ReflectionOnly
'cause it won't resolve dependencies</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   51</span>     asm.GetExportedTypes
() 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   52</span>        
|&gt; Seq.choose (chooseAttr&lt;TableAttribute,_&gt;)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   53</span>        
|&gt; Seq.map (<span style="COLOR: blue">fun</span> (t,ta) <span style="COLOR: blue">-&gt;</span> t,
ta.Name.Replace(<span style="COLOR: #a31515">"dbo."</span>, <span style="COLOR: #a31515">""</span>)
|&gt; pluralize)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   54</span>        
|&gt; Seq.orderBy (<span style="COLOR: blue">fun</span> (t,_) <span style="COLOR: blue">-&gt;</span> t.Name)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   55</span>        
|&gt; Seq.map genTable
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   56</span>        
|&gt; Seq.fold1 (+)
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   57</span> 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   58</span> generate <span style="COLOR: #a31515">"C:\\yourlinq.dll"</span></p>
          <p style="MARGIN: 0px">
            <span style="COLOR: #2b91af">   59</span>     |&gt;
Console.WriteLine
</p>
        </div>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=d6d66155-c288-4984-b4ba-4e58285daf7f" />
      </div>
    </content>
  </entry>
  <entry>
    <title>LINQ to the CRUD RTM</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2008/06/26/LINQ+To+The+CRUD+RTM.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,7fb8423f-ac62-49ae-a01a-e82517c602b0.aspx</id>
    <published>2008-06-26T00:56:24.03125-04:00</published>
    <updated>2008-06-26T00:56:24.03125-04:00</updated>
    <category term="Misc. Technology" label="Misc. Technology" scheme="http://www.atrevido.net/blog/CategoryView,category,Misc.%2BTechnology.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
[Reposting because it appears to have been deleted somehow.]
</p>
        <p>
A bit ago, I posted some info on doing CRUD operations using LINQ: <a href="http://www.atrevido.net/blog/2007/08/26/A+LINQ+To+The+CRUD.aspx">http://www.atrevido.net/blog/2007/08/26/A+LINQ+To+The+CRUD.aspx</a></p>
        <p>
This is a lightweight way (no codegen at all, only 2 lines of code per table) to get
some CRUD stuff with LINQ. It's not the most efficient or fantastic way of doing things,
but it works fine in the several projects we've used it so far. And we get to use
C# 3's expression trees, which is a fantastic and under-exploited feature. At
any rate, it does show that doing disconnected work with LINQ is trivial. 
</p>
        <p>
The code I posted was for Beta 2 and no longer works. I've since added a few new features,
but the basic idea remains the same as before. I'm just posting the new code as I've
gotten a few emails and one comment about the old code no longer working. 
</p>
        <p>
          <a href="http://www.atrevido.net/blog/content/binary/DatabaseBase.cs.txt">DatabaseBase.cs
(10.47 KB)</a>
        </p>
        <p>
While working on it in a real project, I started using our Tuple struct, so you'll
need that too:<br /><a href="http://www.atrevido.net/blog/content/binary/Tuple.cs.txt">Tuple.cs (2.8 KB)</a></p>
        <p>
As Scott Peterson pointed out, this class doesn't implement IEquatable&lt;T&gt;. Just
add it and call the == operator.
</p>
        <p>
As always I welcome any criticism. 
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=7fb8423f-ac62-49ae-a01a-e82517c602b0" />
      </div>
    </content>
  </entry>
  <entry>
    <title>The reason VB.NET is truly a second class citizen</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2008/03/31/The+Reason+VBNET+Is+Truly+A+Second+Class+Citizen.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,1613baf7-ed7e-4ecc-bd10-4106ea3c88bc.aspx</id>
    <published>2008-03-31T17:55:56.427-04:00</published>
    <updated>2008-03-31T18:06:22.2174807-04:00</updated>
    <category term="Code" label="Code" scheme="http://www.atrevido.net/blog/CategoryView,category,Code.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
No support for anonymous methods/lambda statements. I first realised this when
someone commented on one of my <a href="http://www.atrevido.net/blog/2007/08/26/A+LINQ+To+The+CRUD.aspx">functional
C#</a> postings, asking "how can I write this in VB"? Turns out VB has no support
for anonymous methods. <a href="http://www.paulstovell.com/blog/vbnet-wheres-actiont-support">Ouch.</a></p>
        <p>
This lack of capability rules out a so much functionality, I honestly cannot imagine
writing anything significant today using VB.NET. But with LINQ and F# making such
a big splashes, I have high hopes for the future of functional programming on the
.NET languages, and I'm sure VB.NET will get itself fixed up. 
</p>
        <p>
Really, dropping anonymous methods in favour of stuff like XML literals? Maybe that's
why it's listed as <a href="http://msmvps.com/blogs/bill/archive/2008/03/23/first-time-or-casual-programming.aspx">first
time or casual programming</a> ;). (No, I jest. Scheme is far better for first
time programming.)
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=1613baf7-ed7e-4ecc-bd10-4106ea3c88bc" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Empty WCF services references - no code generated</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2008/03/31/Empty+WCF+Services+References+No+Code+Generated.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,ddab93db-ef59-4084-ba60-aa7dba01412e.aspx</id>
    <published>2008-03-31T05:06:51.02525-04:00</published>
    <updated>2008-03-31T05:06:51.02525-04:00</updated>
    <category term="Code" label="Code" scheme="http://www.atrevido.net/blog/CategoryView,category,Code.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Usually I use WCF just by referencing the contracts directly and using my own <a href="http://www.atrevido.net/blog/2007/08/13/Practical+Functional+C+Part+II.aspx">generic
helper methods</a>. Unfortunately, I had to make use of the built-in async patterns
that the codegen can provide. Hence, I ended up using the "Add Service Reference"
dialog, which notices (unlike svcutil on the command line) that since I'm requesting
async, it'll need to generate my interfaces even though they're already referenced.
Maybe in .NET 4 we'll have a new async pattern that'll leverage Expression Trees to
rid us of having to use the rather ugly FooAsync/BeingFoo patterns. 
</p>
        <p>
Things were working just fine until I added a reference to a new service. Adding the
service reference didn't work; it failed silently. It added all the schema files to
the project, but the Reference.cs file was empty. If I told it to NOT used referenced
assemblies, then it generated everything just fine.
</p>
        <p>
After switching to the command line and using svcutil, I got these errors:<br /><font face="Courier New">Error: Cannot import wsdl:portType<br />
Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter<br />
Error: Referenced type 'MyApp.Management.CoolFunction.CoolThingRule, MyApp.Management.Contracts,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' with data contract name 'CoolThingRule'
in namespace 'http://schemas.MyApp.com/management/v2/00' cannot be used since it does
not match imported DataContract. Need to exclude this type from referenced types.XPath
to Error Source: //wsdl:definitions[@targetNamespace='http://schemas.MyApp.com/management/v2/00']/wsdl:portType[@name='ICoolThingManagement']</font></p>
        <p>
I regenerated without the referenced code and figured out that the problem was that
one type referenced an enum which had some values without the [EnumMember] attribute
(although it had a DataContractAttribute on the enum itself). Because of this, WCF
wanted to represent the enum with a string and thus was incompatible. Adding the EnumMemberAttribute
to all the values sorted out this issue.
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=ddab93db-ef59-4084-ba60-aa7dba01412e" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Hacking SOAP Faults into Silverlight 2 Beta 1</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2008/03/27/Hacking+SOAP+Faults+Into+Silverlight+2+Beta+1.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,ffa70c25-0c78-474b-8d60-10a693ffc407.aspx</id>
    <published>2008-03-27T03:19:36.46275-04:00</published>
    <updated>2008-03-27T03:19:36.46275-04:00</updated>
    <category term="Code" label="Code" scheme="http://www.atrevido.net/blog/CategoryView,category,Code.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Silverlight 2 is pretty nice. Compared to dealing with the nightmare of HTML, CSS,
AJAX and whatever else, it's quite divine. Of particular interest is that Silverlight
2 has a mini Windows Communication Foundation stack that can do basic SOAP work (and
some "Web 2.0" type things too I think). While the SL WCF stack works pretty well
overall, it doesn't support SOAP faults.
</p>
        <p>
First off, SOAP faults usually cause the server to return an HTTP 500. For whatever
reasons, this isn't handled correctly between the browser and Silverlight, and results
in an UnexpectedHttpResponseCode. OK, so go into the Global.asax and in Application_EndRequest
change 500s to 200s. [Yes, this requires that you run WCF with AspNetCompatibility.]
</p>
        <p>
Some progress. Silverlight now gives a more useful exception:
</p>
        <p>
          <font face="Courier New">Error: System.Runtime.Serialization.SerializationException:
OperationFormatter encountered an invalid Message body. Expected to find node type
'Element' with name 'MyFunctionResponse' and namespace 'http://schemas.contoso.com/coolservice/v2/00'.
Found node type 'Element' with name 's:Fault' and namespace 'http://schemas.xmlsoap.org/soap/envelope/'</font>
        </p>
        <p>
Hmm, it's getting the fault, but can't seem to handle it. I tried adding typed faults
to my WCF contract, but the SL WCF stack doesn't have the FaultContractAttribute.
It appears as if SL cannot read faults at all.
</p>
        <p>
Enter HackFaults. That message provides two pieces of data from the SOAP message,
the element name, and the namespace. We can hijack these to pass our fault information,
then extract it from the exception message. H to the A to the C-K-Y.
</p>
        <p>
First off, we need to get access to our WCF fault. We can do this with an System.ServiceModel.Dispatcher.IErrorHandler.
I've attached the full code, but basically you add an attribute to your WCF service
to wire up the error handler. If you're doing WCF work, you probably want this
anyways for logging purposes and so on. I've attached the entire error handler code
to this article. The real meat of the error handler is this little function:
</p>
        <p>
          <font size="3">
            <span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">
              <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">public</span>
              <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">void</span> ProvideFault(Exception
error, MessageVersion version, <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">ref</span> Message
fault)<br />
{<br />
    <span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">//
HackFaults store the exception in the httpcontext</span><br />
    var context <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> System.Web.HttpContext.Current;<br />
    <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">if</span> (context
!<span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">null</span>)
{ 
<br />
        <span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">//
Only works in AspNetCompat mode</span><br />
        <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">if</span> (!context.Request.Browser.Crawler
&amp;&amp; context.Request.Browser.EcmaScriptVersion.Major &gt; 0) {<br />
            <span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">//
This should rule out non-browsers</span><br />
            context.Items.Add(<span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">"HackFault"</span>,
error);<br />
        }<br />
    }<br />
}<br /></span>
          </font>
        </p>
        <p>
I'm not sure if there's a better way to differentiate between browsers and real SOAP
stacks. If there is let me know. Now, in our Global.asax, we want to pick this information
up and replace the actual SOAP fault with our own hackfault:
</p>
        <pre>
          <span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">
            <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">protected</span>
            <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">void</span> Application_EndRequest(<span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">object</span> sender,
EventArgs e) { <span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">//
In all fairness, I was drinking eiswein at the time</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">if</span> (Context.Items.Contains(<span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">"HackFault"</span>))
{ Context.Response.ContentType <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span><span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">"text/xml"</span>;
Context.Response.StatusCode <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> 200;
Context.Response.ClearContent(); var hackEx <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> Context.Items[<span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">"HackFault"</span>] <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">as</span> Exception;
var hackFaultXml <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">string</span>.Format( <span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">"&lt;s:Envelope
xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"&gt;&lt;s:Body&gt;&lt;{0} xmlns=\"{1}\"
/&gt;&lt;/s:Body&gt;&lt;/s:Envelope&gt;"</span>, hackEx.GetType().ToString(), Context.Server.HtmlEncode(hackEx.Message));
Context.Response.Output.Write(hackFaultXml); } } </span>
        </pre>
        <p>
Now we have a message that has the bits of data we care about in the right places
for the Silverlight exception to be ready for parsing. The SL-side parsing
code is vile but easy:
</p>
        <pre>
          <span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">
            <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">public</span>
            <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">static</span>
            <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">string</span> ExtractHackFaultMessage(<span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">this</span> Exception
ex) { <span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">//
HackFaults generate these Exceptions and messages:</span><span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">//Without
debug:</span><span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">//Could
not connect to server: System.Runtime.Serialization.SerializationException: [SFxInvalidMessageBody]</span><span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">//Arguments:FaultException,Something
silly</span><span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">//With
debug:</span><span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">//Could
not connect to server: System.Runtime.Serialization.SerializationException: 
<br /></span></span>
          <span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">
            <span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">OperationFormatter
encountered an invalid Message body. Expected to find node type 'Element' with 
<br />
name 'SomeOperationResponse' and namespace 'http://schemas.cool.com/yea/v2/00'. 
<br />
Found node type 'Element' with name 'FaultException' and namespace 'Something silly'</span>
            <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">if</span> (!(ex <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">is</span> System.Runtime.Serialization.SerializationException)) <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">return</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">null</span>;
var msg <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> ex.Message; <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">string</span> regexp; <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">if</span> (msg.Contains(<span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">"[SFxInvalidMessageBody]"</span>))
{ regexp <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span><span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">@"Arguments:(.*),(.*)"</span>;
} <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">else</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">if</span> (msg.Contains(<span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">"OperationFormatter
encountered an invalid Message body"</span>)) { regexp <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span><span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">@"Found
node type 'Element' with name '(.*)' and namespace '(.*)'"</span>; } <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">else</span> { <span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">//
Nope, it's some thing else</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">return</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">null</span>;
} var match <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> System.Text.RegularExpressions.Regex.Match(msg,
regexp); <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">if</span> (match.Groups.Count
!<span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> 3) <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">return</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">null</span>; <span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">//
Not expected</span> var exType <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> match.Groups[1].Value.Trim();
var exMsg <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> match.Groups[2].Value.Trim(); <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">if</span> (exType
== <span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">"System.ServiceModel.FaultException"</span>) <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">return</span> exMsg; <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">else</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">return</span> exType+ <span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">":
"</span><span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">+</span> exMsg;
}</span>
        </pre>
        <p>
This little function will give me the fault information (and not mention FaultException
if that's what it is) or null if it can't extract it. When dealing with errors, I
can show an error like this: "Error: " + (ex.ExtractHackFaultMessage() ?? ex.ToString())
</p>
        <p>
This gives me at least rudimentary error reporting from the server back to Silverlight.
If this can be improved or fixed up, please tell me. (Typed fault exceptions would
be nice, but then SL can't codegen the contracts.) At any rate, it works as a cheap
hack until Silverlight Beta 2 (they gotta fix it by then, right? Right?).
</p>
        <a href="http://www.atrevido.net/blog/content/binary/HttpErrorHandler.cs.txt">HttpErrorHandler.cs.txt
(2.49 KB)</a>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=ffa70c25-0c78-474b-8d60-10a693ffc407" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Medical and General Security</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2008/03/12/Medical+And+General+Security.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,7961bd99-f48a-4d9a-a13c-b7ba9c07ff61.aspx</id>
    <published>2008-03-12T19:56:44.10975-04:00</published>
    <updated>2008-03-12T19:56:44.10975-04:00</updated>
    <category term="Security" label="Security" scheme="http://www.atrevido.net/blog/CategoryView,category,Security.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <strong>Nothing surprising</strong>
        </p>
        <p>
I've been waiting for this: <a href="http://www.nytimes.com/2008/03/12/business/12heart-web.html?_r=2&amp;ref=technology&amp;oref=slogin&amp;oref=slogin">http://www.nytimes.com/2008/03/12/business/12heart-web.html?_r=2&amp;ref=technology&amp;oref=slogin&amp;oref=slogin</a></p>
        <p>
Certain pacemakers (Medtronic in this case) are easy to reprogram without any useful
authentication. The result is that an attacker can kill someone remotely by modifying
their pacemaker. 
</p>
        <p>
This certainly will not be the first time this happens. The response from Medtronic
is idiotic:
</p>
        <p>
"<em>To our knowledge there has not been a single reported incident of such an event
in more than 30 years of device telemetry use, which includes millions of implants
worldwide</em>"
</p>
        <p>
It's funny seeing industries that typically have little to no security requirements
in their products get rudely awakened. Another vendor, St. Jude, says something equally
scary:
</p>
        <p>
"<em>used “proprietary techniques” to protect the security of its implants and had
not heard of any unauthorized or illegal manipulation of them</em>"
</p>
        <p>
Who wants to bet there's some globally shared key at work? At any rate, we expected
this kind of stuff because too many people can't think clearly about security (I'll
be writing about [the lack of] VoIP security soon). 
</p>
        <p>
          <strong>A growing problem</strong>
        </p>
        <p>
How should these devices secured in the first place? I'm not talking specifically
about pacemakers, but all sorts of implants and enhancements that we will have
during the next years, using security technology today.
</p>
        <p>
First, they need to be remotely monitored. This is relatively easy to secure, as the
risk is considerably less: information disclosure. For example, if each monitoring
device had to have it's public key explicitly trusted for a particular patient, that'd
be pretty easy. In the case that a key was disclosed (say, by capturing and attacking
a monitoring device), the only access gained is read-only. 
</p>
        <p>
Making it even less risk, it's possible that the amount of effort required for such
an attack exceeds the value of the information gained. For example, if an attacker
can access a target's house, they could steal identification and request medical records
be sent to them. 
</p>
        <p>
More importantly is editing of configuration. How do we determine who has access?
In theory, we want any qualified medical professional to be able to change configuration
in case of an emergency. Without a global network connected to the device, the device
has no way to validate credentials, particularly revocation. Additionally, even assuming
that every device has access to a global database, there would be too many authorised
users to ensure security. (Just like large government databases.)
</p>
        <p>
Is this a threat? Some people may think this is a far fetched idea. Certainly today
this is not a widespread fear. It may be a neat way to carry off a attack against
a single target, but I doubt it'd be effective for major attacks. But how long will
it be until a large percentage of the population carries some kind of embedded device?
Pacemakers, medicine delivery systems, vision implants, hearing, digestive -- the
list goes on. 
</p>
        <p>
The bottom line is that humans will carry more embedded technology, and this technology
must be secure *and* accessible. A system where losing your private key means surgery
is not usuable.
</p>
        <p>
          <strong>The easy solution</strong>
        </p>
        <p>
As far as I can tell, the only solid way to ensure security with today's technology
is to add a hard link. In order for anyone to modify configuration, the configuration
device must establish itself over a physical connection. This ensures no remote attacks
are possible. This would take away little to no convenience -- before editing yourself,
you'd have to let them physically connect a device to you. 
</p>
        <p>
The same could be done for remote devices. Let's say your doctor wants to adjust your
body remotely. You'd simply key the remote device[s] to your doctor, and key yourself
to the remote device[s]. You've established a chain of trust that's easy to clear
and recreate later. There is no global database, simply yourself and devices you touch. 
</p>
        <p>
This mimics what you have in the real world: You trust your doctor after you establish
a relationship with him. You can then call him on the phone and you trust his advice
to take more or less of the medicine. 
</p>
        <p>
A quick note on the details: The medical devices themselves don't need hard lines
to the hard configuration interface. Indeed, your "hard link" could be a special device
keyed to yourself. However, embedding this device into the body means you won't lose
it and it'll be readily accessible to medical teams, even if you're unconscious. 
</p>
        <p>
To protect against damage to the hard link device, I suppose a backup key could be
made authorized. You could then store it safe, by yourself (as in, with a bank's security
deposit box, <em>not</em> the database of the device manufacturer). 
</p>
        <p>
          <strong>The general solution</strong>
        </p>
        <p>
However, this only secures us as much as we can trust the authentication. But it still
relies on manual revocation and trust editing. It may be acceptable to Verisign when
they accidentally issue a certificate in Microsoft's name to an attacker, but it is
not acceptable for humans. Specifically, in a short vulnerability window, you could
die. 
</p>
        <p>
The real solution, and one that we're going to need eventually across all technology,
is intelligence. Specifically, a machine intelligence that determines if what is happening
or what is requested is dangerous. This is the only way that we will have security
moving forward. 
</p>
        <p>
This kind of intelligence is what we use to protect ourselves now. If the water comes
out glowing green, we decide we won't trust it, even though we do trust (in general)
our public water system. If you see your doctor and he recommends moving from 5mg
to 500mg of Xanax a day, you'll immediately revoke his trust. 
</p>
        <p>
Attacks will adopt this kind of intelligence. A hacker uses a vulnerability to gain
access and then attack other systems from there. How long will it be until attacking
programs themselves replace the work done by the hacker? 
</p>
        <p>
Our software and machines will have to adopt this kind of intelligence to thwart such
attacks. It will no longer be "oh, sorry you got hit by malicious code from clicking
on a hyperlink, please reinstall your OS". As long as humans can be killed by the
devices in use, the stakes are too high for even tiny vulnerability windows.
</p>
        <p>
 
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=7961bd99-f48a-4d9a-a13c-b7ba9c07ff61" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Writing events with System.Diagnostics.Eventing </title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2008/02/28/Writing+Events+With+SystemDiagnosticsEventing.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,1b0c68ce-d168-4210-86fb-4f2b2126bfc0.aspx</id>
    <published>2008-02-28T16:12:25.9-05:00</published>
    <updated>2008-02-28T16:12:25.9-05:00</updated>
    <category term="Code" label="Code" scheme="http://www.atrevido.net/blog/CategoryView,category,Code.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
... or, how the hell to use Vista and 2008's new ETW stuff with managed code. And,
introducing ecmanaged: A decent way to do all this stuff.<br /><br /><strong>Quick ETW Overview</strong></p>
        <p>
Actually, the real ETW overview is here: <a href="http://msdn.microsoft.com/msdnmag/issues/07/04/ETW/">http://msdn.microsoft.com/msdnmag/issues/07/04/ETW/</a> &lt;--
This is some of the best overview and documentation on it (the other good stuff is
the ecmangen documentation in the Windows SDK bin folder). The MSDN stuff is terribly
confusing for the most part. Or maybe I'm too spolied by how easy it is to find stuff
in the BCL. My overview is on what you gotta do to make things work in .NET.
</p>
        <p>
This first part is somewhat ranty. After you spend over a day trying to sort it out,
you'd probaby feel not-so-happy too (although it is somewhat tounge-in-cheek). Also,
I hope I'm wrong and I'm just missing some obvious stuff. PLEASE correct me.
</p>
        <p>
You'd think with .NET 3.5's System.Diagnostics.Eventing namespace, getting going with
all the slick new Event Tracing for Windows stuff in Windows 6 would be a piece of
cake. There's an entire namespace dedicated to it! Of COURSE it should be very easy.
Wrong. Apparently the Eventing stuff was done by the Windows team. First off, we know
they hate managed developers. See Table-1:
</p>
        <table>
          <tbody>
            <tr>
              <td>
              </td>
              <td>
                <font size="2">Abstraction</font>
              </td>
            </tr>
            <tr>
              <td>
                <font size="2">Physics 'n' shit</font>
              </td>
              <td>
                <font size="2">10</font>
              </td>
            </tr>
            <tr>
              <td>
                <font size="2">x86 Assembly</font>
              </td>
              <td>
                <font size="2">200</font>
              </td>
            </tr>
            <tr>
              <td>
                <font size="2">Usual C coding</font>
              </td>
              <td>
                <font size="2">210</font>
              </td>
            </tr>
            <tr>
              <td>
                <font size="2">Functional .NET app</font>
              </td>
              <td>
                <font size="2">4000</font>
              </td>
            </tr>
          </tbody>
        </table>
        <p>
See, writing in poor languages is closer to quantum electrodynamics than making .NET
apps. Complaining things weren't one-click easy doesn't work here. Even
worse, I think ETW has something to do with the kernel or driver teams (I'm basing
this off that half of the confusing documentation seems to show up in that part of
MSDN -- or maybe there's some similarly named other tracing stuff). A typical day
in that area consists of running hardware debugggers while sitting inside a Faraday
cage then waiting the rest of the day for a compile to complete to try a fix out.
(Not to mention that HR says that sitting in a Faraday cage lowers your radition intake
and thus counts as health benefit.) So, don't even start to tell such souls how difficult
YOUR work is because you had to manually delete bin and obj directories because VS's
clean function doesn't work -- they're happy they dont have to manually position hard
drive heads.
</p>
        <p>
Even so, ETW starts off looking really promising. You define everything in a nice
XML manifest file, and everything is based off that. But wait, everything? Shouldn't
the manifest be the end-all? Yea, that'd make logical sense. No, you run some tools
from the Windows SDK. First you run MC, which generates a .h header file. Managed
devs are growning now -- why the hell should something as general as event tracing
be language specific? The .h file contains the processed event descriptors, ready
for C consumption. 
</p>
        <p>
It worsens: MC also generated a resource script. You have to compile that with
RC and it'll create a Win32 .res resource. Then you compile that into a binary (the
C# compiler has the /win32res option). Then you go back and edit your XML manifest
and make sure it points to the final binary. Wait, what? Yes. The resources that MC
generates for RC contain all the messages that are in your XML manifest. Someone thought
it was a really cute idea to go and make the Event Viewer not only read all the data
from your manifest, but also have to go look it up from some binary resources. 
</p>
        <p>
Actually, this probably made sense to someone on the Windows team since I'm guessing
they already have tools to go and localise Win32 resources or something. Unfortunately,
it sucks and makes no sense for anyone NOT in their particular position. Now,
I hope I'm wrong (I really, really want to be wrong), but I think there's no way to
force the message strings to just stay in the XML file and be read from there. 
</p>
        <p>
Finally, things get easy again. Just run "wevtutil install-manifest Some.man" (wevtutil
is in system32). In fact, this utility is so user friendly, it even lets you type
"im" instead of "install-manifest". At this point, assuming the other steps went well,
your provider shows up in Event Viewer.
</p>
        <p>
          <strong>ECManGen</strong>
        </p>
        <p>
But wait, how do I actually make that manifest? This part is almost the easiest.
In the Windows SDK, there's a lovely little tool called ECManGen. Just fire it up,
and go to town adding Providers, Channels, Templates, and Events. 
</p>
        <p>
Providers are the main things that show up in your Event Viewer, such as MyApp-FooProduct-LameComp.
Channels separate Admin/Operational/Debug and others. Templates are an argument list
for Events. If you have, say, a bunch of events that take the same kinds of parameters,
you can share templates among them (I find it helpful to create a "SingleStringTemplate".)
It's very straightforward.
</p>
        <p>
*Note: I can't actually get Admin channels to work. If I create an event and stick
it in an Admin channel and set its level to Informational, MC complains (as does ECManGen)
that the level has to be Critical, Error, or Informational. Uh, OK. Instead, just
use Operational.
</p>
        <p>
Except... ECManGen is a free utility. (Free? Perhaps not, seeing as the annual MS
bill for a 4-person dev team is around $20,000 (counting just MSDN) -- but it's well
worth it.) Part of the docs say: "NOTE: For the Manifest Generator Tool to function
correctly, the file winmeta.xml (which contains pre-defined metadata values) must
either be in the Include directory of the SDK or in the same directory as the Manifest
Generator tool." OK, easy enough. Except... it doesn't work that easily. The only
way I got it to work was to copy the xml file over to the same directory, *and* start
ECManGen from that directory. 
</p>
        <p>
Oh yea, ECManGen won't open your manifest file if you pass it as an argument, so forget
about cute VS integration. Just Google ecmangen and go rate up the bugs on Connect
:).
</p>
        <p>
          <strong>Going Managed</strong>
        </p>
        <p>
OK, so you're not living in the last century and use decent tools -- how does this
map to C#? First off, you create an EventProvider with the right Guid (the one from
your manifest). Then you create an EventDescriptor for each event, matching up all
the little parameters (the MSDN docs for EventDescriptor have more details). Finally,
you can call WriteEvent, passing the EventDescriptor *by ref* for some reason (no,
I can't figure out why). 
</p>
        <p>
Oh yea, and you have to hookup that Win32 resource to your C# project, so if you needed
another resource (like another app manifest?), you'll have to go deal with merging
them and all that hassle. And, don't forget to make sure the parameters you pass into
the object[] array of WriteEvent line up with what your manifest has. And also,
the .NET API won't even handle the Boolean-&gt;BOOL (4 byte) silliness for you. 
</p>
        <p>
In summary, it's a lot of boring, error-prone work, and you'll have to repeat
it every time you edit your manifest. Yuck. Maybe it's just easier to use the old
event log stuff and forget about all this fancy ETW stuff.
</p>
        <p>
However, the ETW features are pretty cool. As is ecmangen (well, for the most part).
I couldn't tear myself away from the promises the new ETW stuff offered, so I sat
down and wrote a hack tool to do everything for me. The goal is to have an XML file,
then convert it right into a DLL I can use. 
</p>
        <p>
ecmanaged does exactly this. Sorta. It doesn't deal with complicated scenarios or
performance counters, but handles straightforward event logging with templates in
an easy and type-safe fashion. 
</p>
        <p>
          <strong>Using ecmanaged</strong>
        </p>
        <p>
          <font face="Courier New">Usage: ecmanaged ecgen &lt;manifest&gt; /out:&lt;target assembly&gt;
/namespace:&lt;target namespace&gt; /class:&lt;target class&gt;<br />
Usage: ecmanaged msglocate &lt;manifest&gt; &lt;messageFileName&gt;<br />
Usage: ecmanaged install &lt;manifest&gt; &lt;targetManifest&gt; &lt;messageFileName&gt;<br />
Usage: ecmanaged uninstall &lt;targetManifest&gt;</font>
          <br />
        </p>
        <p>
Call ecgen with a manifest, and it'll go build an assembly with the wrappers for calling
your provider events. It'll stick the Win32 resource on the assembly too, so it's
ready to be used. 
</p>
        <p>
Call msglocate with the manifest and the message binary file, and it'll go fix the
manifest to point to the right place.
</p>
        <p>
Call install, and it'll copy the manifest to another location, fix the msg location,
and call wevtutil on it. It copies because I'm assuming your original manifest is
under source control, and hence shouldn't be fixed up.
</p>
        <p>
Uninstall just calls wevutil uninstall-manifest.
</p>
        <p>
        </p>
        <p>
          <font size="3">
            <font size="2">Yey! Now you can just make a batch file to call this
on your manifest and run it every time you change your manifest. What I do is stick
this in a folder in my project called "Eventing". I check the resulting binary into
source control (just like a 3rd party DLL). The downside is making sure you always
update the DLL if you modify the manifest. I'm sure somehow msbuild can come to the
rescue (and autoupdate when the manifest changes, so Intellisense keeps working),
but this works for me.</font>
          </font>
        </p>
        <p>
          <font size="3">
            <font size="2">I welcome all comments/questions/insults, but please,
no death threats. Download: <a href="http://www.atrevido.net/blog/content/binary/ecmanaged.exe">ecmanaged.exe
(45 KB)</a></font>
          </font>
        </p>
        <p>
          <font size="3">
            <font size="2">P.S. No, I don't hate Windows or the devs on it, although
I hate unmanaged code (it IS 2008, innit?). Perhaps I'm just annoyed I have to
make a Saving Throw versus Hang every time I click Send in Outlook 2007 (yes, patched
up, even with Vista SP1... which made it worse). But I still think this whole ETW
toolchain is terribly unpolished.</font>
          </font>
        </p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=1b0c68ce-d168-4210-86fb-4f2b2126bfc0" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Access is denied when starting Windows Event Log on Vista</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2007/12/10/Access+Is+Denied+When+Starting+Windows+Event+Log+On+Vista.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,e9df149a-a795-4a25-a95b-957ba6201e43.aspx</id>
    <published>2007-12-10T10:18:17.073125-05:00</published>
    <updated>2007-12-10T10:18:17.073125-05:00</updated>
    <category term="Misc. Technology" label="Misc. Technology" scheme="http://www.atrevido.net/blog/CategoryView,category,Misc.%2BTechnology.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
I ran into a strange problem today. The Windows Event Log service would not start,
stating an error code 5 "Access is denied". This doesn't make any sense as running
the services MSC requires elevated permissions and I'm an administrator. That error
message alone didn't give me too much of a clue, especially because I don't know much
about the event log service. Also, as the event log service was down, troubleshooting
it required a bit more work than usual since I couldn't just turn to the event log. 
</p>
        <p>
Fortunately, Vista's ETW (Event Tracing for Windows) provided an easy solution. At
a command prompt, I ran "logman query providers". This shows a list of all the installed
tracing providers on the system. The interesting one in this case is "Microsoft-Windows-Eventlog".
Using this information I could start a trace and generate a report. The report indicated
that access was denied creating the System channel. It mentioned a path it was trying
to use: %SystemRoot%\system32\winevt\logs\System.evtx
</p>
        <p>
I checked the permissions and they looked ok (SYSTEM had full control). So I renamed
the System log and gave permissions to everyone on the folder. Then I started the
Event log service and it worked fine. It created a new System.evtx. When I checked
the permissions I saw that Event log service runs as local system. Apparently that
must be the security required. After resetting the permissions, everything seems to
be working fine.
</p>
        <p>
I'm posting this since when I searched for a solution, I found several people asking
and no answers. This could be the solution for other people. I'd like to hear if anyone
knows what might have caused this mess in the first place.
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=e9df149a-a795-4a25-a95b-957ba6201e43" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Complicated functions in LINQ to SQL</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2007/09/06/Complicated+Functions+In+LINQ+To+SQL.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,f9e4d1ef-8fff-4f44-8d9f-248bfc498e60.aspx</id>
    <published>2007-09-06T09:56:54.769-04:00</published>
    <updated>2007-09-06T10:00:48.910375-04:00</updated>
    <category term="Code" label="Code" scheme="http://www.atrevido.net/blog/CategoryView,category,Code.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Rob Conery talks about geocoding with LINQ <a href="http://blog.wekeroad.com/2007/08/30/linq-and-geocoding/">here</a>.
In his post, he provides some code using the <a href="http://en.wikipedia.org/wiki/Haversine_formula">Haversine
formula</a> to compute the distance between two points on earth. His function is declared
as: 
</p>
        <p style="BACKGROUND: white">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: #2b91af; BACKGROUND-COLOR: #eeece1">Func</span>
            <span style="COLOR: black; BACKGROUND-COLOR: #eeece1">&lt;</span>
            <span style="COLOR: blue; BACKGROUND-COLOR: #eeece1">double</span>
            <span style="COLOR: black; BACKGROUND-COLOR: #eeece1">, </span>
            <span style="COLOR: blue; BACKGROUND-COLOR: #eeece1">double</span>
            <span style="COLOR: black; BACKGROUND-COLOR: #eeece1">, </span>
            <span style="COLOR: blue; BACKGROUND-COLOR: #eeece1">double</span>
            <span style="COLOR: black; BACKGROUND-COLOR: #eeece1">, </span>
            <span style="COLOR: blue; BACKGROUND-COLOR: #eeece1">double</span>
            <span style="COLOR: black; BACKGROUND-COLOR: #eeece1">, </span>
            <span style="COLOR: blue; BACKGROUND-COLOR: #eeece1">double</span>
            <span style="COLOR: black">
              <span style="BACKGROUND-COLOR: #eeece1">&gt;
CalcDistance = (lat1, lon1, lat2, lon2) =&gt; …</span>
              <span style="FONT-SIZE: 12pt">
              </span>
            </span>
          </span>
        </p>
        <p>
Further, this delegate is wrapped in a normal C# method. Now, read my previous post
about <a href="http://www.atrevido.net/blog/2007/09/05/Calling+Custom+Methods+In+LINQtoSQL.aspx"><span style="FONT-SIZE: 12pt; FONT-FAMILY: Consolas">calling
functions in LINQ to SQL</span></a>. Can you see where things are going to go wrong?
That's right, a normal delegate or method can't be converted into SQL by LINQ, as
the engine has nothing to work with. Only when our code is available as <em>data</em> can
the LINQ to SQL engine do it's magic. Since there's some insinuation that LINQ to
SQL just can't handle things like Haversine, I'll demonstrate how to do it. 
</p>
        <p>
If you want to use your own "complicated" functions with LINQ to SQL, you'll need
to manually construct the predicate expression. It's not pretty, but, it does let
you convert somewhat detailed functions, such as Haversine, inside of LINQ-to-SQL
queries. This is not always the right approach: in some cases it'll be better to use
a UDF or stored procedure. (If someone knows a native, better way, please let me know! <a href="http://tomasp.net/articles/dynamic-linq-queries.aspx">TomasP's
Expandable stuff looks cool</a>, but I ran into some bugs on Beta 2. This is really
something the compiler should help out with!). 
</p>
        <p>
To start off, we need to declare our function as an Expression Tree (I cannot vouch
for the accuracy of this code; I'm merely demonstrating LINQ to SQL technique. For
the geocoding details, read Rob's post.): 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: blue">const</span>
            <span style="COLOR: blue">double</span> R
= 6367; 
<br /><span style="COLOR: blue">const</span><span style="COLOR: blue">double</span> RAD
= <span style="COLOR: #2b91af">Math</span>.PI / 180; 
<br /><span style="COLOR: blue">static</span><span style="COLOR: #2b91af">Expression</span>&lt;<span style="COLOR: #2b91af">Func</span>&lt;<span style="COLOR: blue">double</span>, <span style="COLOR: blue">double</span>, <span style="COLOR: blue">double</span>, <span style="COLOR: blue">double</span>, <span style="COLOR: blue">double</span>&gt;&gt;
dist = 
<br /></span>
          <span style="FONT-FAMILY: Consolas">(lat1, lon1, lat2, lon2) =&gt;<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span>R
* 2 *<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span>(<br /><span style="COLOR: #2b91af"><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span></span></span>Math</span>.Asin(<span style="COLOR: #2b91af">Math</span>.Min(1,<span style="COLOR: #2b91af">Math</span>.Sqrt(<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af"><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span>    <span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span></span></span>(<br /><span style="COLOR: #2b91af"><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af"><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span>    <span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span></span></span>Math</span>.Pow(<span style="COLOR: #2b91af">Math</span>.Sin(((lat1
* RAD - lat2 * RAD)) / 2.0), 2.0) +<br /><span style="COLOR: #2b91af"><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span></span></span>Math</span>.Cos(lat1
* RAD) * <span style="COLOR: #2b91af">Math</span>.Cos(lat2 * RAD) *<br /><span style="COLOR: #2b91af"><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af"><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span>    <span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span></span></span>Math</span>.Pow(<span style="COLOR: #2b91af">Math</span>.Sin(((lon1
* RAD - lon2 * RAD)) / 2.0), 2.0) <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af"><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span>    <span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span></span></span>) <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span></span></span>))) <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: #2b91af">    </span></span>); </span>
        </p>
        <p>
OK, that was the easy part. We just had to wrap Expression&lt;&gt; around the
type declaration and remove the method calls. But how do we pass this to our query?
The Where method has this signature: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: blue">public</span>
            <span style="COLOR: blue">static</span>
            <span style="COLOR: #2b91af">IQueryable</span>&lt;TSource&gt;
Where&lt;TSource&gt;(<span style="COLOR: blue">this</span><span style="COLOR: #2b91af">IQueryable</span>&lt;TSource&gt;
source, <span style="COLOR: #2b91af">Expression</span>&lt;<span style="COLOR: #2b91af">Func</span>&lt;TSource, <span style="COLOR: blue">bool</span>&gt;&gt;
predicate); </span>
        </p>
        <p>
Hence, we need to provide a predicate of <span style="FONT-FAMILY: Courier New">Expression&lt;Func&lt;TSource,
bool&gt;&gt;</span> for it do its magic. To work with expressions, we need to start
using the <span style="FONT-FAMILY: Courier New">System.Linq.Expressions</span> namespace.
For more clarity, I aliased <span style="FONT-FAMILY: Courier New">E</span> to <span style="FONT-FAMILY: Courier New">System.Linq.Expressions.Expression</span>.
Building expressions isn't particularly <em>hard</em>, it's just annoying and time
consuming. C#'s lack of "symbolics", or a way to use the compiler to create expressions
to reference properties, etc. means we have to use strings to do so. I never did claim
it'd be pretty. 
</p>
        <p>
We start off with some data from elsewhere in our application. In my example, I'm
just going to declare some locals: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: blue">double</span> coolLat
= 43.641852; 
<br /><span style="COLOR: blue">double</span> coolLong = -79.387298; 
<br /><span style="COLOR: blue">double</span> maxDist = 100; </span>
        </p>
        <p>
The first <span style="FONT-FAMILY: Courier New">Expression</span> we need is a <span style="FONT-FAMILY: Courier New">ParameterExpression</span> to
refer to the source item from the table (i.e., the parameter the Where method is going
to give to us). In my code, my table is called Accounts, hence my object type is Account.
To create the parameter expression: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: blue">var</span> acctParam
= <span style="COLOR: #2b91af">E</span>.Parameter(<span style="COLOR: blue">typeof</span>(<span style="COLOR: #2b91af">Account</span>), <span style="COLOR: #a31515">"a"</span>); </span>
        </p>
        <p>
Next, we need to be able to reference the fields in the table. With LINQ to SQL, these
are properties on our object. We create them like this: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: blue">var</span> acctLon = <span style="COLOR: #2b91af">E</span>.Property(acctParam, <span style="COLOR: #a31515">"Longitude"</span>);<br /><span style="COLOR: blue">var</span> acctLat = <span style="COLOR: #2b91af">E</span>.Property(acctParam, <span style="COLOR: #a31515">"Latitude"</span>); </span>
        </p>
        <p>
The secret sauce is creating the invoke to our <span style="FONT-FAMILY: Courier New">dist</span> expression.
This is where all the work comes into play and includes all our complicated code in
the LINQ to SQL query. Fortunately, after building up our arguments separately, it's
not that hard: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: blue">var</span> distCalc
= <span style="COLOR: #2b91af">E</span>.Invoke(dist, <span style="COLOR: #2b91af">E</span>.Constant(coolLat), <span style="COLOR: #2b91af">E</span>.Constant(coolLong),
acctLat, acctLon); </span>
        </p>
        <p>
We have to use <span style="FONT-FAMILY: Courier New">ConstantExpression</span>s for
our local variables. Using constant allows us to capture the value of those variables.
Now we're ready to finish off, by adding a less than comparison and turning it all
into a <span style="FONT-FAMILY: Courier New">&lt;TSource, bool&gt; LambdaExpression</span>: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: blue">var</span> maxComp = <span style="COLOR: #2b91af">E</span>.LessThan(distCalc, <span style="COLOR: #2b91af">E</span>.Constant(maxDist)); 
<br /><span style="COLOR: blue">var</span> pred = <span style="COLOR: #2b91af">E</span>.Lambda&lt;<span style="COLOR: #2b91af">Func</span>&lt;<span style="COLOR: #2b91af">Account</span>, <span style="COLOR: blue">bool</span>&gt;&gt;(maxComp,
acctParam); </span>
        </p>
        <p>
Our query can now look like this: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: #2b91af">MembersDataContext</span> dc
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">MembersDataContext</span>();<br /><span style="COLOR: blue">var</span> q = dc.Accounts.Where(pred); 
<br /><span style="COLOR: #2b91af">Console</span>.WriteLine(q.ToString()); </span>
        </p>
        <p>
When we run it, we see that LINQ to SQL is quite capable of handling our little bit
of math: 
</p>
        <p>
          <span style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New">
            <span style="COLOR: blue">exec</span>
            <span style="COLOR: maroon">sp_executesql</span> N<span style="COLOR: red">'SELECT
[t0].[AccountId], [t0].[Latitude], [t0].[Longitude]<br /></span></span>
          <span style="FONT-SIZE: 10pt; COLOR: red; FONT-FAMILY: Courier New">FROM
[dbo].[Accounts] AS [t0] 
<br /></span>
          <span style="FONT-SIZE: 10pt; COLOR: red; FONT-FAMILY: Courier New">WHERE (@p0
* ASIN( 
<br /></span>
          <span style="FONT-SIZE: 10pt; COLOR: red; FONT-FAMILY: Courier New">(CASE 
<br /></span>
          <span style="FONT-SIZE: 10pt; COLOR: red; FONT-FAMILY: Courier New">WHEN @p1
&lt; SQRT(POWER(SIN(((@p2 * @p3) - ([t0].[Latitude] * @p4)) / @p5), @p6) + (COS(@p7
* @p8) * COS([t0].[Latitude] * @p9) * 
<br />
    </span>
          <span style="FONT-SIZE: 10pt; COLOR: red; FONT-FAMILY: Courier New">POWER(SIN(((@p10
* @p11) - ([t0].[Longitude] * @p12)) / @p13), @p14))) THEN @p1 
<br /></span>
          <span style="FONT-SIZE: 10pt; COLOR: red; FONT-FAMILY: Courier New">ELSE SQRT(POWER(SIN(((@p2
* @p3) - ([t0].[Latitude] * @p4)) / @p5), @p6) + (COS(@p7 * @p8) * COS([t0].[Latitude]
* @p9) * 
<br />
    POWER(SIN(((@p10 * @p11) - ([t0].[Longitude] * @p12)) / @p13),
@p14))) </span>
          <span style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New">
            <span style="COLOR: red">
              <br />
END))) &lt; @p15'</span>
            <span style="COLOR: gray">,</span>N<span style="COLOR: red">'@p0
float,@p1 float,@p2 float,@p3 float,@p4 float,@p5 float,@p6 float,@p7 float,@p8 float,@p9
float,<br />
    @p10 float,@p11 float,@p12 float,@p13 float,@p14 float,@p15 float'</span><span style="COLOR: gray">,</span>@p0<span style="COLOR: gray">=</span>12742<span style="COLOR: gray">,</span>@p1<span style="COLOR: gray">=</span>1<span style="COLOR: gray">,</span>@p2<span style="COLOR: gray">=</span>95.412000000000006<span style="COLOR: gray">,</span>@p3<span style="COLOR: gray">=</span>0.017453292519943295<span style="COLOR: gray">,<br /></span>@p4<span style="COLOR: gray">=</span>0.017453292519943295<span style="COLOR: gray">,</span>@p5<span style="COLOR: gray">=</span>2<span style="COLOR: gray">,</span>@p6<span style="COLOR: gray">=</span>2<span style="COLOR: gray">,</span>@p7<span style="COLOR: gray">=</span>95.412000000000006<span style="COLOR: gray">,</span>@p8<span style="COLOR: gray">=</span>0.017453292519943295<span style="COLOR: gray">,</span>@p9<span style="COLOR: gray">=</span>0.017453292519943295<span style="COLOR: gray">,</span>@p10<span style="COLOR: gray">=</span>102.63200000000001<span style="COLOR: gray">,<br /></span>@p11<span style="COLOR: gray">=</span>0.017453292519943295<span style="COLOR: gray">,</span>@p12<span style="COLOR: gray">=</span>0.017453292519943295<span style="COLOR: gray">,</span>@p13<span style="COLOR: gray">=</span>2<span style="COLOR: gray">,</span>@p14<span style="COLOR: gray">=</span>2<span style="COLOR: gray">,</span>@p15<span style="COLOR: gray">=</span>100 </span>
        </p>
        <p>
I still think there should be some kind of syntax so we could write it like we want
to: (Where(a=&gt;dist(coolLat, coolLong, a.Latitude, a.Longitude) &gt; 10)). If anyone
knows a built-in way to do it, please let me know. I'm sure it's just something simple
I'm overlooking...
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=f9e4d1ef-8fff-4f44-8d9f-248bfc498e60" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Calling custom methods in LINQ-to-SQL</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2007/09/05/Calling+Custom+Methods+In+LINQtoSQL.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,f26a9142-88f9-4376-9285-a775227cfde7.aspx</id>
    <published>2007-09-05T19:58:49.363-04:00</published>
    <updated>2007-09-05T20:01:00.8635-04:00</updated>
    <category term="Code" label="Code" scheme="http://www.atrevido.net/blog/CategoryView,category,Code.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
This was sparked by the issues raised by <a href="http://blog.wekeroad.com/2007/08/30/linq-and-geocoding/">Rob
Conery here</a>. Basically, if you have some semi-complicated function that you need
to apply to a LINQ-to-SQL query, how can you do it? This is somewhat covered by TomasP.NET: <a href="http://tomasp.net/articles/dynamic-linq-queries.aspx">Building
LINQ Queries at Runtime</a> in C# and Joseph Albahari: <a href="http://www.albahari.com/expressions/">Dynamically
building LINQ expression predicates</a>. I recommend those two articles; they're very
good. I'm going to write a bit about it too. Some of it might be redundant, some of
the ideas I took from those articles. The code is all mine. 
</p>
        <p>
So, let's say we want to get all accounts where the square root of the account ID
is even. This will serve as our placeholder for a totally contrived example. Just
calling our method in our LINQ query won't work because the LINQ-to-SQL code isn't
going to know what to do with it. A method is just an opaque block of code with a
name. Here's an example: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">static</span>
            <span style="COLOR: blue">void</span> Main(<span style="COLOR: blue">string</span>[]
args) { 
<br /></span>
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: #2b91af">   
MembersDataContext</span> dc = <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">MembersDataContext</span>(); 
<br /></span>
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">   
var</span> q = dc.Accounts.Where(a =&gt; IsRightAccount(a)); 
<br /></span>
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: #2b91af">   
Console</span>.WriteLine(q.ToString()); 
<br /></span>
          <span style="FONT-FAMILY: Courier New">} 
<br /></span>
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">static</span>
            <span style="COLOR: blue">bool</span> IsRightAccount(<span style="COLOR: #2b91af">Account</span> a)
{ 
<br /></span>
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">   
return</span>
            <span style="COLOR: #2b91af">Math</span>.Sqrt(a.AccountId) % 2 == 0; 
<br /></span>
          <span style="FONT-FAMILY: Courier New">} </span>
        </p>
        <p>
This code crashes with: <span style="FONT-FAMILY: Courier New">Unhandled Exception:
System.NotSupportedException: Method 'Boolean IsRightAccount(ConsoleApplication1.Account)'
has no supported translation to SQL</span>. Which should be expected, as LINQ to SQL
cannot know what goes on inside that method and thus can't translate it. 
</p>
        <p>
Let's change things to make IsRightAccount be a Func delegate (from a lambda expression): 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">static</span>
            <span style="COLOR: #2b91af">Func</span>&lt;<span style="COLOR: #2b91af">Account</span>, <span style="COLOR: blue">bool</span>&gt;
IsRightAccount = a =&gt; <span style="COLOR: #2b91af">Math</span>.Sqrt(a.AccountId)
% 2 == 0; </span>
        </p>
        <p>
Now we get: <span style="FONT-FAMILY: Courier New">Unhandled Exception: System.NotImplementedException:
The method or operation is not implemented. At System.Data.Linq.SqlClient.QueryConverter.VisitInvocation(InvocationExpression
invoke).</span> That's a somewhat strange exception, as I'd expect it to be a bit
more helpful. At any rate, I'd expect it to crash, because that is just a delegate
to a method. It's still an opaque block of code. 
</p>
        <p>
Enter the magic Tree of Expressions: <span style="FONT-FAMILY: Courier New">Expression&lt;T&gt;</span>.
As I mentioned in my <a href="http://www.atrevido.net/blog/2007/09/05/C+30+And+LINQ+Misunderstandings.aspx">last
post</a>, Expression Trees provide "introspection" (reflection against code). In the
examples above, the lambda that calls <span style="FONT-FAMILY: Courier New">IsRightAccount</span> for
the Where clause actually turned into an <span style="FONT-FAMILY: Courier New">InvocationExpression</span> that
represents a call to the delegate provided. Hence me saying that it is "opaque". What
we need is to make sure that our code (our <span style="FONT-FAMILY: Courier New">IsRightAccount</span> calculation)
is visible <em>as data</em>. When it's visible as data, then LINQ-to-SQL can go and
say "Oh, you want to take the square root of the account ID, mod it by 2, and see
if that's zero… now THAT I can do in SQL". 
</p>
        <p>
Declaring an Expression Tree is really simple. First, make sure you import System.Linq.Expressions
if you don't want to fully qualify the name. Then, declare your tree just like any
lambda Func, except this time make the type Expression&lt;MyFunc&gt;: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="COLOR: blue; FONT-FAMILY: Courier New">static</span>
          <span style="FONT-FAMILY: Consolas">
          </span>
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: #2b91af">Expression</span>&lt;<span style="COLOR: #2b91af">Func</span>&lt;<span style="COLOR: #2b91af">Account</span>, <span style="COLOR: blue">bool</span>&gt;&gt;
IsRightAccount = a =&gt; <span style="COLOR: #2b91af">Math</span>.Sqrt(a.AccountId)
% 2 == 0;</span>
          <span style="FONT-FAMILY: Consolas">
          </span>
        </p>
        <p>
We will also change our Where clause to accommodate the fact that we are not calling
a method: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">var</span> q = dc.Accounts.Where(IsRightAccount); </span>
        </p>
        <p>
And presto! Our program now shows a SQL conversion: 
</p>
        <p>
          <span style="FONT-FAMILY: Courier New">SELECT [t0].[AccountId], [t0].[Email] 
<br />
FROM [dbo].[Accounts] AS [t0]<br />
WHERE (SQRT(CONVERT(Float,[t0].[AccountId])) % @p0) = @p1 </span>
        </p>
        <p>
Things get a bit more complicated when we try to stack expressions together. As far
as I know, we must create the Expression manually (using the Expression static methods);
the compiler won't help out. If anyone knows a built-in way around this, please let
me know. Otherwise, see the links at the top of this article for more information
and other workarounds. 
</p>
        <p>
This also applies if you have complex logic that doesn't directly map to a item -&gt;
bool predicate expression. In those cases, you can still encapsulate most of your
code by using the compiler to generate the bulk of the Expression, and then just wrap
it with a bit of hand-created expression. In my <a href="http://www.atrevido.net/blog/2007/08/26/A+LINQ+To+The+CRUD.aspx">LINQ
to the CRUD</a> article, the code attached uses this approach to generate queries
for the select/delete commands. Again, I will note that TomasP has written expansions
so you can just write myCoolExpression.Expand(arg) rather than building everything
by hand. 
</p>
        <p>
If you know of any other links or work done in this area, I'm very interested in seeing
other approaches. Thanks!
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=f26a9142-88f9-4376-9285-a775227cfde7" />
      </div>
    </content>
  </entry>
  <entry>
    <title>C# 3.0 and LINQ Misunderstandings</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2007/09/05/C+30+And+LINQ+Misunderstandings.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,522978e9-045b-447b-9898-9947467c2fe5.aspx</id>
    <published>2007-09-04T23:01:18.785-04:00</published>
    <updated>2007-09-04T23:10:27.89475-04:00</updated>
    <category term="Code" label="Code" scheme="http://www.atrevido.net/blog/CategoryView,category,Code.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Apparently, there is some considerable confusion over all the new C# language features.
People who I would hope are reasonably intelligent are completely misunderstanding
some C# fundamentals. Agreed, a lot of the new concepts introduced to C# 3.0 are might
seem relatively foreign to C# users. Microsoft's marketing related to LINQ doesn't
help much either. I'm going to try to clarify the top few things I've seen. I'll reference
the C# spec (<a href="http://msdn2.microsoft.com/en-us/library/ms364047(vs.80).aspx">http://msdn2.microsoft.com/en-us/library/ms364047(vs.80).aspx</a>)
so you can know I'm being accurate. 
</p>
        <h1>
          <font size="4">Myth: LINQ is just a data access technology</font>
        </h1>
        <p>
While data access is obviously a large part of LINQ (even the name stands for Language
Integrated Query), you can do a lot more than just access data. Re-using a <a href="http://www.atrevido.net/blog/2007/08/29/Practical+Functional+C+Part+IV+Think+In+ResultSets.aspx">previous
example</a>: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-SIZE: 9pt; FONT-FAMILY: Courier New">
            <span style="COLOR: blue">    </span>args<br /><span style="COLOR: blue">        </span>.Select(s
=&gt; <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">Thread</span>(()
=&gt; SomeLongProcess(s))) <br /><span style="COLOR: blue">        </span>.Process(t
=&gt; t.Start())<br /><span style="COLOR: blue">        </span>.ToList()<br /><span style="COLOR: blue">        </span>.ForEach(t
=&gt; t.Join());</span>
        </p>
        <p>
There's no sign of data access there! The practical functional C# articles on my site
go into more detail on this. Suffice to say, while a lot of new features were added
to "make LINQ possible", much, much, more is possible than just creating queries.
(Alternatively, you might chose to limit the meaning of LINQ, as I'd like to do. In
this case, I wouldn't consider using lambdas, extensions, etc. as LINQ. Others may
disagree. Marketing?)
</p>
        <h1>
          <font size="4">Implicitly typed local variables (var keyword)</font>
        </h1>
        <p>
C# is still statically and strongly typed. But, there's a new feature that lets you
declare local variables without specifying the type, if the type can be inferred from
the initializing expression. From the spec: 
</p>
        <p style="BACKGROUND: #dddddd">
          <span style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New">var i = 5; 
<br />
var s = "Hello"; 
<br />
var d = 1.0; 
<br />
var numbers = new int[] {1, 2, 3}; 
<br />
var orders = new Dictionary&lt;int,Order&gt;(); </span>
        </p>
        <p>
          <span style="FONT-SIZE: 8pt; FONT-FAMILY: Verdana">The implicitly typed local variable
declarations above are precisely equivalent to the following explicitly typed declarations: </span>
        </p>
        <p style="BACKGROUND: #dddddd">
          <span style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New">int i = 5; 
<br />
string s = "Hello"; 
<br />
double d = 1.0; 
<br />
int[] numbers = new int[] {1, 2, 3}; 
<br />
Dictionary&lt;int,Order&gt; orders = new Dictionary&lt;int,Order&gt;(); </span>
        </p>
        <p>
Oddly enough, the C# spec doesn't even mention LINQ or anonymous types when it talks
about "var" locals. Why is there confusion about this simple feature? Let's examine
anonymous types: 
</p>
        <p>
C# anonymous types allow you to declare a type just by specifying its fields. From
the spec: "<span style="FONT-SIZE: 8pt; FONT-FAMILY: Verdana">C# 3.0 permits the <strong>new</strong> operator
to be used with an anonymous object initializer to create an object of an anonymous
type."</span> For instance, the following code is a valid expression: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: blue">new</span> { Name = <span style="COLOR: #a31515">"Michael" </span>} </span>
        </p>
        <p>
This produces an object of a new, anonymous, type, containing a single string property
called Name. Hence, this code works: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: #2b91af">Console</span>.WriteLine(<span style="COLOR: blue">new</span> {
Name = <span style="COLOR: #a31515">"Michael"</span> }.Name); </span>
        </p>
        <p>
However, how can you assign such an object to a variable? Yes, that is the only "need"
for the var keyword. There's no way to name the type, since it's anonymous. Regardless
if you agree with anonymous types (versus a Tuple class), this is the place where
you *need* to use var: assigning an anonymous type to a local. 
</p>
        <p>
As you may have noticed, I still haven't mentioned LINQ. Anonymous types are not LINQ
specific. They are, however, particularly helpful for certain LINQ queries: 
</p>
        <p>
var topCustomers = MyDatabase.Customers.Where(c =&gt; c.GoldStar == true).Select(c
=&gt; new {c.CustomerId, c.Name}); 
</p>
        <p>
Because of this, people start to associate anonymous types only with LINQ queries
and hence, var with LINQ only. The truth is that these features can be used anywhere. 
</p>
        <p>
What's the takeaway here? <strong>The var keyword simply allows the compiler to infer
the type of the variable so you don't have to specify it.</strong> Nothing more, nothing
less. Some people still want to explicitly annotate every single variable – hey, that's
their choice. But don't be locked into this just because there was no option before.
Me? I'll take more concise code any day! 
</p>
        <p>
As a side note (if this wasn't clear), the var keyword is NOT dynamic typing, just
implicit typing (type inference). 
</p>
        <h1>
          <font size="4">Dynamic C#</font>
        </h1>
        <p>
Seems there's a lot of confusion about C# being dynamic. C# is not dynamically typed,
as some seem to imply. I think perhaps some of the confusion comes from all the nice
type inference that C# provides. Using the var keyword as shown above might make some
people feel "oh, I'm saying var just like Javascript!". Adding to the confusion is
the fact that C# is now a "semi"-functional language. For instance, from "<a href="http://poignantguide.net/ruby/chapter-3.html">why's
(poignant) guide to ruby</a>", we see this Ruby code: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: #339966; BACKGROUND-COLOR: #fffef9">5</span>
            <span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9">.</span>
            <span style="COLOR: #336699; BACKGROUND-COLOR: #fffef9">times</span>
            <span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9"> { </span>
            <span style="COLOR: #336699; BACKGROUND-COLOR: #fffef9">print</span>
            <span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9"> "</span>
            <span style="COLOR: #339966; BACKGROUND-COLOR: #e9f5f5">Odelay!</span>
            <span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9">"
} </span>
          </span>
        </p>
        <p>
C# allows us to write in a similar style: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">5.Times(() =&gt; <span style="COLOR: #2b91af">Console</span>.WriteLine(<span style="COLOR: #a31515">"Odelay!"</span>)); </span>
        </p>
        <p>
The next Ruby example in that guide goes like this: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: #336699; BACKGROUND-COLOR: #fffef9">exit</span>
            <span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9">
              <strong>unless</strong> "</span>
            <span style="COLOR: #339966; BACKGROUND-COLOR: #e9f5f5">restaurant</span>
            <span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9">".</span>
            <span style="COLOR: #336699; BACKGROUND-COLOR: #fffef9">include?</span>
            <span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9"> "</span>
            <span style="COLOR: #339966; BACKGROUND-COLOR: #e9f5f5">aura</span>
            <span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9">" </span>
          </span>
        </p>
        <p>
In C#, we can write: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">exit.Unless(() =&gt; <span style="COLOR: #a31515">"restaurant"</span>.Contains(<span style="COLOR: #a31515">"aura"</span>));</span>
        </p>
        <p>
The <a href="http://en.wikipedia.org/wiki/Dynamic_language">Wikipedia article on Functional
Programming</a> lists a few features that dynamic languages usually have: 
</p>
        <h2>
          <font size="3">Eval </font>
        </h2>
        <p>
Sorta… you can create Expression&lt;T&gt; and execute them. On the other hand, you
can't do anything like eval(myString) (which is just asking for runtime failure). 
</p>
        <h2>
          <font size="3">Higher-order functions</font>
        </h2>
        <p>
Definitely in there. 
</p>
        <h2>
          <font size="3">Runtime alteration of object or type system</font>
        </h2>
        <p>
No, not really. (I.e., maybe you can hack around with certain APIs to try to do some
magic, but it's not a language feature.) 
</p>
        <h2>
          <font size="3">Functional Programming</font>
        </h2>
        <p>
Yes. But still, functions aren't really first class citizens…yet. Once we can start
using method groups as Actions and Funcs, implicitly, then it'll get even better.
This is an interesting presentation from Andrew Kennedy, Microsoft Research: <a href="http://sneezy.cs.nott.ac.uk/fun/nov-06/FunPm.ppt">C#
is a functional programming language</a>.
</p>
        <h2>
          <font size="3">Closures </font>
        </h2>
        <p>
Yep, since anonymous methods were introduced in C# 2.0. 
</p>
        <h2>
          <font size="3">Continuations</font>
        </h2>
        <p>
Extremely limited, in the form of <span style="FONT-FAMILY: Courier New">yield return</span>. 
</p>
        <h2>
          <font size="3">Introspection</font>
        </h2>
        <p>
Not just reflection, but actually inspecting the actual code. C# 3.0 has this in the
form of Expression&lt;T&gt; (see below). 
</p>
        <h2>
          <font size="3">Macros</font>
        </h2>
        <p>
No, not crappy C-style macros. Here, I'm thinking more like macros that'd let you
create things like C# query comprehensions, *in source code*. (Which is what I was
actually hoping when I saw the new query comprehension syntax… no such luck). 
</p>
        <p>
          <strong>In summary</strong>, C# lets you gain a lot of benefits usually associated
with dynamic <strong>programming</strong>, but without the nasty parts of dynamic <strong>typing</strong>. 
</p>
        <p>
A great paper on this subject is <a href="http://pico.vub.ac.be/~wdmeuter/RDL04/papers/Meijer.pdf">Static
Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between
Programming Languages</a>, by Erik Meijer and Peter Drayton of Microsoft. 
</p>
        <h1>
          <font size="4">Myth: Extension methods add methods to a class</font>
        </h1>
        <p>
This is a tricky one, since extension methods appear to be exactly that. This myth
is also somewhat perpetuated by the C# spec: "In effect, extension methods make it
possible to extend existing types and constructed types with additional methods."
But, right before that, the real explanation is given: "Extension methods are static
methods that can be invoked using instance method syntax." 
</p>
        <p>
Essentially, Extension methods allow us to use <a href="http://en.wikipedia.org/wiki/Infix_notation"><strong>infix</strong></a><strong></strong>notation
with certain methods. This explains the line from the spec "in effect". A more helpful
way to think of this is by thinking of the "." operator as an overloaded operator
that also allows passing the first operand given to it as the first argument to <em>specially
marked</em> methods. 
</p>
        <p>
An alternative* would be to define an operator like the F# pipeline operator (|&gt;).
In C#, this would let us write stuff like: 
</p>
        <p style="BACKGROUND: #eeece1">
customers |&gt; Seq.Where(c =&gt; c.Name == "Michael") 
</p>
        <p>
That doesn't look like an improvement. BUT, we no longer need to mark methods in a
special way. We can just use them: 
</p>
        <p style="BACKGROUND: #eeece1">
myArray |&gt; Array.BinarySearch("s") 
</p>
        <p>
Why do we need infix notation anyways? Well, the normal prefix notation can be difficult
to read: 
</p>
        <p style="BACKGROUND: #eeece1">
Select(Where(customers, c =&gt; c.Cool == true), c =&gt; c.Name)<br />
Array.BinarySearch(items, "S") 
</p>
        <p>
Extension methods just make those functions easier to pipeline. That's all folks.
Think of them like this, and save yourself a headache about what "extending a type"
means. 
</p>
        <p>
*My guess as to why extension methods are done they way they are is because it could
confuse people if you have something like "item |&gt; Stuff.SomeMethod("X")" where
SomeMethod returns a function. Or, where you have "item |&gt; Stuff.SomeMethod("X").SomethingElse("y").
I'm still annoyed that I can't use infix semantics where *I* want, but oh well. 
</p>
        <h2>
          <font size="4">Lambda expressions and Expression&lt;T&gt;</font>
        </h2>
        <p>
Spec: "Lambda expressions provide a more concise, functional syntax for writing anonymous
methods.". Spec: "Expression trees permit lambda expressions to be represented as
data structures instead of executable code. A lambda expression that is convertible
to a delegate type D is also convertible to an expression tree of type System.Query.Expression&lt;D&gt;." 
</p>
        <p>
So, "lambda expressions" can either be just code (i.e., directly executable IL) OR
they can get turned into a data structure, Expression&lt;T&gt;. 
</p>
        <p>
Adding to the confusion, a lambda expression can contain just an expression (i=&gt;
i + 1), or it can be a block of statements ( i =&gt; {Write(i); i++; Write(i); return
i+1;} ). However, a lambda expression with a statement block body <em>cannot </em>become
an Expression&lt;T&gt;. (As far as I know, VB's lambdas only allow for expression
bodies, not blocks.) 
</p>
        <p>
An example: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: #2b91af">Expression</span>&lt;<span style="COLOR: #2b91af">Func</span>&lt;<span style="COLOR: blue">int</span>, <span style="COLOR: blue">int</span>&gt;&gt;
inc = i =&gt; i + 1; </span>
        </p>
        <p>
          <span style="FONT-FAMILY: Consolas">
            <font face="Arial">Is equivalent to:</font>
          </span>
        </p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: #2b91af">ParameterExpression</span> param_i
= <span style="COLOR: #2b91af">Expression</span>.Parameter(<span style="COLOR: blue">typeof</span>(<span style="COLOR: blue">int</span>), <span style="COLOR: #a31515">"i"</span>);<br /><span style="COLOR: blue">var</span> inc2 = <span style="COLOR: #2b91af">Expression</span>.Lambda&lt;<span style="COLOR: #2b91af">Func</span>&lt;<span style="COLOR: blue">int</span>, <span style="COLOR: blue">int</span>&gt;&gt;(<br /><span style="COLOR: #2b91af">    Expression</span>.Add(<br /><span style="COLOR: #2b91af">    <span style="COLOR: #2b91af">    </span></span>param_i, <br /><span style="COLOR: #2b91af"><span style="COLOR: #2b91af">    </span>Expression</span>.Constant(1, <span style="COLOR: blue">typeof</span>(<span style="COLOR: blue">int</span>))), 
<br />
param_i); </span>
        </p>
        <p>
At runtime, you can then go inspect the actual code and decide what to do with it.
This is exactly the premise for LINQ to SQL. When you create a LINQ-to-SQL query,
it is turned into an expression like shown above. Then the LINQ-to-SQL APIs inspect
and convert that expression tree into SQL statements. 
</p>
        <p>
Here, I can understand the confusion. The word "expression" is used in three distinct
manners. Rightfully, Expression Trees should be referred to as Expression or Expression&lt;T&gt;,
which could help clear up some of the confusion. Additionally, it doesn't help that
lambdas have these different conversion rules (although working around it could be
ugly, possibly). 
</p>
        <p>
          <strong>Are there any other features that you've seen misused or you've had questions
about?</strong> Let me know! I love comments, insults, and suggestions.
</p>
        <p>
          <strong>Want to correct me on something?</strong> Go right ahead! But, if you're going
to say something like "C# doesn't have type inference", please make sure to either
be an expert on the matter or be able to quote an authoritative source or show a proof.
Thanks!
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=522978e9-045b-447b-9898-9947467c2fe5" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Practical Functional C# - Part IV – Think in [Result]Sets</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2007/08/29/Practical+Functional+C+Part+IV+Think+In+ResultSets.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,ed630fc6-cafa-450a-a6f2-7a570064f09a.aspx</id>
    <published>2007-08-29T06:45:59.972-04:00</published>
    <updated>2007-08-29T06:55:18.035375-04:00</updated>
    <category term="Code" label="Code" scheme="http://www.atrevido.net/blog/CategoryView,category,Code.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Don't skip parts I to III to get you up to speed. I have $300 up for grabs
if these articles are incorrect in stating that it will greatly improve most C# apps:
</p>
        <p>
    <a href="http://www.atrevido.net/blog/2007/08/12/Practical+Functional+C+Part+I.aspx">Practical
Functional C# - Part I </a><br />
    <a href="http://www.atrevido.net/blog/2007/08/13/Practical+Functional+C+Part+II.aspx">Practical
Functional C# - Part II <br /></a>    <a href="http://www.atrevido.net/blog/2007/08/16/Practical+Functional+C+Part+III+Loops+Are+Evil.aspx">Practical
Functional C# - Part III - Loops are Evil</a></p>
        <p>
Tell the compiler what you want, rather than how to do it. That's a key concept that
can take you very far. However, as imperative programmers, this can sometimes be a
hard concept. We are so used to instructing the processor, step-by-step, how do to
things, and then only after we're all done, making sure the end effect is to our liking.
Functional programming helps us change this. 
</p>
        <p>
Consider the following task: Write a function that checks a username against a few
disallowed characters "!@#$%^&amp;*". The normal C# implementation looks like this
(null checks removed): 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">static</span>
            <span style="COLOR: blue">bool</span> IsBadUserName(<span style="COLOR: blue">string</span> userName)<br />
{<br /><span style="COLOR: blue">    var</span> badChars = <span style="COLOR: #a31515">"!@#$%^&amp;*"</span>;<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>foreach</span> (<span style="COLOR: blue">char</span> c <span style="COLOR: blue">in</span> badChars)
{<br /><span style="COLOR: blue"><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>if</span> (userName.Contains(c)) <span style="COLOR: blue">return</span><span style="COLOR: blue">true</span>; <br /><span style="COLOR: blue">    </span>}<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>return</span><span style="COLOR: blue">false</span>; 
<br />
} </span>
        </p>
        <p>
It's not horrible; there's only one branch, but it does require a bit of thought to
sort out. Now let's take an approach where we deal with string as a set of characters
to manipulate at once (requires C# 3.0 compiler): 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">static</span>
            <span style="COLOR: blue">bool</span> IsBadUserName2(<span style="COLOR: blue">string</span> userName){ <br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>var</span> badChars
= <span style="COLOR: #a31515">"!@#$%^&amp;*"</span>;<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>return</span> userName<br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>.Intersect(badChars) <br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>.Any();<br />
} </span>
        </p>
        <p>
We've reduced the function from a step-by-step loop into something that has only path.
The bigger benefit is that there's no need to evaluate end conditions and so on for
correctness: The code says exactly what it does. "Are there any bad characters in
the user name?" We don't have to worry how it does what we asked, we just need to
think in terms of what we want our result to be. 
</p>
        <p>
A common function in functional languages is called "map". Map takes a list of something
and turns it into a list of something else. For instance, if we had a list of integers
("ourInts"), we could turn them into squares by saying "map ourInts by multiplying
each value with itself". In C# (LINQ), they called map "Select". Here's a quick example: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">var</span> ourInts
= <span style="COLOR: blue">new</span>[] { 2, 5, 13 };<br /><span style="COLOR: blue">var</span> squares = ourInts.Select(i =&gt; i * i); </span>
        </p>
        <p>
Squares will contain the list { 4, 25, 169 }. What use is this? Well, it is an extremely
common pattern to take some set of data, filter it, modify it a bit, and return a
new set of data. Here's an example: You have a variable from containing semicolon-delimited
email addresses. You want to turn these into an array of .NET's MailAddress objects
to use with some other code. The loop isn't very pretty: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">var</span> tempAddresses
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">List</span>&lt;<span style="COLOR: #2b91af">MailAddress</span>&gt;();<br /><span style="COLOR: blue">foreach</span> (<span style="COLOR: blue">string</span> s <span style="COLOR: blue">in</span> semicolonEmails.Split(<span style="COLOR: #a31515">';'</span>))
{<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>var</span> ts
= s.Trim();<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>if</span> (ts
== <span style="COLOR: #a31515">""</span>) <span style="COLOR: blue">continue</span>; <br /><span style="COLOR: blue">    </span>tempAddresses.Add(<span style="COLOR: blue">new</span><span style="COLOR: #2b91af">MailAddress</span>(ts)); <br />
}<br /><span style="COLOR: blue">var</span> myAddresses = tempAddresses.ToArray(); </span>
        </p>
        <p>
But consider the functional approach: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">var </span>myAddresses
= semicolonEmails<br /><span style="COLOR: blue">    </span>.Split(<span style="COLOR: #a31515">';'</span>) <br /><span style="COLOR: blue">    </span>.Select(s =&gt; s.Trim())<br /><span style="COLOR: blue">    </span>.Where(s =&gt; s !=<span style="COLOR: #a31515"> ""</span>) <br /><span style="COLOR: blue">    </span>.Select(s =&gt; <span style="COLOR: blue">new</span> MailAddress(s))<br /><span style="COLOR: blue">    </span>.ToArray(); </span>
        </p>
        <p>
In one statement, we transform the data three times, as well as add filter to remove
empty items. 
</p>
        <p>
One place where LINQ falls flat on its face is when it comes to processing data. For
some reason, there are no methods defined to do "ForEach" or "Process". (Even more
interesting: List&lt;T&gt; does define these methods.) <span style="FONT-FAMILY: Courier New">Process</span> is
a great pattern: on each item, it performs some action, then returns the original
item. The code to define it is very simple and looks like this: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">static</span>
            <span style="COLOR: #2b91af">IEnumerable</span>&lt;T&gt;
Process&lt;T&gt;(<span style="COLOR: blue">this</span><span style="COLOR: #2b91af">IEnumerable</span>&lt;T&gt;
source, <span style="COLOR: #2b91af">Action</span>&lt;T&gt; f)<br />
{<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>foreach</span> (<span style="COLOR: blue">var</span> item <span style="COLOR: blue">in</span> source)
{<br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>f(item); <br /><span style="COLOR: blue"><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>yield</span><span style="COLOR: blue">return</span> item; <br /><span style="COLOR: blue">    </span>}<br />
} </span>
        </p>
        <p>
How is this of use? Well, let's chain together some functional and imperative processing.
For instance, write a program that does some long process on all files passed in as
arguments – on separate threads. If we take the purely imperative approach, our code
looks like this: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">static</span>
            <span style="COLOR: blue">void</span> Main(<span style="COLOR: blue">string</span>[]
args)<br />
{<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>var</span> threads
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">List</span>&lt;<span style="COLOR: #2b91af">Thread</span>&gt;();<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>foreach</span> (<span style="COLOR: blue">var</span> s <span style="COLOR: blue">in</span> args)
{<br /><span style="COLOR: #2b91af"><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>Thread</span> t
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">Thread</span>(startLongProcess); <br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>t.Start(s); <br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>threads.Add(t); <br /><span style="COLOR: blue">    </span>}<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>foreach</span> (<span style="COLOR: blue">var</span> t <span style="COLOR: blue">in</span> threads)
{<br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>t.Join();<br /><span style="COLOR: blue">    </span>}<br />
}<br /><span style="COLOR: blue">static</span><span style="COLOR: blue">void</span> startLongProcess(<span style="COLOR: blue">object</span> data) 
<br />
{<br /><span style="COLOR: blue">    </span>SomeLongProcess((<span style="COLOR: blue">string</span>)data); 
<br />
} </span>
        </p>
        <p>
Yes, we actually must declare a separate function just to invoke <span style="FONT-FAMILY: Courier New">SomeLongProcess</span>.
Let's combine and use the functional approach now: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">static</span>
            <span style="COLOR: blue">void</span> Main(<span style="COLOR: blue">string</span>[]
args) 
<br />
{<br /><span style="COLOR: blue">    </span>args<br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>.Select(s
=&gt; <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">Thread</span>(()
=&gt; SomeLongProcess(s))) <br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>    </span>.Process(t
=&gt; t.Start())<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>    </span>.ToList()<br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>.ForEach(t
=&gt; t.Join());<br />
} </span>
        </p>
        <p>
Which way is going to be easier to edit and change around? I don't know about you,
but for me, going from ~12 to ~5 lines, removing extra variables, useless functions
and flow control structures: that's a hands-down win in my book. 
</p>
        <p>
As a side note, threading, in fact, is a space that is extremely ripe for functional
styles. I'm willing to bet that ".NET 4" will include threading extensions that rely
heavily on functional concepts. For instance, it's easy to create a method that allows
us to replace the previous program with this: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">args.Parallel(SomeLongProcess); </span>
        </p>
        <p>
But I'll talk about that another day. 
</p>
        <p>
In the next article, I'm going to cover C#'s new inner functions capability and how
that can be used to help build up more complicated function chains. I'd also like
some feedback on which kinds of areas of C# programming you've run into that seem
to require more code than necessary. 
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=ed630fc6-cafa-450a-a6f2-7a570064f09a" />
      </div>
    </content>
  </entry>
  <entry>
    <title>A LINQ to the CRUD</title>
    <link rel="alternate" type="text/html" href="http://www.atrevido.net/blog/2007/08/26/A+LINQ+To+The+CRUD.aspx" />
    <id>http://www.atrevido.net/blog/PermaLink,guid,6f242348-42ca-4934-9c2e-ea2bd1103a02.aspx</id>
    <pu