<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" version="2.0">
  <channel>
    <title>[Giagnocavo]Michael::Write() - Code</title>
    <link>http://www.atrevido.net/blog/</link>
    <description>Something about .NET.</description>
    <copyright>Michael Giagnocavo</copyright>
    <lastBuildDate>Fri, 07 May 2010 04:57:57 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>mggUNSPAM@telefinity.com</managingEditor>
    <webMaster>mggUNSPAM@telefinity.com</webMaster>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=e0bf507d-5e92-4f49-b834-be3f8ae61318</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,e0bf507d-5e92-4f49-b834-be3f8ae61318.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,e0bf507d-5e92-4f49-b834-be3f8ae61318.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=e0bf507d-5e92-4f49-b834-be3f8ae61318</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In Visual Studio 2010, you can now get your F# unit tests loaded by the IDE. First,
create your F# test project. This is just a normal library referencing Microsoft.VisualStudio.QualityTools.UnitTestFramework
and having test classes and so on. The only change you need to do is go into the configuration
and set the output folder to "bin" for both debug and release (instead of bin\debug).
</p>
        <p>
Next, create a C# Test Project, and delete the code file. Then add an existing item,
and navigate to the bin directory of your test project output. Select the DLL and
Add as Link. 
</p>
        <p>
Finally, right click the solution, and change the project dependencies so the C# test
project depends on your F# test project.
</p>
        <p>
That's it. Now the IDE will pickup your F# tests and allow you to manage, run, and
debug them right from VS. You may have to restart the IDE after setting all this
up for it to work smoothly. 
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=e0bf507d-5e92-4f49-b834-be3f8ae61318" />
      </body>
      <title>F# Unit Testing with Visual Studio 2010</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,e0bf507d-5e92-4f49-b834-be3f8ae61318.aspx</guid>
      <link>http://www.atrevido.net/blog/2010/05/07/F+Unit+Testing+With+Visual+Studio+2010.aspx</link>
      <pubDate>Fri, 07 May 2010 04:57:57 GMT</pubDate>
      <description>&lt;p&gt;
In Visual Studio 2010, you can now get your F# unit tests loaded by the IDE. First,
create your F# test project. This is just a normal library referencing Microsoft.VisualStudio.QualityTools.UnitTestFramework
and having test classes and so on. The only change you need to do is go into the configuration
and set the output folder to "bin" for both debug and release (instead of bin\debug).
&lt;/p&gt;
&lt;p&gt;
Next, create a C# Test Project, and delete the code file. Then add an existing item,
and navigate to the bin directory of your test project output. Select the DLL and
Add as Link. 
&lt;/p&gt;
&lt;p&gt;
Finally, right click the solution, and change the project dependencies so the C# test
project depends on your F# test project.
&lt;/p&gt;
&lt;p&gt;
That's it. Now the IDE will pickup your F# tests and allow you to manage, run, and
debug them right from VS.&amp;nbsp;You may have to restart the IDE after setting all this
up for it to work smoothly.&amp;nbsp;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=e0bf507d-5e92-4f49-b834-be3f8ae61318" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,e0bf507d-5e92-4f49-b834-be3f8ae61318.aspx</comments>
      <category>Code</category>
      <category>FSharp</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=71f95609-5a0d-40d5-afb8-734076aa7df1</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,71f95609-5a0d-40d5-afb8-734076aa7df1.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,71f95609-5a0d-40d5-afb8-734076aa7df1.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=71f95609-5a0d-40d5-afb8-734076aa7df1</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Using the data protection API, I found I needed to be able to generate values by hand
that my apps can work with later. So I wrote a small command line utility to help
out with that process.
</p>
        <p>
Example:<br /><br />
dpapicmd [/user] [/decrypt] [/utf8] [/entropy:&lt;entropy&gt;] {/clipboard|&lt;text&gt;}<br />
Text is read as Base64 bytes unless /utf8 is used. Decrypted input and encrypted output
is always Base64.
</p>
        <p>
C:\&gt;dpapicmd /utf8 /entropy:dogstuff "I'm barking mad."<br />
AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAOE510Ds5PkGpG2g7PxkgXwQAAAACAAAAAAAQZgAAAAEAACAAAACSClIQpWDawT26jRrsFr/HauG2NjUw963fPKH+AcXqlwAAAAAOgAAAAAIAACAAAABwxg<br />
Osbkh6TfdTUzaiEGgKJ/ohL91VGHIpRDrBeR7wvyAAAADyvUh1W+bmzUFago/LybBvmmQD96x2vCOiJgpPxTNItEAAAAAmVJ3DoTnIAfUIsO2ea8hqs6Rpp77gvDn77XAzXfACRY3IGT7BjicYJ7Og<br />
NQhzsrHCybBK0DRQchrPK5+XT8TR
</p>
        <p>
C:\&gt;dpapicmd /utf8 /dec /entropy:dogstuff AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAOE510Ds5PkGpG2g7PxkgXwQAAAACAAAAAAAQZgAAAAEAACAAAACSClIQpWDawT26jRrsFr/HauG2<br />
NjUw963fPKH+AcXqlwAAAAAOgAAAAAIAACAAAABwxgOsbkh6TfdTUzaiEGgKJ/ohL91VGHIpRDrBeR7wvyAAAADyvUh1W+bmzUFago/LybBvmmQD96x2vCOiJgpPxTNItEAAAAAmVJ3DoTnIAfUIsO<br />
2ea8hqs6Rpp77gvDn77XAzXfACRY3IGT7BjicYJ7OgNQhzsrHCybBK0DRQchrPK5+XT8TR<br /><br />
I'm barking mad.
</p>
        <p>
Download: <a href="http://www.atrevido.net/blog/content/binary/dpapicmd.exe">dpapicmd.exe
(7.5 KB)</a> (Requires .NET 2.0 because I'm too lazy to write it in C.)<br /><br />
And horrible hacky source: <a href="http://www.atrevido.net/blog/content/binary/dpapicmd.cs.txt">dpapicmd.cs.txt
(4.25 KB)</a></p>
        <p>
 
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=71f95609-5a0d-40d5-afb8-734076aa7df1" />
      </body>
      <title>Command line tool for DPAPI</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,71f95609-5a0d-40d5-afb8-734076aa7df1.aspx</guid>
      <link>http://www.atrevido.net/blog/2010/05/06/Command+Line+Tool+For+DPAPI.aspx</link>
      <pubDate>Thu, 06 May 2010 17:53:33 GMT</pubDate>
      <description>&lt;p&gt;
Using the data protection API, I found I needed to be able to generate values by hand
that my apps can work with later. So I wrote a small command line utility to help
out with that process.
&lt;/p&gt;
&lt;p&gt;
Example:&lt;br&gt;
&lt;br&gt;
dpapicmd [/user] [/decrypt] [/utf8] [/entropy:&amp;lt;entropy&amp;gt;] {/clipboard|&amp;lt;text&amp;gt;}&lt;br&gt;
Text is read as Base64 bytes unless /utf8 is used. Decrypted input and encrypted output
is always Base64.
&lt;/p&gt;
&lt;p&gt;
C:\&amp;gt;dpapicmd /utf8 /entropy:dogstuff "I'm barking mad."&lt;br&gt;
AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAOE510Ds5PkGpG2g7PxkgXwQAAAACAAAAAAAQZgAAAAEAACAAAACSClIQpWDawT26jRrsFr/HauG2NjUw963fPKH+AcXqlwAAAAAOgAAAAAIAACAAAABwxg&lt;br&gt;
Osbkh6TfdTUzaiEGgKJ/ohL91VGHIpRDrBeR7wvyAAAADyvUh1W+bmzUFago/LybBvmmQD96x2vCOiJgpPxTNItEAAAAAmVJ3DoTnIAfUIsO2ea8hqs6Rpp77gvDn77XAzXfACRY3IGT7BjicYJ7Og&lt;br&gt;
NQhzsrHCybBK0DRQchrPK5+XT8TR
&lt;/p&gt;
&lt;p&gt;
C:\&amp;gt;dpapicmd /utf8 /dec /entropy:dogstuff AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAOE510Ds5PkGpG2g7PxkgXwQAAAACAAAAAAAQZgAAAAEAACAAAACSClIQpWDawT26jRrsFr/HauG2&lt;br&gt;
NjUw963fPKH+AcXqlwAAAAAOgAAAAAIAACAAAABwxgOsbkh6TfdTUzaiEGgKJ/ohL91VGHIpRDrBeR7wvyAAAADyvUh1W+bmzUFago/LybBvmmQD96x2vCOiJgpPxTNItEAAAAAmVJ3DoTnIAfUIsO&lt;br&gt;
2ea8hqs6Rpp77gvDn77XAzXfACRY3IGT7BjicYJ7OgNQhzsrHCybBK0DRQchrPK5+XT8TR&lt;br&gt;
&lt;br&gt;
I'm barking mad.
&lt;/p&gt;
&lt;p&gt;
Download: &lt;a href="http://www.atrevido.net/blog/content/binary/dpapicmd.exe"&gt;dpapicmd.exe
(7.5 KB)&lt;/a&gt;&amp;nbsp;(Requires .NET 2.0 because I'm too lazy to write it in C.)&lt;br&gt;
&lt;br&gt;
And horrible hacky source: &lt;a href="http://www.atrevido.net/blog/content/binary/dpapicmd.cs.txt"&gt;dpapicmd.cs.txt
(4.25 KB)&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=71f95609-5a0d-40d5-afb8-734076aa7df1" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,71f95609-5a0d-40d5-afb8-734076aa7df1.aspx</comments>
      <category>Code</category>
      <category>Security</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=88dc6738-246f-4ca8-a6b2-be5b23bdf59e</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,88dc6738-246f-4ca8-a6b2-be5b23bdf59e.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,88dc6738-246f-4ca8-a6b2-be5b23bdf59e.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=88dc6738-246f-4ca8-a6b2-be5b23bdf59e</wfw:commentRss>
      <title>FluentNHibernate FSharp update for RTM</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,88dc6738-246f-4ca8-a6b2-be5b23bdf59e.aspx</guid>
      <link>http://www.atrevido.net/blog/2010/04/28/FluentNHibernate+FSharp+Update+For+RTM.aspx</link>
      <pubDate>Wed, 28 Apr 2010 21:56:22 GMT</pubDate>
      <description>I've updated the code we use for FluentNHibernate with F# - using the final versions of both products. It's just some code to fixup F# quotations to LINQ expressions that FluentNHibernate can work with, and type extensions to make it easy to consume from F#.&lt;br&gt;
&lt;br&gt;
The &lt;a href="http://fluentnhibernate.org/downloads/releases/fluentnhibernate-1.0RTM.zip"&gt;FluentNHibernate
RTM zip&lt;/a&gt; has all the other binaries you need to get started.&lt;br&gt;
&lt;br&gt;
I'm building against .NET 4, but the code should work on 2.0 as well.&lt;br&gt;
&lt;br&gt;
&lt;a href="http://www.atrevido.net/blog/content/binary/FluentNHibernate.FSharp.dll"&gt;FluentNHibernate.FSharp.dll
(38.5 KB)&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
&lt;a href="http://www.atrevido.net/blog/content/binary/FluentNHibernate.FSharp.zip"&gt;FluentNHibernate.FSharp.zip
(6.95 KB) Source&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
And here's the FluentNHibernate sample first project using FluentNHibernate.FSharp:&lt;br&gt;
&lt;br&gt;
&lt;a href="http://www.atrevido.net/blog/content/binary/FirstProject.zip"&gt;FirstProject.zip
(7.66 KB)&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
Here's an example of what some mapping code looks like:&lt;br&gt;
&lt;br&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt;
&lt;meta name="ProgId" content="Word.Document"&gt;
&lt;meta name="Generator" content="Microsoft Word 14"&gt;
&lt;meta name="Originator" content="Microsoft Word 14"&gt;
&lt;link rel="File-List" href="file:///C:%5CUsers%5CMichael%5CAppData%5CLocal%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_filelist.xml"&gt;
&lt;!--[if gte mso 9]&gt;&lt;xml&gt;
 &lt;o:OfficeDocumentSettings&gt;
  &lt;o:AllowPNG/&gt;
 &lt;/o:OfficeDocumentSettings&gt;
&lt;/xml&gt;&lt;![endif]--&gt;
&lt;link rel="themeData" href="file:///C:%5CUsers%5CMichael%5CAppData%5CLocal%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_themedata.thmx"&gt;
&lt;link rel="colorSchemeMapping" href="file:///C:%5CUsers%5CMichael%5CAppData%5CLocal%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_colorschememapping.xml"&gt;
&lt;!--[if gte mso 9]&gt;&lt;xml&gt;
 &lt;w:WordDocument&gt;
  &lt;w:View&gt;Normal&lt;/w:View&gt;
  &lt;w:Zoom&gt;0&lt;/w:Zoom&gt;
  &lt;w:TrackMoves/&gt;
  &lt;w:TrackFormatting/&gt;
  &lt;w:PunctuationKerning/&gt;
  &lt;w:ValidateAgainstSchemas/&gt;
  &lt;w:SaveIfXMLInvalid&gt;false&lt;/w:SaveIfXMLInvalid&gt;
  &lt;w:IgnoreMixedContent&gt;false&lt;/w:IgnoreMixedContent&gt;
  &lt;w:AlwaysShowPlaceholderText&gt;false&lt;/w:AlwaysShowPlaceholderText&gt;
  &lt;w:DoNotPromoteQF/&gt;
  &lt;w:LidThemeOther&gt;EN-US&lt;/w:LidThemeOther&gt;
  &lt;w:LidThemeAsian&gt;X-NONE&lt;/w:LidThemeAsian&gt;
  &lt;w:LidThemeComplexScript&gt;X-NONE&lt;/w:LidThemeComplexScript&gt;
  &lt;w:Compatibility&gt;
   &lt;w:BreakWrappedTables/&gt;
   &lt;w:SnapToGridInCell/&gt;
   &lt;w:WrapTextWithPunct/&gt;
   &lt;w:UseAsianBreakRules/&gt;
   &lt;w:DontGrowAutofit/&gt;
   &lt;w:SplitPgBreakAndParaMark/&gt;
   &lt;w:EnableOpenTypeKerning/&gt;
   &lt;w:DontFlipMirrorIndents/&gt;
   &lt;w:OverrideTableStyleHps/&gt;
  &lt;/w:Compatibility&gt;
  &lt;m:mathPr&gt;
   &lt;m:mathFont m:val="Cambria Math"/&gt;
   &lt;m:brkBin m:val="before"/&gt;
   &lt;m:brkBinSub m:val="&amp;#45;-"/&gt;
   &lt;m:smallFrac m:val="off"/&gt;
   &lt;m:dispDef/&gt;
   &lt;m:lMargin m:val="0"/&gt;
   &lt;m:rMargin m:val="0"/&gt;
   &lt;m:defJc m:val="centerGroup"/&gt;
   &lt;m:wrapIndent m:val="1440"/&gt;
   &lt;m:intLim m:val="subSup"/&gt;
   &lt;m:naryLim m:val="undOvr"/&gt;
  &lt;/m:mathPr&gt;&lt;/w:WordDocument&gt;
&lt;/xml&gt;&lt;![endif]--&gt;
&lt;!--[if gte mso 9]&gt;&lt;xml&gt;
 &lt;w:LatentStyles DefLockedState="false" DefUnhideWhenUsed="true"
  DefSemiHidden="true" DefQFormat="false" DefPriority="99"
  LatentStyleCount="267"&gt;
  &lt;w:LsdException Locked="false" Priority="0" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Normal"/&gt;
  &lt;w:LsdException Locked="false" Priority="9" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="heading 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 7"/&gt;
  &lt;w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 8"/&gt;
  &lt;w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 9"/&gt;
  &lt;w:LsdException Locked="false" Priority="39" Name="toc 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="39" Name="toc 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="39" Name="toc 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="39" Name="toc 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="39" Name="toc 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="39" Name="toc 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="39" Name="toc 7"/&gt;
  &lt;w:LsdException Locked="false" Priority="39" Name="toc 8"/&gt;
  &lt;w:LsdException Locked="false" Priority="39" Name="toc 9"/&gt;
  &lt;w:LsdException Locked="false" Priority="35" QFormat="true" Name="caption"/&gt;
  &lt;w:LsdException Locked="false" Priority="10" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Title"/&gt;
  &lt;w:LsdException Locked="false" Priority="1" Name="Default Paragraph Font"/&gt;
  &lt;w:LsdException Locked="false" Priority="11" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Subtitle"/&gt;
  &lt;w:LsdException Locked="false" Priority="22" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Strong"/&gt;
  &lt;w:LsdException Locked="false" Priority="20" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Emphasis"/&gt;
  &lt;w:LsdException Locked="false" Priority="59" SemiHidden="false"
   UnhideWhenUsed="false" Name="Table Grid"/&gt;
  &lt;w:LsdException Locked="false" UnhideWhenUsed="false" Name="Placeholder Text"/&gt;
  &lt;w:LsdException Locked="false" Priority="1" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="No Spacing"/&gt;
  &lt;w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading"/&gt;
  &lt;w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List"/&gt;
  &lt;w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid"/&gt;
  &lt;w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List"/&gt;
  &lt;w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading"/&gt;
  &lt;w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List"/&gt;
  &lt;w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid"/&gt;
  &lt;w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1 Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2 Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1 Accent 1"/&gt;
  &lt;w:LsdException Locked="false" UnhideWhenUsed="false" Name="Revision"/&gt;
  &lt;w:LsdException Locked="false" Priority="34" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="List Paragraph"/&gt;
  &lt;w:LsdException Locked="false" Priority="29" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Quote"/&gt;
  &lt;w:LsdException Locked="false" Priority="30" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Intense Quote"/&gt;
  &lt;w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2 Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1 Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2 Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3 Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid Accent 1"/&gt;
  &lt;w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1 Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2 Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1 Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2 Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1 Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2 Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3 Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid Accent 2"/&gt;
  &lt;w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1 Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2 Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1 Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2 Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1 Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2 Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3 Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid Accent 3"/&gt;
  &lt;w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1 Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2 Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1 Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2 Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1 Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2 Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3 Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid Accent 4"/&gt;
  &lt;w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1 Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2 Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1 Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2 Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1 Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2 Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3 Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid Accent 5"/&gt;
  &lt;w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1 Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2 Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1 Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2 Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1 Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2 Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3 Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid Accent 6"/&gt;
  &lt;w:LsdException Locked="false" Priority="19" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Subtle Emphasis"/&gt;
  &lt;w:LsdException Locked="false" Priority="21" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Intense Emphasis"/&gt;
  &lt;w:LsdException Locked="false" Priority="31" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Subtle Reference"/&gt;
  &lt;w:LsdException Locked="false" Priority="32" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Intense Reference"/&gt;
  &lt;w:LsdException Locked="false" Priority="33" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Book Title"/&gt;
  &lt;w:LsdException Locked="false" Priority="37" Name="Bibliography"/&gt;
  &lt;w:LsdException Locked="false" Priority="39" QFormat="true" Name="TOC Heading"/&gt;
 &lt;/w:LatentStyles&gt;
&lt;/xml&gt;&lt;![endif]--&gt;&lt;style&gt;
&lt;!--
 /* Font Definitions */
 @font-face
	{font-family:Calibri;
	panose-1:2 15 5 2 2 2 4 3 2 4;
	mso-font-charset:0;
	mso-generic-font-family:swiss;
	mso-font-pitch:variable;
	mso-font-signature:-520092929 1073786111 9 0 415 0;}
@font-face
	{font-family:Consolas;
	panose-1:2 11 6 9 2 2 4 3 2 4;
	mso-font-charset:0;
	mso-generic-font-family:modern;
	mso-font-pitch:fixed;
	mso-font-signature:-520092929 1073806591 9 0 415 0;}
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{mso-style-unhide:no;
	mso-style-qformat:yes;
	mso-style-parent:"";
	margin-top:0in;
	margin-right:0in;
	margin-bottom:10.0pt;
	margin-left:0in;
	line-height:115%;
	mso-pagination:widow-orphan;
	font-size:11.0pt;
	font-family:"Calibri","sans-serif";
	mso-ascii-font-family:Calibri;
	mso-ascii-theme-font:minor-latin;
	mso-fareast-font-family:Calibri;
	mso-fareast-theme-font:minor-latin;
	mso-hansi-font-family:Calibri;
	mso-hansi-theme-font:minor-latin;
	mso-bidi-font-family:"Times New Roman";
	mso-bidi-theme-font:minor-bidi;}
.MsoChpDefault
	{mso-style-type:export-only;
	mso-default-props:yes;
	font-family:"Calibri","sans-serif";
	mso-ascii-font-family:Calibri;
	mso-ascii-theme-font:minor-latin;
	mso-fareast-font-family:Calibri;
	mso-fareast-theme-font:minor-latin;
	mso-hansi-font-family:Calibri;
	mso-hansi-theme-font:minor-latin;
	mso-bidi-font-family:"Times New Roman";
	mso-bidi-theme-font:minor-bidi;}
.MsoPapDefault
	{mso-style-type:export-only;
	margin-bottom:10.0pt;
	line-height:115%;}
@page WordSection1
	{size:8.5in 11.0in;
	margin:1.0in 1.0in 1.0in 1.0in;
	mso-header-margin:.5in;
	mso-footer-margin:.5in;
	mso-paper-source:0;}
div.WordSection1
	{page:WordSection1;}
--&gt;
&lt;/style&gt;
&lt;!--[if gte mso 10]&gt;
&lt;style&gt;
 /* Style Definitions */
 table.MsoNormalTable
	{mso-style-name:"Table Normal";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-priority:99;
	mso-style-parent:"";
	mso-padding-alt:0in 5.4pt 0in 5.4pt;
	mso-para-margin-top:0in;
	mso-para-margin-right:0in;
	mso-para-margin-bottom:10.0pt;
	mso-para-margin-left:0in;
	line-height:115%;
	mso-pagination:widow-orphan;
	font-size:11.0pt;
	font-family:"Calibri","sans-serif";
	mso-ascii-font-family:Calibri;
	mso-ascii-theme-font:minor-latin;
	mso-hansi-font-family:Calibri;
	mso-hansi-theme-font:minor-latin;
	mso-bidi-font-family:"Times New Roman";
	mso-bidi-theme-font:minor-bidi;}
&lt;/style&gt;
&lt;![endif]--&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas; color: blue;"&gt;type&lt;/span&gt;&lt;span style="font-family: Consolas;"&gt; ProductMap() &lt;span style="color: blue;"&gt;as&lt;/span&gt; m
= &lt;span style="color: blue;"&gt;inherit&lt;/span&gt; ClassMapQ&amp;lt;Product&amp;gt;() &lt;span style="color: blue;"&gt;do&lt;/span&gt;
&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue;"&gt;let&lt;/span&gt; x
= m.DefaultX&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;m.Not.LazyLoad()&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;(m.IdQ
&amp;lt;@ x.Id @&amp;gt;).Done&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;(m.MapQ
&amp;lt;@ x.Name @&amp;gt;).Done&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;(m.MapQ
&amp;lt;@ x.Price @&amp;gt;).Done&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;(m.HasManyToManyQ
&amp;lt;@ seq x.StoresStockedIn @&amp;gt;)&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.LazyLoad()&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.Cascade.All()&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.Inverse()&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.Table(&lt;span style="color: maroon;"&gt;"StoreProduct"&lt;/span&gt;)&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.Done&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
&lt;o:p&gt;
&lt;br&gt;
&lt;/o:p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=88dc6738-246f-4ca8-a6b2-be5b23bdf59e" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,88dc6738-246f-4ca8-a6b2-be5b23bdf59e.aspx</comments>
      <category>Code</category>
      <category>FSharp</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=e66f49f0-22da-4fac-b100-f2a5b0a0ca29</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,e66f49f0-22da-4fac-b100-f2a5b0a0ca29.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,e66f49f0-22da-4fac-b100-f2a5b0a0ca29.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=e66f49f0-22da-4fac-b100-f2a5b0a0ca29</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Fluent NHibernate is a nice way to be able to use NHibernate without having to deal
with all that unchecked XML. This morning I decided to find out how well it works
with F#. Things went relatively smooth. I've converted some code samples from the <a href="http://wiki.fluentnhibernate.org/show/GettingStarted%3A+First+Project">Fluent
NHibernate First Project</a>. I suggest having that open to fill in any gaps. I've
also included the full project code and DB script at the end of this article.
</p>
        <p>
If you're not familiar at all with Fluent NHibernate, basically it takes advantage
of lambda expressions as Expression&lt;T&gt; to provide a somewhat strongly typechecked
reflection system. Thus, instead of having attributes with hard-coded strings, or
XML files, you have expressions that target the properties of objects you wish to
map. The Fluent NHibernate library then takes care of hooking it up to NHibernate,
and away you go. Something like that anyways.
</p>
        <p>
          <strong>Classes</strong>
        </p>
        <p>
So, first, we define the "entities" like the C# project does. Here's the first little
pain. F# doesn't really support C#'s idea of "automatic properties". You can have
vals on a class, which act like fields (although, they are implemented as properties).
Or, you can manually specify them, like you would in earlier versions of C# which
didn't have the auto-gen-a-field-for-me. 
</p>
        <p>
F# doesn't encourage uninitialized values. If you have uninitialized fields (vals),
you need to mark them with an attribute to say you know what you're doing. So, that
adds a bit more code overhead. What I do here is to alias the DefaultValueAttribute
to "DV". So the first bit of our classes looks like this:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt">
          <p style="MARGIN: 0px">
            <span style="COLOR: blue">#light</span>
          </p>
          <p style="MARGIN: 0px">
            <span style="COLOR: blue">namespace</span> FHib.Entities
</p>
          <p style="MARGIN: 0px">
 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: blue">open</span> System.Collections.Generic
</p>
          <p style="MARGIN: 0px">
 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: blue">type</span> DV = DefaultValueAttribute
</p>
          <p style="MARGIN: 0px">
 
</p>
          <p style="MARGIN: 0px">
            <span style="COLOR: blue">type</span> Employee() <span style="COLOR: blue">as</span> this
=
</p>
          <p style="MARGIN: 0px">
    [&lt;DV&gt;] <span style="COLOR: blue">val</span><span style="COLOR: blue">mutable</span> Id
: int
</p>
          <p style="MARGIN: 0px">
    [&lt;DV&gt;] <span style="COLOR: blue">val</span><span style="COLOR: blue">mutable</span> FirstName
: string
</p>
          <p style="MARGIN: 0px">
    [&lt;DV&gt;] <span style="COLOR: blue">val</span><span style="COLOR: blue">mutable</span> LastName
: string
</p>
        </div>
        <!--EndFragment-->
        <p>
Now, NHibernate relies on having virtual properties so that it can dynamically create
code to do nifty things like lazy loading. In F#, creating a virtual member means
defining an abstract member and providing an implementation, in the same class. Since
we don't have automatic properties, this means we'll have to define the backing field
ourselfs. In all, the full code for the virtual property "Store" (virtual so NHibernate
can lazy-load it) is:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt">
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">abstract</span> Store : Store <span style="COLOR: blue">with</span> get,set
</p>
          <p style="MARGIN: 0px">
    [&lt;DV(<span style="COLOR: blue">false</span>)&gt;] <span style="COLOR: blue">val</span><span style="COLOR: blue">mutable</span> _store
: Store
</p>
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">override</span> x.Store <span style="COLOR: blue">with</span> get()
= x._store <span style="COLOR: blue">and</span> set(v) = x._store &lt;- v
</p>
        </div>
        <!--EndFragment-->
        <p>
Not the pinnacle of short code, but not horrible all things considered. The rest
of the entity mappings are rather straightforward so I'll skip them here. I stuck
with vals for anything that didn't have to be virtual, to keep it more concise.
</p>
        <p>
          <strong>Mappings: Easy Start</strong>
        </p>
        <p>
OK, so now to the "real" work. Fluent NHiberate looks for classes that subclass
ClassMap&lt;T&gt;. It then creates an instance of them, which allows you to call the
mapping methods in the object's constructor. From the First Project:
</p>
        <pre>
          <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px">
            <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">public</span>
            <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">class</span> EmployeeMap
: ClassMap&lt;Employee&gt; { <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">public</span> EmployeeMap()
{ Id(x =&gt; x.Id); } } </span>
        </pre>
        <p>
OK, so how do we convert this to F#? It's easy... except for that lambda. The lambda
in this case compiles to an Expression&lt;Func&lt;Employee, object&gt;&gt;. F#'s compiler
does not support Expression&lt;T&gt;. So, we turn to experimental support. Referencing
the FSharp.PowerPack.Linq assembly gives us the Microsoft.FSharp.Linq.QuotationEvaluation
module. This extends the F# quotation type, Expr, with "ToLinqExpression", which returns
an untyped LINQ Expression object. 
</p>
        <p>
To get this untyped Expression (LINQ) out of an Expr (F#) and into an Expression&lt;T&gt;
(F#) suitable for Fluent NHibernate's consumption, I started off writing this tiny
helper module:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt">
          <p style="MARGIN: 0px">
            <span style="COLOR: blue">module</span> LinqHelper =
</p>
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">open</span> Microsoft.FSharp.Quotations
</p>
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">open</span> Microsoft.FSharp.Linq.QuotationEvaluation
</p>
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">open</span> System.Linq.Expressions
</p>
          <p style="MARGIN: 0px">
 
</p>
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">let</span> ToLinq (exp : Expr&lt;'a <span style="COLOR: blue">-&gt;</span> 'b&gt;)
=
</p>
          <p style="MARGIN: 0px">
        <span style="COLOR: blue">let</span> linq =
exp.ToLinqExpression()
</p>
          <p style="MARGIN: 0px">
        <span style="COLOR: blue">let</span> call =
linq :?&gt; MethodCallExpression
</p>
          <p style="MARGIN: 0px">
        <span style="COLOR: blue">let</span> lambda
= call.Arguments.[0] :?&gt; LambdaExpression
</p>
          <p style="MARGIN: 0px">
        Expression.Lambda&lt;Func&lt;'a, 'b&gt;&gt;(lambda.Body,
lambda.Parameters) 
</p>
        </div>
        <!--EndFragment-->
        <p>
When an F# quotation of a lambda is turned into a LINQ expression, the root node is
a useless MethodCallExpression. So, we unwrap that by taking it's argument and using
it to generate a typed lambda Expression&lt;T&gt;.  
</p>
        <p>
This is a good start. But many of the Expressions that Fluent NHibernate looks for
have a return type of object. Instead of having to write "box" or "upcast" all over,
I added another function called "ToLinqObj". This takes an Expr&lt;'a -&gt; 'b&gt;,
but returns an Expression&lt;Func&lt;'a, obj&gt;&gt;. 
</p>
        <p>
Finally, writing "ToLinq" and "ToLinqObj" seemed too verbose, so I added some operators
to the LinqHelper module:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt">
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">let</span> (~@) expr = ToLinq expr
</p>
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">let</span> (~@@) expr = ToLinqObj expr
</p>
        </div>
        <!--EndFragment-->
        <p>
Now we can start mapping:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt">
          <span style="COLOR: blue">
            <font color="#0000ff" size="3">
              <font color="#0000ff" size="3">
                <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt">
                  <p style="MARGIN: 0px">
                    <span style="COLOR: blue">open</span> LinqHelper
</p>
                  <p style="MARGIN: 0px">
 
</p>
                  <p style="MARGIN: 0px">
                    <span style="COLOR: blue">type</span> EmployeeMap() = <span style="COLOR: blue">inherit</span> ClassMap&lt;Employee&gt;() <span style="COLOR: blue">do</span></p>
                  <p style="MARGIN: 0px">
    <span style="COLOR: blue">base</span>.Not.LazyLoad()
</p>
                  <p style="MARGIN: 0px">
    <span style="COLOR: blue">base</span>.Id ~@@ &lt;@ <span style="COLOR: blue">fun</span> x <span style="COLOR: blue">-&gt;</span> x.Id
@&gt; |&gt; ignore
</p>
                  <p style="MARGIN: 0px">
    <span style="COLOR: blue">base</span>.Map ~@@ &lt;@ <span style="COLOR: blue">fun</span> x <span style="COLOR: blue">-&gt;</span> x.FirstName
@&gt; |&gt; ignore
</p>
                  <p style="MARGIN: 0px">
    <span style="COLOR: blue">base</span>.Map ~@@ &lt;@ <span style="COLOR: blue">fun</span> x <span style="COLOR: blue">-&gt;</span> x.LastName
@&gt; |&gt; ignore
</p>
                  <p style="MARGIN: 0px">
    (<span style="COLOR: blue">base</span>.References ~@ &lt;@ <span style="COLOR: blue">fun</span> x <span style="COLOR: blue">-&gt;</span> x.Store
@&gt;).LazyLoad() |&gt; ignore
</p>
                </div>
                <!--EndFragment-->
              </font>
            </font>
          </span>
        </div>
        <!--EndFragment-->
        <p>
We start off by disabling LazyLoad because most of the properties are not virtual,
and NHibernate will fail to validate the mapping. Instead, we explicitly LazyLoad
things, like the Store reference. 
</p>
        <p>
          <strong>Mappings: Modifying the Expressions</strong>
        </p>
        <p>
Unfortunately, things didn't stay so simple. The Fluent NHibernate methods "HasMany"
and "HasManyToMany", for instance, don't work with F#'s type inference. This is because
they have several overloads, a couple of which take expressions. If we try this in
the StoreMap:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt">
          <p style="MARGIN: 0px">
            <span style="COLOR: blue">    base</span>.HasMany ~@@ &lt;@ <span style="COLOR: blue">fun</span> x <span style="COLOR: blue">-&gt;</span> x.Staff
@&gt; |&gt; ignore
</p>
        </div>
        <!--EndFragment-->
        <p>
We get an error because F# doesn't know what x is. (error FS0055: This lookup uses
a deprecated feature, where a class type is inferred from the use of a class field
label. Consider using a type annotation to make it clear which class the field comes
from.) Using ~@ to keep it strongly typed fails as well; it can't figure out the overload.
This is nothing surprising -- overloading is the enemy of type inference.
</p>
        <p>
So, what do we do? Type annotations are not what I consider fun. So instead, we'll
add non-overloaded ClassMap&lt;'t&gt; type extensions into the LinqHelper module:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt">
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">type</span> ClassMap&lt;'t&gt; <span style="COLOR: blue">with</span></p>
          <p style="MARGIN: 0px">
        <span style="COLOR: blue">member</span> x.HasManyX
expr = (x.HasMany : Expression&lt;Func&lt;'t, seq&lt;_&gt;&gt;&gt; <span style="COLOR: blue">-&gt;</span> _)
(ToLinq expr)
</p>
          <p style="MARGIN: 0px">
        <span style="COLOR: blue">member</span> x.HasManyToManyX
expr = (x.HasManyToMany : Expression&lt;Func&lt;'t, seq&lt;_&gt;&gt;&gt; <span style="COLOR: blue">-&gt;</span> _)
(ToLinq expr)
</p>
        </div>
        <!--EndFragment-->
        <p>
By providing these extensions that are explicit once, we enable type inference for
the rest of the time. We can now finish the StoreMap:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt">
          <p style="MARGIN: 0px">
            <span style="COLOR: blue">type</span> StoreMap() = <span style="COLOR: blue">inherit</span> ClassMap&lt;Store&gt;() <span style="COLOR: blue">do</span></p>
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">base</span>.Not.LazyLoad()
</p>
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">base</span>.Id ~@@ &lt;@ <span style="COLOR: blue">fun</span> x <span style="COLOR: blue">-&gt;</span> x.Id
@&gt; |&gt; ignore
</p>
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">base</span>.Map ~@@ &lt;@ <span style="COLOR: blue">fun</span> x <span style="COLOR: blue">-&gt;</span> x.Name
@&gt; |&gt; ignore
</p>
          <p style="MARGIN: 0px">
 
</p>
          <p style="MARGIN: 0px">
    (<span style="COLOR: blue">base</span>.HasManyX &lt;@ <span style="COLOR: blue">fun</span> x <span style="COLOR: blue">-&gt;</span><span style="COLOR: blue">upcast</span> x.Staff
@&gt;)
</p>
          <p style="MARGIN: 0px">
        .LazyLoad()
</p>
          <p style="MARGIN: 0px">
        .Inverse().Cascade.All() |&gt; ignore
</p>
          <p style="MARGIN: 0px">
    (<span style="COLOR: blue">base</span>.HasManyToManyX &lt;@ <span style="COLOR: blue">fun</span> x <span style="COLOR: blue">-&gt;</span><span style="COLOR: blue">upcast</span> x.Products
@&gt;)
</p>
          <p style="MARGIN: 0px">
        .Cascade.All()
</p>
          <p style="MARGIN: 0px">
        .WithTableName(<span style="COLOR: maroon">"StoreProduct"</span>)
|&gt; ignore
</p>
        </div>
        <!--EndFragment-->
        <p>
The only type "annotation" we need here is the upcast for the HasManyX. This
is because F# forces you to be explicit. Accessing "Staff" in the first quotation
means type IList&lt;Employee&gt;, not seq&lt;Employee&gt;. The upcast will sort this
out for us.
</p>
        <p>
This compiles fine. But remember how I said using expressions was a "somewhat strongly
typed" way of doing things? The expression trees are interpreted at runtime, which
allows failures a more complex type system might prevent. This is one of the times.
If we try to execute it as-is, we get this exception:
</p>
        <p>
          <font face="Courier New"> ---&gt; FluentNHibernate.Cfg.FluentConfigurationException:
An invalid or incomplete configuration was used while creating a SessionFactory. Check
PotentialReasons collection, and InnerException for more detail.</font>
        </p>
        <p>
          <font face="Courier New"> ---&gt; System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation. ---&gt; System.ArgumentException:
Not a member access Parameter name: member</font>
        </p>
        <p>
Ouch. Fluent NHibernate does not appreciate our expression trees. Why? Using FSI,
we can inspect what we're actually converting the F# quotations to:
</p>
        <p>
          <font face="Courier New">type SomeClass() = member x.Stuff = [|1;2;3|];;<br />
let myExpr : Expr&lt;SomeClass -&gt; seq&lt;int&gt;&gt; = &lt;@ fun x -&gt; upcast
x.Stuff @&gt;;;<br />
let myLinq = LinqHelper.ToLinq myExpr;;</font>
        </p>
        <p>
          <font face="Courier New">&gt; myLinq;;<br />
val it : Linq.Expressions.Expression&lt;Func&lt;SomeClass,seq&lt;int&gt;&gt;&gt;<br />
= x =&gt; (x.Stuff As IEnumerable`1)<br />
    {Body = (x.Stuff As IEnumerable`1);<br />
     NodeType = Lambda;<br />
     Parameters = seq [x];<br />
     Type = System.Func`2[FSI_0022+SomeClass,System.Collections.Generic.IEnumerable`1[System.Int32]];}</font>
        </p>
        <p>
          <font face="Courier New">&gt; myLinq.Body;;<br />
val it : Linq.Expressions.Expression<br />
= (x.Stuff As IEnumerable`1)<br />
    {IsLifted = false;<br />
     IsLiftedToNull = false;<br />
     Method = null;<br />
     NodeType = TypeAs;<br />
     Operand = x.Stuff;<br />
     Type = System.Collections.Generic.IEnumerable`1[System.Int32];}</font>
        </p>
        <p>
So, what's going on? The upcast is modifying the F# quotation (as it should), and
the ToLinqExpression is sticking this in as a "TypeAs" node. Fluent NHibernate does
not seem to like this. Not. One. Bit.
</p>
        <p>
But, it IS ok if we have a Convert node in the Expression tree. I imagine this is
because C# generates such nodes in its expression trees (say, accessing an int member
in a Func&lt;T, object&gt; expression). So, our last hack in making F# work right
here is adding a fixup function to our LinqHelper, and using it from ToLinq:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt">
          <p style="MARGIN: 0px">
    <span style="COLOR: blue">let</span> fixup (lexpr:LambdaExpression)
= 
</p>
          <p style="MARGIN: 0px">
        <span style="COLOR: blue">if</span> lexpr.Body.NodeType
&lt;&gt; ExpressionType.TypeAs <span style="COLOR: blue">then</span> lexpr <span style="COLOR: blue">else</span></p>
          <p style="MARGIN: 0px">
        <span style="COLOR: blue">let</span> typeAs
= lexpr.Body :?&gt; UnaryExpression
</p>
          <p style="MARGIN: 0px">
        <span style="COLOR: blue">let</span> newBody
= Expression.Convert(typeAs.Operand, typeAs.Type)
</p>
          <p style="MARGIN: 0px">
        Expression.Lambda(lexpr.Type, newBody, lexpr.Parameters)
</p>
        </div>
        <!--EndFragment-->
        <p>
Now it's happy with our expressions. 
</p>
        <p>
          <strong>Finally</strong>
        </p>
        <p>
The rest of the First Project is pretty straightforward in F#. For instance, creating
the Session Factory:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt">
          <p style="MARGIN: 0px">
            <span style="COLOR: blue">let</span> createSessionFactory() = 
</p>
          <p style="MARGIN: 0px">
    Fluently.Configure()
</p>
          <p style="MARGIN: 0px">
        .Database(
</p>
          <p style="MARGIN: 0px">
            MsSqlConfiguration.MsSql2005.ConnectionString(<span style="COLOR: blue">fun</span> csb <span style="COLOR: blue">-&gt;</span></p>
          <p style="MARGIN: 0px">
                csb.Is(<span style="COLOR: maroon">"server=(local);database=fhib;Integrated
Security=true"</span>) |&gt; ignore))
</p>
          <p style="MARGIN: 0px">
        .Mappings(<span style="COLOR: blue">fun</span> m <span style="COLOR: blue">-&gt;</span></p>
          <p style="MARGIN: 0px">
            m.FluentMappings.AddFromAssemblyOf&lt;Mappings.EmployeeMap&gt;()
|&gt; ignore)
</p>
          <p style="MARGIN: 0px">
        .BuildSessionFactory()
</p>
        </div>
        <!--EndFragment-->
        <p>
Everything seems to execute as it should. Fluent interfaces in F# generate a bit more
noise, because of all the ignores that have to be added. I'm thinking of creating
a type extension to obj to add Ignore as a method, to make it look a bit more uniform.
</p>
        <p>
          <strong>Future</strong>
        </p>
        <p>
It's my hope that F# has now addressed most of these issues -- 1.9.6 is 7 months old.
Expression&lt;T&gt; is growing in importance, outside of LINQ querying, so I cannot
see F# not being able to handle them easily and generating similar output to C#. It'd
be really neat if F# would auto-convert quotations to Expression&lt;T&gt; when the expr
is a syntactic argument like it does with delegates now. I'd also be surprised
if abstract/virtual members still lack the ability to define accessibility. 
</p>
        <p>
Code: <a href="http://www.atrevido.net/blog/content/binary/fhib.zip">fhib.zip (4.76
KB)</a><br />
I did not include Fluent NHibernate or any of its dependencies. The project expects
them to be in the project's lib folder, so get them <a href="http://fluentnhibernate.org/downloads">here</a> if
you don't have them and extract them to "lib".
</p>
        <p>
I welcome comments on this and suggestions for making the code more concise.
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=e66f49f0-22da-4fac-b100-f2a5b0a0ca29" />
      </body>
      <title>Using Fluent NHibernate with F#</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,e66f49f0-22da-4fac-b100-f2a5b0a0ca29.aspx</guid>
      <link>http://www.atrevido.net/blog/2009/04/01/Using+Fluent+NHibernate+With+F.aspx</link>
      <pubDate>Wed, 01 Apr 2009 08:01:29 GMT</pubDate>
      <description>&lt;p&gt;
Fluent NHibernate is a nice way to be able to use NHibernate without having to deal
with all that unchecked XML. This morning I decided to find out how well it works
with F#. Things went relatively smooth. I've converted some code samples from the &lt;a href="http://wiki.fluentnhibernate.org/show/GettingStarted%3A+First+Project"&gt;Fluent
NHibernate First Project&lt;/a&gt;. I suggest having that open to fill in any gaps. I've
also included the full project code and DB script at the end of this article.
&lt;/p&gt;
&lt;p&gt;
If you're not familiar at all with Fluent NHibernate, basically it takes advantage
of lambda expressions as Expression&amp;lt;T&amp;gt; to provide a somewhat strongly typechecked
reflection system. Thus, instead of having attributes with hard-coded strings, or
XML files, you have expressions that target the properties of objects you wish to
map. The Fluent NHibernate library then takes care of hooking it up to NHibernate,
and away you go. Something like that anyways.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Classes&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
So, first, we define the "entities" like the C# project does. Here's the first little
pain. F# doesn't really support C#'s idea of "automatic properties". You can have
vals on a class, which act like fields (although, they are implemented as properties).
Or, you can manually specify them, like you would in earlier versions of C# which
didn't have the auto-gen-a-field-for-me. 
&lt;/p&gt;
&lt;p&gt;
F# doesn't encourage uninitialized values. If you have uninitialized fields (vals),
you need to mark them with an attribute to say you know what you're doing. So, that
adds a bit more code overhead. What I do here is to alias the DefaultValueAttribute
to "DV". So the first bit of our classes looks like this:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;#light&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;namespace&lt;/span&gt; FHib.Entities
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;open&lt;/span&gt; System.Collections.Generic
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;type&lt;/span&gt; DV = DefaultValueAttribute
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;type&lt;/span&gt; Employee() &lt;span style="COLOR: blue"&gt;as&lt;/span&gt; this
=
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; [&amp;lt;DV&amp;gt;] &lt;span style="COLOR: blue"&gt;val&lt;/span&gt; &lt;span style="COLOR: blue"&gt;mutable&lt;/span&gt; Id
: int
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; [&amp;lt;DV&amp;gt;] &lt;span style="COLOR: blue"&gt;val&lt;/span&gt; &lt;span style="COLOR: blue"&gt;mutable&lt;/span&gt; FirstName
: string
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; [&amp;lt;DV&amp;gt;] &lt;span style="COLOR: blue"&gt;val&lt;/span&gt; &lt;span style="COLOR: blue"&gt;mutable&lt;/span&gt; LastName
: string
&lt;/p&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
Now, NHibernate relies on having virtual properties so that it can dynamically create
code to do nifty things like lazy loading. In F#, creating a virtual member means
defining an abstract member and providing an implementation, in the same class. Since
we don't have automatic properties, this means we'll have to define the backing field
ourselfs. In all, the full code for the virtual property "Store" (virtual so NHibernate
can lazy-load it) is:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;abstract&lt;/span&gt; Store : Store &lt;span style="COLOR: blue"&gt;with&lt;/span&gt; get,set
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; [&amp;lt;DV(&lt;span style="COLOR: blue"&gt;false&lt;/span&gt;)&amp;gt;] &lt;span style="COLOR: blue"&gt;val&lt;/span&gt; &lt;span style="COLOR: blue"&gt;mutable&lt;/span&gt; _store
: Store
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;override&lt;/span&gt; x.Store &lt;span style="COLOR: blue"&gt;with&lt;/span&gt; get()
= x._store &lt;span style="COLOR: blue"&gt;and&lt;/span&gt; set(v) = x._store &amp;lt;- v
&lt;/p&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
Not the pinnacle of short code, but not horrible all things considered.&amp;nbsp;The rest
of the entity mappings are rather straightforward so I'll skip them here. I stuck
with vals for anything that didn't have to be virtual, to keep it more concise.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Mappings: Easy Start&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
OK, so now to the "real" work.&amp;nbsp;Fluent NHiberate looks for classes that subclass
ClassMap&amp;lt;T&amp;gt;. It then creates an instance of them, which allows you to call the
mapping methods in the object's constructor.&amp;nbsp;From the First Project:
&lt;/p&gt;
&lt;pre&gt;&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px"&gt;&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;public&lt;/span&gt; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;class&lt;/span&gt; EmployeeMap
: ClassMap&amp;lt;Employee&amp;gt; { &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;public&lt;/span&gt; EmployeeMap()
{ Id(x =&amp;gt; x.Id); } } &lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
OK, so how do we convert this to F#? It's easy... except for that lambda. The lambda
in this case compiles to an Expression&amp;lt;Func&amp;lt;Employee, object&amp;gt;&amp;gt;. F#'s compiler
does not support Expression&amp;lt;T&amp;gt;. So, we turn to experimental support. Referencing
the FSharp.PowerPack.Linq assembly gives us the Microsoft.FSharp.Linq.QuotationEvaluation
module. This extends the F# quotation type, Expr, with "ToLinqExpression", which returns
an untyped LINQ Expression object. 
&lt;/p&gt;
&lt;p&gt;
To get this untyped Expression (LINQ) out of an Expr (F#) and into an Expression&amp;lt;T&amp;gt;
(F#) suitable for Fluent NHibernate's consumption, I started off writing this tiny
helper module:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;module&lt;/span&gt; LinqHelper =
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;open&lt;/span&gt; Microsoft.FSharp.Quotations
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;open&lt;/span&gt; Microsoft.FSharp.Linq.QuotationEvaluation
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;open&lt;/span&gt; System.Linq.Expressions
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; ToLinq (exp : Expr&amp;lt;'a &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; 'b&amp;gt;)
=
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; linq =
exp.ToLinqExpression()
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; call =
linq :?&amp;gt; MethodCallExpression
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; lambda
= call.Arguments.[0] :?&amp;gt; LambdaExpression
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; Expression.Lambda&amp;lt;Func&amp;lt;'a, 'b&amp;gt;&amp;gt;(lambda.Body,
lambda.Parameters) 
&lt;/p&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
When an F# quotation of a lambda is turned into a LINQ expression, the root node is
a useless MethodCallExpression. So, we unwrap that by taking it's argument and using
it to generate a typed lambda Expression&amp;lt;T&amp;gt;.&amp;nbsp;&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
This is a good start. But many of the Expressions that Fluent NHibernate looks for
have a return type of object. Instead of having to write "box" or "upcast" all over,
I added another function called "ToLinqObj". This takes an Expr&amp;lt;'a -&amp;gt; 'b&amp;gt;,
but returns an Expression&amp;lt;Func&amp;lt;'a, obj&amp;gt;&amp;gt;. 
&lt;/p&gt;
&lt;p&gt;
Finally, writing "ToLinq" and "ToLinqObj" seemed too verbose, so I added some operators
to the LinqHelper module:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; (~@) expr = ToLinq expr
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; (~@@) expr = ToLinqObj expr
&lt;/p&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
Now we can start mapping:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt"&gt;&lt;span style="COLOR: blue"&gt;&lt;font color=#0000ff size=3&gt;&lt;font color=#0000ff size=3&gt; 
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;open&lt;/span&gt; LinqHelper
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;type&lt;/span&gt; EmployeeMap() = &lt;span style="COLOR: blue"&gt;inherit&lt;/span&gt; ClassMap&amp;lt;Employee&amp;gt;() &lt;span style="COLOR: blue"&gt;do&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;base&lt;/span&gt;.Not.LazyLoad()
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;base&lt;/span&gt;.Id ~@@ &amp;lt;@ &lt;span style="COLOR: blue"&gt;fun&lt;/span&gt; x &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; x.Id
@&amp;gt; |&amp;gt; ignore
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;base&lt;/span&gt;.Map ~@@ &amp;lt;@ &lt;span style="COLOR: blue"&gt;fun&lt;/span&gt; x &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; x.FirstName
@&amp;gt; |&amp;gt; ignore
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;base&lt;/span&gt;.Map ~@@ &amp;lt;@ &lt;span style="COLOR: blue"&gt;fun&lt;/span&gt; x &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; x.LastName
@&amp;gt; |&amp;gt; ignore
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; (&lt;span style="COLOR: blue"&gt;base&lt;/span&gt;.References ~@ &amp;lt;@ &lt;span style="COLOR: blue"&gt;fun&lt;/span&gt; x &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; x.Store
@&amp;gt;).LazyLoad() |&amp;gt; ignore
&lt;/p&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;&lt;/font&gt;&lt;/font&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
We start off by disabling LazyLoad because most of the properties are not virtual,
and NHibernate will fail to validate the mapping. Instead, we explicitly LazyLoad
things, like the Store reference. 
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Mappings: Modifying the Expressions&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Unfortunately, things didn't stay so simple. The Fluent NHibernate methods "HasMany"
and "HasManyToMany", for instance, don't work with F#'s type inference. This is because
they have several overloads, a couple of which take expressions. If we try this in
the StoreMap:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; base&lt;/span&gt;.HasMany ~@@ &amp;lt;@ &lt;span style="COLOR: blue"&gt;fun&lt;/span&gt; x &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; x.Staff
@&amp;gt; |&amp;gt; ignore
&lt;/p&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
We get an error because F# doesn't know what x is. (error FS0055: This lookup uses
a deprecated feature, where a class type is inferred from the use of a class field
label. Consider using a type annotation to make it clear which class the field comes
from.) Using ~@ to keep it strongly typed fails as well; it can't figure out the overload.
This is nothing surprising -- overloading is the enemy of type inference.
&lt;/p&gt;
&lt;p&gt;
So, what do we do? Type annotations are not what I consider fun. So instead, we'll
add non-overloaded ClassMap&amp;lt;'t&amp;gt; type extensions into the LinqHelper module:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;type&lt;/span&gt; ClassMap&amp;lt;'t&amp;gt; &lt;span style="COLOR: blue"&gt;with&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;member&lt;/span&gt; x.HasManyX
expr = (x.HasMany : Expression&amp;lt;Func&amp;lt;'t, seq&amp;lt;_&amp;gt;&amp;gt;&amp;gt; &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; _)
(ToLinq expr)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;member&lt;/span&gt; x.HasManyToManyX
expr = (x.HasManyToMany : Expression&amp;lt;Func&amp;lt;'t, seq&amp;lt;_&amp;gt;&amp;gt;&amp;gt; &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; _)
(ToLinq expr)
&lt;/p&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
By providing these extensions that are explicit once, we enable type inference for
the rest of the time. We can now finish the StoreMap:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;type&lt;/span&gt; StoreMap() = &lt;span style="COLOR: blue"&gt;inherit&lt;/span&gt; ClassMap&amp;lt;Store&amp;gt;() &lt;span style="COLOR: blue"&gt;do&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;base&lt;/span&gt;.Not.LazyLoad()
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;base&lt;/span&gt;.Id ~@@ &amp;lt;@ &lt;span style="COLOR: blue"&gt;fun&lt;/span&gt; x &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; x.Id
@&amp;gt; |&amp;gt; ignore
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;base&lt;/span&gt;.Map ~@@ &amp;lt;@ &lt;span style="COLOR: blue"&gt;fun&lt;/span&gt; x &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; x.Name
@&amp;gt; |&amp;gt; ignore
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; (&lt;span style="COLOR: blue"&gt;base&lt;/span&gt;.HasManyX &amp;lt;@ &lt;span style="COLOR: blue"&gt;fun&lt;/span&gt; x &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; &lt;span style="COLOR: blue"&gt;upcast&lt;/span&gt; x.Staff
@&amp;gt;)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; .LazyLoad()
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; .Inverse().Cascade.All() |&amp;gt; ignore
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; (&lt;span style="COLOR: blue"&gt;base&lt;/span&gt;.HasManyToManyX &amp;lt;@ &lt;span style="COLOR: blue"&gt;fun&lt;/span&gt; x &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; &lt;span style="COLOR: blue"&gt;upcast&lt;/span&gt; x.Products
@&amp;gt;)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; .Cascade.All()
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; .WithTableName(&lt;span style="COLOR: maroon"&gt;"StoreProduct"&lt;/span&gt;)
|&amp;gt; ignore
&lt;/p&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
The only type "annotation" we need here&amp;nbsp;is the upcast for the HasManyX. This
is because F# forces you to be explicit. Accessing "Staff" in the first quotation
means type IList&amp;lt;Employee&amp;gt;, not seq&amp;lt;Employee&amp;gt;. The upcast will sort this
out for us.
&lt;/p&gt;
&lt;p&gt;
This compiles fine. But remember how I said using expressions was a "somewhat strongly
typed" way of doing things? The expression trees are interpreted at runtime, which
allows failures a more complex type system might prevent. This is one of the times.
If we try to execute it as-is, we get this exception:
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;&amp;nbsp;---&amp;gt; FluentNHibernate.Cfg.FluentConfigurationException:
An invalid or incomplete configuration was used while creating a SessionFactory. Check
PotentialReasons collection, and InnerException for more detail.&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;&amp;nbsp;---&amp;gt; System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation. ---&amp;gt; System.ArgumentException:
Not a member access Parameter name: member&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
Ouch. Fluent NHibernate does not appreciate our expression trees. Why? Using FSI,
we can inspect what we're actually converting the F# quotations to:
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;type SomeClass() = member x.Stuff = [|1;2;3|];;&lt;br&gt;
let myExpr : Expr&amp;lt;SomeClass -&amp;gt; seq&amp;lt;int&amp;gt;&amp;gt; = &amp;lt;@ fun x -&amp;gt; upcast
x.Stuff @&amp;gt;;;&lt;br&gt;
let myLinq = LinqHelper.ToLinq myExpr;;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;&amp;gt; myLinq;;&lt;br&gt;
val it : Linq.Expressions.Expression&amp;lt;Func&amp;lt;SomeClass,seq&amp;lt;int&amp;gt;&amp;gt;&amp;gt;&lt;br&gt;
= x =&amp;gt; (x.Stuff As IEnumerable`1)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {Body = (x.Stuff As IEnumerable`1);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; NodeType = Lambda;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Parameters = seq [x];&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Type = System.Func`2[FSI_0022+SomeClass,System.Collections.Generic.IEnumerable`1[System.Int32]];}&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;&amp;gt; myLinq.Body;;&lt;br&gt;
val it : Linq.Expressions.Expression&lt;br&gt;
= (x.Stuff As IEnumerable`1)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {IsLifted = false;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; IsLiftedToNull = false;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Method = null;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; NodeType = TypeAs;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Operand = x.Stuff;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Type = System.Collections.Generic.IEnumerable`1[System.Int32];}&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
So, what's going on? The upcast is modifying the F# quotation (as it should), and
the ToLinqExpression is sticking this in as a "TypeAs" node. Fluent NHibernate does
not seem to like this. Not. One. Bit.
&lt;/p&gt;
&lt;p&gt;
But, it IS ok if we have a Convert node in the Expression tree. I imagine this is
because C# generates such nodes in its expression trees (say, accessing an int member
in a Func&amp;lt;T, object&amp;gt; expression). So, our last hack in making F# work right
here is adding a fixup function to our LinqHelper, and using it from ToLinq:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; fixup (lexpr:LambdaExpression)
= 
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;if&lt;/span&gt; lexpr.Body.NodeType
&amp;lt;&amp;gt; ExpressionType.TypeAs &lt;span style="COLOR: blue"&gt;then&lt;/span&gt; lexpr &lt;span style="COLOR: blue"&gt;else&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; typeAs
= lexpr.Body :?&amp;gt; UnaryExpression
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; newBody
= Expression.Convert(typeAs.Operand, typeAs.Type)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; Expression.Lambda(lexpr.Type, newBody, lexpr.Parameters)
&lt;/p&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
Now it's happy with our expressions. 
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Finally&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
The rest of the First Project is pretty straightforward in F#. For instance, creating
the Session Factory:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;let&lt;/span&gt; createSessionFactory() = 
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Fluently.Configure()
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; .Database(
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; MsSqlConfiguration.MsSql2005.ConnectionString(&lt;span style="COLOR: blue"&gt;fun&lt;/span&gt; csb &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt; 
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; csb.Is(&lt;span style="COLOR: maroon"&gt;"server=(local);database=fhib;Integrated
Security=true"&lt;/span&gt;) |&amp;gt; ignore))
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; .Mappings(&lt;span style="COLOR: blue"&gt;fun&lt;/span&gt; m &lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; m.FluentMappings.AddFromAssemblyOf&amp;lt;Mappings.EmployeeMap&amp;gt;()
|&amp;gt; ignore)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; .BuildSessionFactory()
&lt;/p&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
Everything seems to execute as it should. Fluent interfaces in F# generate a bit more
noise, because of all the ignores that have to be added. I'm thinking of creating
a type extension to obj to add Ignore as a method, to make it look a bit more uniform.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Future&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
It's my hope that F# has now addressed most of these issues -- 1.9.6 is 7 months old.
Expression&amp;lt;T&amp;gt; is growing in importance, outside of LINQ querying, so I cannot
see F# not being able to handle them easily and generating similar output to C#. It'd
be really neat if F# would auto-convert quotations to Expression&amp;lt;T&amp;gt; when the&amp;nbsp;expr
is a syntactic argument like it does with delegates now.&amp;nbsp;I'd also be surprised
if abstract/virtual members still lack the ability to define accessibility. 
&lt;/p&gt;
&lt;p&gt;
Code: &lt;a href="http://www.atrevido.net/blog/content/binary/fhib.zip"&gt;fhib.zip (4.76
KB)&lt;/a&gt;
&lt;br&gt;
I did not include Fluent NHibernate or any of its dependencies. The project expects
them to be in the project's lib folder, so get them &lt;a href="http://fluentnhibernate.org/downloads"&gt;here&lt;/a&gt; if
you don't have them and extract them to "lib".
&lt;/p&gt;
&lt;p&gt;
I welcome comments on this and suggestions for making the code more concise.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=e66f49f0-22da-4fac-b100-f2a5b0a0ca29" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,e66f49f0-22da-4fac-b100-f2a5b0a0ca29.aspx</comments>
      <category>Code</category>
      <category>FSharp</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=9bb60288-03e1-4610-bf72-8326c62f1358</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,9bb60288-03e1-4610-bf72-8326c62f1358.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,9bb60288-03e1-4610-bf72-8326c62f1358.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=9bb60288-03e1-4610-bf72-8326c62f1358</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This entry was triggered by <a href="http://stackoverflow.com/questions/667887/aes-in-asp-net-with-vb-net/668258">this
question</a>. Someone asked how to use AES, and we got 2 sample classes that do it
wrong. The flaw in both was that they shared the IV which means your ciphertext will
can leak information. One answerer didn't believe me at first, but then got it and
deleted his code. The other person got offended and said IVs, performing authentication,
etc. are all "corner cases" and any problem is "contrived". So, I'm going to provide
a bit of code and show two problems that arise from not generating a unique IV for
each message and not authenticating the decrypted data.
</p>
        <p>
First, I wrote this a while ago: <a href="http://www.atrevido.net/blog/PermaLink,guid,6136ce81-9fa1-4995-bb3e-15bc5f1f5899.aspx">What
is an IV?</a>. That describes what an IV is, and why you need a unique one for each
message. Wikipedia also has good information on this. Now for the demo. I used the
code at the bottom, but removed the hashing and random IV from the code. So it's just
encrypting the with the same key and IV for each message -- very straightforward.
Here are the messages and their ciphertext:
</p>
        <p>
"Alice; Bob; Eve;: PerformAct1"<br />
"Alice; Bob; Eve;: PerformAct2"
</p>
        <p>
tZfHJSFTXYX8V38AqEfYVXU5Dl/meUVAond70yIKGHY= 
<br />
tZfHJSFTXYX8V38AqEfYVcf9a3U8vIEk1LuqGEyRZXM=
</p>
        <p>
Notice how the first block of ciphertext is the same? All messages starting with "Alice;
Bob; Eve;" will have that same first block. That means an attacker, after getting
this ciphertext once, now knows if any message is addressed the same way. Very, very
straightforward, basic attack. Now, maybe for a specific implementation you have in
mind, this is not an issue. But it's still improperly implemented cryptography.
</p>
        <p>
For the next attack, we're going to show that even with a random IV, you need to authenticate
your decrypted messages. This code generates a 64-bit integer and encrypts it with
AES and a random key/IV. Then, it starts changing bytes until the decrypt succeeds.
Presto: the attacker was able to present a completely different value, and the decryption
was successful.
</p>
        <p>
          <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px">
            <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">public</span>
            <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">static</span>
            <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">void</span> Main()
{<br />
    var buff <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">=</span><span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">new</span><span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">byte</span>[8];<br />
    <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">new</span> Random().NextBytes(buff);<br />
    var v <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">=</span> BitConverter.ToUInt64(buff,
0);<br />
    Console.WriteLine(<span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px">"Value:
"</span><span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">+</span> v.ToString());<br />
    Console.WriteLine(<span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px">"Value
(bytes): "</span><span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">+</span> BitConverter.ToString(BitConverter.GetBytes(v)));<br />
    var aes <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">=</span> Aes.Create();<br />
    aes.GenerateIV();<br />
    aes.GenerateKey();<br />
    var encBytes <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">=</span> aes.CreateEncryptor().TransformFinalBlock(BitConverter.GetBytes(v),
0, 8);<br />
    Console.WriteLine(<span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px">"Encrypted:
"</span><span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">+</span> BitConverter.ToString(encBytes));<br />
    var dec <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">=</span> aes.CreateDecryptor();<br />
    Console.WriteLine(<span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px">"Decrypted:
"</span><span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">+</span> BitConverter.ToUInt64(dec.TransformFinalBlock(encBytes,
0, encBytes.Length), 0));<br />
    <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">for</span> (<span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">int</span> i <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">=</span> 0;
i &lt; 8; i++) {<br />
        <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">for</span> (<span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">int</span> x <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">=</span> 0;
x &lt; 250; x++) {<br />
            encBytes[i]++;<br />
            <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">try</span> {<br />
               
Console.WriteLine(<span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px">"Attacked:
"</span><span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">+</span> BitConverter.ToUInt64(dec.TransformFinalBlock(encBytes,
0, encBytes.Length), 0));<br />
    </span>
          <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px">            <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">return</span>;<br />
            } <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">catch</span> {
}<br />
        }<br />
    }<br />
}</span>
        </p>
        <pre>
          <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px">
            <font size="2" face="Verdana">Here's
an example run:</font>
          </span>
        </pre>
        <pre>
          <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px">Value:
5686260040031435365<br />
Value (bytes): 65-7A-92-1A-61-A7-E9-4E<br />
Encrypted: F4-62-AC-02-2D-7D-43-6A-4D-97-68-4D-95-9F-8A-DF<br />
Decrypted: 5686260040031435365<br />
Attacked: 1603329786558177755</span>
        </pre>
        <pre>
          <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px">
          </span>
        </pre>
        <p>
Since there's no authentication of the decrypted data, an attacker can just play with
the ciphertext until it generates an acceptable value. Perhaps you have other mitigations
in your implementation/application for this, but why rely on that?
</p>
        <p>
Here's some demo code (I haven't tested it much, so it might have some major issues
-- but not by design AFAIK). Note this just shows performing an encryption operation,
including the IV in the message, and verifying the decrypted bytes. Other things like
replay attacks are not considered. If you're trying to learn how to use crypto so
you can drop it into an application, STOP, then go read enough to understand
what you're doing and the implications for your particular application.
</p>
        <p>
          <a href="http://www.atrevido.net/blog/content/binary/aesdemo.cs.txt">aesdemo.cs.txt
(4.38 KB)</a>
        </p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=9bb60288-03e1-4610-bf72-8326c62f1358" />
      </body>
      <title>Using symmetric encryption to pass messages</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,9bb60288-03e1-4610-bf72-8326c62f1358.aspx</guid>
      <link>http://www.atrevido.net/blog/2009/03/22/Using+Symmetric+Encryption+To+Pass+Messages.aspx</link>
      <pubDate>Sun, 22 Mar 2009 23:46:56 GMT</pubDate>
      <description>&lt;p&gt;
This entry was triggered by &lt;a href="http://stackoverflow.com/questions/667887/aes-in-asp-net-with-vb-net/668258"&gt;this
question&lt;/a&gt;. Someone asked how to use AES, and we got 2 sample classes that do it
wrong. The flaw in both was that they shared the IV which means your ciphertext will
can leak information. One answerer didn't believe me at first, but then got it and
deleted his code. The other person got offended and said IVs, performing authentication,
etc. are all "corner cases" and any problem is "contrived". So, I'm going to provide
a bit of code and show two problems that arise from not generating a unique IV for
each message and not authenticating the decrypted data.
&lt;/p&gt;
&lt;p&gt;
First, I wrote this a while ago: &lt;a href="http://www.atrevido.net/blog/PermaLink,guid,6136ce81-9fa1-4995-bb3e-15bc5f1f5899.aspx"&gt;What
is an IV?&lt;/a&gt;. That describes what an IV is, and why you need a unique one for each
message. Wikipedia also has good information on this. Now for the demo. I used the
code at the bottom, but removed the hashing and random IV from the code. So it's just
encrypting the with the same key and IV for each message -- very straightforward.
Here are the messages and their ciphertext:
&lt;/p&gt;
&lt;p&gt;
"Alice; Bob; Eve;: PerformAct1"&lt;br&gt;
"Alice; Bob; Eve;: PerformAct2"
&lt;/p&gt;
&lt;p&gt;
tZfHJSFTXYX8V38AqEfYVXU5Dl/meUVAond70yIKGHY= 
&lt;br&gt;
tZfHJSFTXYX8V38AqEfYVcf9a3U8vIEk1LuqGEyRZXM=
&lt;/p&gt;
&lt;p&gt;
Notice how the first block of ciphertext is the same? All messages starting with "Alice;
Bob; Eve;" will have that same first block. That means an attacker, after getting
this ciphertext once, now knows if any message is addressed the same way. Very, very
straightforward, basic attack. Now, maybe for a specific implementation you have in
mind, this is not an issue. But it's still improperly implemented cryptography.
&lt;/p&gt;
&lt;p&gt;
For the next attack, we're going to show that even with a random IV, you need to authenticate
your decrypted messages. This code generates a 64-bit integer and encrypts it with
AES and a random key/IV. Then, it starts changing bytes until the decrypt succeeds.
Presto: the attacker was able to present a completely different value, and the decryption
was successful.
&lt;/p&gt;
&lt;p&gt;
&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px"&gt;&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;public&lt;/span&gt; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;static&lt;/span&gt; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;void&lt;/span&gt; Main()
{&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; var buff &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;=&lt;/span&gt; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;new&lt;/span&gt; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;byte&lt;/span&gt;[8];&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;new&lt;/span&gt; Random().NextBytes(buff);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; var v &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;=&lt;/span&gt; BitConverter.ToUInt64(buff,
0);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px"&gt;"Value:
"&lt;/span&gt; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;+&lt;/span&gt; v.ToString());&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px"&gt;"Value
(bytes): "&lt;/span&gt; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;+&lt;/span&gt; BitConverter.ToString(BitConverter.GetBytes(v)));&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; var aes &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;=&lt;/span&gt; Aes.Create();&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; aes.GenerateIV();&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; aes.GenerateKey();&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; var encBytes &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;=&lt;/span&gt; aes.CreateEncryptor().TransformFinalBlock(BitConverter.GetBytes(v),
0, 8);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px"&gt;"Encrypted:
"&lt;/span&gt; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;+&lt;/span&gt; BitConverter.ToString(encBytes));&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; var dec &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;=&lt;/span&gt; aes.CreateDecryptor();&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px"&gt;"Decrypted:
"&lt;/span&gt; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;+&lt;/span&gt; BitConverter.ToUInt64(dec.TransformFinalBlock(encBytes,
0, encBytes.Length), 0));&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;for&lt;/span&gt; (&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;int&lt;/span&gt; i &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;=&lt;/span&gt; 0;
i &amp;lt; 8; i++) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;for&lt;/span&gt; (&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;int&lt;/span&gt; x &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;=&lt;/span&gt; 0;
x &amp;lt; 250; x++) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; encBytes[i]++;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;try&lt;/span&gt; {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
Console.WriteLine(&lt;span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px"&gt;"Attacked:
"&lt;/span&gt; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;+&lt;/span&gt; BitConverter.ToUInt64(dec.TransformFinalBlock(encBytes,
0, encBytes.Length), 0));&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;return&lt;/span&gt;;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;catch&lt;/span&gt; {
}&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;
}&lt;/span&gt;
&lt;/p&gt;
&lt;pre&gt;&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px"&gt;&lt;font size=2 face=Verdana&gt;Here's
an example run:&lt;/font&gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px"&gt;Value:
5686260040031435365&lt;br&gt;
Value (bytes): 65-7A-92-1A-61-A7-E9-4E&lt;br&gt;
Encrypted: F4-62-AC-02-2D-7D-43-6A-4D-97-68-4D-95-9F-8A-DF&lt;br&gt;
Decrypted: 5686260040031435365&lt;br&gt;
Attacked: 1603329786558177755&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px"&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
Since there's no authentication of the decrypted data, an attacker can just play with
the ciphertext until it generates an acceptable value. Perhaps you have other mitigations
in your implementation/application for this, but why rely on that?
&lt;/p&gt;
&lt;p&gt;
Here's some demo code (I haven't tested it much, so it might have some major issues
-- but not by design AFAIK). Note this just shows performing an encryption operation,
including the IV in the message, and verifying the decrypted bytes. Other things like
replay attacks are not considered. If you're trying to learn how to use crypto so
you can drop it into an application, STOP, then&amp;nbsp;go read enough to understand
what you're doing and the implications for your particular application.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.atrevido.net/blog/content/binary/aesdemo.cs.txt"&gt;aesdemo.cs.txt
(4.38 KB)&lt;/a&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=9bb60288-03e1-4610-bf72-8326c62f1358" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,9bb60288-03e1-4610-bf72-8326c62f1358.aspx</comments>
      <category>Code</category>
      <category>Security</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=89c360be-0db4-47db-9c63-708d4baf33dd</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,89c360be-0db4-47db-9c63-708d4baf33dd.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,89c360be-0db4-47db-9c63-708d4baf33dd.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=89c360be-0db4-47db-9c63-708d4baf33dd</wfw:commentRss>
      <slash:comments>4</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">Silverlight 2 doesn't support faults, so
you can't catch them. That sucks, since WCF's FaultException&lt;T&gt; is pretty useful.
In Beta 1 I did a vile hack to get some data. After reading online, Id determined
that Silverlight should be able to intercept the fault message and interpret it. Unfortunately,
some of the handy classes to insert yourself into the stack aren't in Silverlight's
WCF. Fortunately, there is a sample that does most of it:<br /><br /><a href="http://code.msdn.microsoft.com/silverlightws/Release/ProjectReleases.aspx?ReleaseId=1660">http://code.msdn.microsoft.com/silverlightws/Release/ProjectReleases.aspx?ReleaseId=1660</a><br /><br />
In the "Message Inspectors" sample. This sample has code to let you inspect messages,
and it also has a sample where they throw "raw" faults (i.e., "wrapped exceptions",
aka "ExceptionDetail"). Why they stopped there is beyond me. With a bit of hacking
(I must say, this SOAP stuff looks very complex), I got it to recognize any fault
type, and throw a FaultException&lt;T&gt;. Well, not a FaultException&lt;T&gt;, 'cause
there is a neutered FaultException class already in System.ServiceModel from Silverlight.
So I named mine "SLFaultException" (SL for Simple Lame).<br /><br />
To get the fault thrown, you need to hookup the SilverlightFaultMessageInspector.
From the demo code:<br /><pre><span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"> EndpointAddress
address <span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;">=</span><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">new</span> EndpointAddress(<span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"http://127.0.0.1:52620/Service.svc"</span>);
BasicHttpMessageInspectorBinding binding <span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;">=</span><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">new</span> BasicHttpMessageInspectorBinding(<span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">new</span> SilverlightFaultMessageInspector());
ServiceClient proxy <span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;">=</span><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">new</span> ServiceClient(binding,
address); proxy.DoWorkCompleted += <span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">new</span> System.EventHandler&lt;System.ComponentModel.AsyncCompletedEventArgs&gt;(proxy_DoWorkCompleted);
proxy.DoWorkAsync(); </span></pre>You also need to register the assembly's types so
that the fault throwing code can find the fault detail to deserialize. There's no
way in Silverlight to get all the loaded assemblies (as far as I know). So we do this:<br />
   <font face="Courier New">System.ServiceModel.SilverlightFaultMessageInspector.RegisterCurrentAssembly();</font><br /><br />
This registers the calling assembly's types to be searched when a fault detail is
received.<br /><br />
Now the only thing that needs to be done is fixup the HTTP 500 status code to a 200.
The MS sample has a behaviour to do this. But that's annoying, having another DLL
to deploy and deal with. So I do this in the Global.asax:<br /><pre><span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">protected</span><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">void</span> Application_EndRequest(<span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">object</span> sender,
EventArgs e) {<br /><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">if</span> (HttpContext.Current.Request.PhysicalPath.EndsWith(<span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">".svc"</span>,
StringComparison.OrdinalIgnoreCase) &amp;&amp;<br />
HttpContext.Current.Response.StatusCode == 500 &amp;&amp;<br />
!HttpContext.Current.Request.Browser.Crawler &amp;&amp;<br />
HttpContext.Current.Request.Browser.EcmaScriptVersion.Major &gt; 0) {<br /><span style="color: Green; background-color: transparent; font-family: Courier New; font-size: 11px;">//
Set 200 if its a faulted service request</span><br />
HttpContext.Current.Response.StatusCode <span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;">=</span> 200;<br />
}<br />
}</span></pre>From there, go ahead and catch SLFaultException&lt;T&gt; just like you
would a FaultException&lt;T&gt;.<br /><br />
Overall, this proved far easier than I expected. I'm at a complete loss why they didn't
ship faults in SL2. I mean, if I hacked _something_ out in an hour or two, I'm sure
someone who had some clue of what they're doing could have done so easier. Heck, they
even have the real WCF source -- I was stuck using Reflector for parts :P.<br /><br /><p></p><a href="http://www.atrevido.net/blog/content/binary/SilverlightFaultsBinary.zip">SilverlightFaultsBinary.zip
(13.81 KB)</a><br /><br /><a href="http://www.atrevido.net/blog/content/binary/SilverlightFaultsSource.zip">SilverlightFaultsSource.zip
(61.55 KB)</a><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=89c360be-0db4-47db-9c63-708d4baf33dd" /></body>
      <title>Full Typed Faults in Silverlight 2 (FaultException&lt;T&gt;)</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,89c360be-0db4-47db-9c63-708d4baf33dd.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/12/11/Full+Typed+Faults+In+Silverlight+2+FaultException.aspx</link>
      <pubDate>Thu, 11 Dec 2008 02:04:45 GMT</pubDate>
      <description>Silverlight 2 doesn't support faults, so you can't catch them. That sucks, since WCF's FaultException&amp;lt;T&amp;gt; is pretty useful. In Beta 1 I did a vile hack to get some data. After reading online, Id determined that Silverlight should be able to intercept the fault message and interpret it. Unfortunately, some of the handy classes to insert yourself into the stack aren't in Silverlight's WCF. Fortunately, there is a sample that does most of it:&lt;br&gt;
&lt;br&gt;
&lt;a href="http://code.msdn.microsoft.com/silverlightws/Release/ProjectReleases.aspx?ReleaseId=1660"&gt;http://code.msdn.microsoft.com/silverlightws/Release/ProjectReleases.aspx?ReleaseId=1660&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
In the "Message Inspectors" sample. This sample has code to let you inspect messages,
and it also has a sample where they throw "raw" faults (i.e., "wrapped exceptions",
aka "ExceptionDetail"). Why they stopped there is beyond me. With a bit of hacking
(I must say, this SOAP stuff looks very complex), I got it to recognize any fault
type, and throw a FaultException&amp;lt;T&amp;gt;. Well, not a FaultException&amp;lt;T&amp;gt;, 'cause
there is a neutered FaultException class already in System.ServiceModel from Silverlight.
So I named mine "SLFaultException" (SL for Simple Lame).&lt;br&gt;
&lt;br&gt;
To get the fault thrown, you need to hookup the SilverlightFaultMessageInspector.
From the demo code:&lt;br&gt;
&lt;pre&gt;&lt;span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt; EndpointAddress
address &lt;span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;=&lt;/span&gt; &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;new&lt;/span&gt; EndpointAddress(&lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"http://127.0.0.1:52620/Service.svc"&lt;/span&gt;);
BasicHttpMessageInspectorBinding binding &lt;span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;=&lt;/span&gt; &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;new&lt;/span&gt; BasicHttpMessageInspectorBinding(&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;new&lt;/span&gt; SilverlightFaultMessageInspector());
ServiceClient proxy &lt;span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;=&lt;/span&gt; &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;new&lt;/span&gt; ServiceClient(binding,
address); proxy.DoWorkCompleted += &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;new&lt;/span&gt; System.EventHandler&amp;lt;System.ComponentModel.AsyncCompletedEventArgs&amp;gt;(proxy_DoWorkCompleted);
proxy.DoWorkAsync(); &lt;/span&gt;&lt;/pre&gt;You also need to register the assembly's types so
that the fault throwing code can find the fault detail to deserialize. There's no
way in Silverlight to get all the loaded assemblies (as far as I know). So we do this:&lt;br&gt;
&amp;nbsp;&amp;nbsp; &lt;font face="Courier New"&gt;System.ServiceModel.SilverlightFaultMessageInspector.RegisterCurrentAssembly();&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
This registers the calling assembly's types to be searched when a fault detail is
received.&lt;br&gt;
&lt;br&gt;
Now the only thing that needs to be done is fixup the HTTP 500 status code to a 200.
The MS sample has a behaviour to do this. But that's annoying, having another DLL
to deploy and deal with. So I do this in the Global.asax:&lt;br&gt;
&lt;pre&gt;&lt;span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt; &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;protected&lt;/span&gt; &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;void&lt;/span&gt; Application_EndRequest(&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;object&lt;/span&gt; sender,
EventArgs e) {&lt;br&gt;
&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;if&lt;/span&gt; (HttpContext.Current.Request.PhysicalPath.EndsWith(&lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;".svc"&lt;/span&gt;,
StringComparison.OrdinalIgnoreCase) &amp;amp;&amp;amp;&lt;br&gt;
HttpContext.Current.Response.StatusCode == 500 &amp;amp;&amp;amp;&lt;br&gt;
!HttpContext.Current.Request.Browser.Crawler &amp;amp;&amp;amp;&lt;br&gt;
HttpContext.Current.Request.Browser.EcmaScriptVersion.Major &amp;gt; 0) {&lt;br&gt;
&lt;span style="color: Green; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;//
Set 200 if its a faulted service request&lt;/span&gt;
&lt;br&gt;
HttpContext.Current.Response.StatusCode &lt;span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;=&lt;/span&gt; 200;&lt;br&gt;
}&lt;br&gt;
}&lt;/span&gt;&lt;/pre&gt;From there, go ahead and catch SLFaultException&amp;lt;T&amp;gt; just like you
would a FaultException&amp;lt;T&amp;gt;.&lt;br&gt;
&lt;br&gt;
Overall, this proved far easier than I expected. I'm at a complete loss why they didn't
ship faults in SL2. I mean, if I hacked _something_ out in an hour or two, I'm sure
someone who had some clue of what they're doing could have done so easier. Heck, they
even have the real WCF source -- I was stuck using Reflector for parts :P.&lt;br&gt;
&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;a href="http://www.atrevido.net/blog/content/binary/SilverlightFaultsBinary.zip"&gt;SilverlightFaultsBinary.zip
(13.81 KB)&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
&lt;a href="http://www.atrevido.net/blog/content/binary/SilverlightFaultsSource.zip"&gt;SilverlightFaultsSource.zip
(61.55 KB)&lt;/a&gt;&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=89c360be-0db4-47db-9c63-708d4baf33dd" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,89c360be-0db4-47db-9c63-708d4baf33dd.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=58bb956f-89a8-4938-a595-5e01bf862a03</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,58bb956f-89a8-4938-a595-5e01bf862a03.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,58bb956f-89a8-4938-a595-5e01bf862a03.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=58bb956f-89a8-4938-a595-5e01bf862a03</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <br />
I have a scenario where my web service app exposes several interfaces, and I want
to use all of them from the Silverlight UI. The code generated by SvcUtil isn't completely
compatible with Silverlight's WCF, meaning you need to do a lot of fixup to make it
work in SL. Looking in the forums, I see mentions of "slsvcutil" and "slwsdl", but
I've been unable to actually find these programs. The only thing that Silverlight
has is "Microsoft.Silverlight.ServiceReference.dll", in the "Program Files\Microsoft
SDKs\Silverlight\v2.0\Tools\ServiceReference" folder.<br /><br />
I opened that DLL up in ildasm, and it appears to just be some classes that work on
a ServiceContractGenerator. Digging in deeper, yep, they just go through the generated
CodeDOM and fixup stuff that isn't compatible. For instance, IExtensibleDataObject
isn't supported. SL WCF also doesn't handle having Sync and Async methods (i.e, SomeOp
and Begin/EndSomeOp) since they both have the same action. (You'll get an "An item
with the same key has already been added" error.)<br /><br />
My main problems with the cutesy "Add Service Reference" UI are:<br />
 - I can't figure out how to tell it to use mutliple WSDL files and share the
data types.<br />
 - It generates a ton of files and VS gets all obsessive over them for some reason.<br />
 - It generates a lot of extra code (like the useless ClientBase stuff, and the
idiotic/useless "event based async pattern" code). Extra code just clutters up Intellisense,
so why bother?<br /><br />
[Add Service Reference is great for demos and perhaps simple one-offs... I can't imagine
dealing with it for anything slightly complicated.]<br /><br />
So, I took the MSDN code sample for the ServiceContractGenerator, and hacked it up
to do what I needed. Then I added the 2 lines to pass it through the Silverlight ServiceReference
fixup thing, and presto - things look great. Usage is simple:<br /><br />
Usage: slsvchack &lt;clr namespace&gt; &lt;outputfile&gt; &lt;wsdl1&gt; .. &lt;wsdlN&gt;<br /><br />
The options are hard-coded to what I use and makes the most sense for Silverlight
apps (in my opinion). I want to do a full fledged "SLSvcUtil.exe", but I think the
right approach there is to dissassemble SvcUtil and patch in the Silverlight.ServiceReference
stuff. But, I don't have the time right now.<br /><br />
Code: <a href="http://www.atrevido.net/blog/content/binary/slsvchack.cs.txt">slsvchack.cs.txt
(2.95 KB)</a> [It's in C# 'cause the MSDN sample was, and my edits were minor. ]<br />
Binary: <a href="http://www.atrevido.net/blog/content/binary/slsvchack.exe">slsvchack.exe
(8.5 KB) </a>[I'm too lazy to link in the Microsoft.Silverlight.ServiceReference.dll,
so you'll need the Silverlight SDK installed.]<br /><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=58bb956f-89a8-4938-a595-5e01bf862a03" /></body>
      <title>Command line WCF Proxy Generation for Silverlight 2 RTM</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,58bb956f-89a8-4938-a595-5e01bf862a03.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/12/02/Command+Line+WCF+Proxy+Generation+For+Silverlight+2+RTM.aspx</link>
      <pubDate>Tue, 02 Dec 2008 19:56:09 GMT</pubDate>
      <description>&lt;br&gt;
I have a scenario where my web service app exposes several interfaces, and I want
to use all of them from the Silverlight UI. The code generated by SvcUtil isn't completely
compatible with Silverlight's WCF, meaning you need to do a lot of fixup to make it
work in SL. Looking in the forums, I see mentions of "slsvcutil" and "slwsdl", but
I've been unable to actually find these programs. The only thing that Silverlight
has is "Microsoft.Silverlight.ServiceReference.dll", in the "Program Files\Microsoft
SDKs\Silverlight\v2.0\Tools\ServiceReference" folder.&lt;br&gt;
&lt;br&gt;
I opened that DLL up in ildasm, and it appears to just be some classes that work on
a ServiceContractGenerator. Digging in deeper, yep, they just go through the generated
CodeDOM and fixup stuff that isn't compatible. For instance, IExtensibleDataObject
isn't supported. SL WCF also doesn't handle having Sync and Async methods (i.e, SomeOp
and Begin/EndSomeOp) since they both have the same action. (You'll get an "An item
with the same key has already been added" error.)&lt;br&gt;
&lt;br&gt;
My main problems with the cutesy "Add Service Reference" UI are:&lt;br&gt;
&amp;nbsp;- I can't figure out how to tell it to use mutliple WSDL files and share the
data types.&lt;br&gt;
&amp;nbsp;- It generates a ton of files and VS gets all obsessive over them for some reason.&lt;br&gt;
&amp;nbsp;- It generates a lot of extra code (like the useless ClientBase stuff, and the
idiotic/useless "event based async pattern" code). Extra code just clutters up Intellisense,
so why bother?&lt;br&gt;
&lt;br&gt;
[Add Service Reference is great for demos and perhaps simple one-offs... I can't imagine
dealing with it for anything slightly complicated.]&lt;br&gt;
&lt;br&gt;
So, I took the MSDN code sample for the ServiceContractGenerator, and hacked it up
to do what I needed. Then I added the 2 lines to pass it through the Silverlight ServiceReference
fixup thing, and presto - things look great. Usage is simple:&lt;br&gt;
&lt;br&gt;
Usage: slsvchack &amp;lt;clr namespace&amp;gt; &amp;lt;outputfile&amp;gt; &amp;lt;wsdl1&amp;gt; .. &amp;lt;wsdlN&amp;gt;&lt;br&gt;
&lt;br&gt;
The options are hard-coded to what I use and makes the most sense for Silverlight
apps (in my opinion). I want to do a full fledged "SLSvcUtil.exe", but I think the
right approach there is to dissassemble SvcUtil and patch in the Silverlight.ServiceReference
stuff. But, I don't have the time right now.&lt;br&gt;
&lt;br&gt;
Code: &lt;a href="http://www.atrevido.net/blog/content/binary/slsvchack.cs.txt"&gt;slsvchack.cs.txt
(2.95 KB)&lt;/a&gt; [It's in C# 'cause the MSDN sample was, and my edits were minor. ]&lt;br&gt;
Binary: &lt;a href="http://www.atrevido.net/blog/content/binary/slsvchack.exe"&gt;slsvchack.exe
(8.5 KB) &lt;/a&gt;[I'm too lazy to link in the Microsoft.Silverlight.ServiceReference.dll,
so you'll need the Silverlight SDK installed.]&lt;br&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=58bb956f-89a8-4938-a595-5e01bf862a03" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,58bb956f-89a8-4938-a595-5e01bf862a03.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=80ef8587-712c-4bc9-a5af-f77ae3df173c</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,80ef8587-712c-4bc9-a5af-f77ae3df173c.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,80ef8587-712c-4bc9-a5af-f77ae3df173c.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=80ef8587-712c-4bc9-a5af-f77ae3df173c</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">Recently I mentioned how a lot of companies
use obfuscation unnecessarily, and it ends up hurting legitimate customers while doing
nothing to prevent "crackers". Specifically, I mentioned VistaDB, as the obfuscation
tool was injecting invalid IL, causing Mono to reject the assembly. 
<br /><br />
Jason Short replied to me and I detailed the exact problems with the obfuscator (along
with a few F# scripts to unobfuscate and remove the bad IL). They then released a
new build with the obfuscation removed -- which Mono now happily loads. 
<br /><br />
I just wanted to give kudos to <a href="http://vistadb.net/">VistaDB</a> for doing
this. Not many companies are smart enough to realise that their "protection" tools
are useless and do a 180 on such a stance.<br /><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=80ef8587-712c-4bc9-a5af-f77ae3df173c" /></body>
      <title>Follow up on Obfuscation and VistaDB</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,80ef8587-712c-4bc9-a5af-f77ae3df173c.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/11/29/Follow+Up+On+Obfuscation+And+VistaDB.aspx</link>
      <pubDate>Sat, 29 Nov 2008 19:12:05 GMT</pubDate>
      <description>Recently I mentioned how a lot of companies use obfuscation unnecessarily, and it ends up hurting legitimate customers while doing nothing to prevent "crackers". Specifically, I mentioned VistaDB, as the obfuscation tool was injecting invalid IL, causing Mono to reject the assembly. &lt;br&gt;
&lt;br&gt;
Jason Short replied to me and I detailed the exact problems with the obfuscator (along
with a few F# scripts to unobfuscate and remove the bad IL). They then released a
new build with the obfuscation removed -- which Mono now happily loads. 
&lt;br&gt;
&lt;br&gt;
I just wanted to give kudos to &lt;a href="http://vistadb.net/"&gt;VistaDB&lt;/a&gt; for doing
this. Not many companies are smart enough to realise that their "protection" tools
are useless and do a 180 on such a stance.&lt;br&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=80ef8587-712c-4bc9-a5af-f77ae3df173c" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,80ef8587-712c-4bc9-a5af-f77ae3df173c.aspx</comments>
      <category>Code</category>
      <category>Security</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=9db695f2-3740-4bf5-b16a-adeb4020b0fc</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,9db695f2-3740-4bf5-b16a-adeb4020b0fc.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,9db695f2-3740-4bf5-b16a-adeb4020b0fc.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=9db695f2-3740-4bf5-b16a-adeb4020b0fc</wfw:commentRss>
      <slash:comments>4</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">I've been meaning to write about this for
a while. It's a very simple topic, but developers get all emotional and stop being
rational as soon as the magic "code protection" and "piracy" words get invoked. I'd
like to say I'm not promoting copyright infringement nor saying developers don't deserve
to be compensated for their work. Now that that's out of the way...<br /><br />
The two things most developers want to stop are unauthorized installing (license enforcement)
and "code protection". Code protection is a very weak concept, mainly revolving around
thinking people are gonna steal your precious algorithms. Protection is easy to deal
with, so I'm going to cover that now.<br /><br />
Before VMs like .NET were popular, most of the code protection I've seen revolved
around the code that implements the license enforcement. Developers would write all
sorts of nasty-clever-clever code to make things hard for the crackers. You see this
sometimes when you run an application and it complains about a debugger being installed
or running. With Java and .NET, disassembly got easier. This made it extra easy to
patch any license code, since the dissassembled code was in a high level language
like IL. The response, and our first enemy of the day, was obfuscation.<br /><br />
Obfuscation takes your assembly and screws up all the metadata. On top of that, it
might go and rewrite sections of your code to obfuscate the flow of the program, or
perhaps indirectly load strings. The downside of course is that debugging gets really
hard cause all your method names are now unreadable, reflection is broken, etc. Depending
on the techniques an obfuscator uses, you can run into some other troubles. For instance,
whatever obfuscator VistaDB uses is really broken, as it generates bad IL that just
happens to work on MS CLR, but crashes (rightly so) on Mono. Not to mention that certain
IL tricks are not verifiable, hence you can't use the code in lower-trust scenarios.<br /><br />
But what does obfuscation accomplish? Crackers ALWAYS win. Even the "most difficult"
license system with hardware dongles and activation get cracked. The response I usually
hear is "well it raises the bar". So. What. "Raising the bar" is totally pointless.
Bruce Schneier talked about this. 
<br /><br />
For physical security, raising the bar is good in general. For example, if you buy
a safe, it'll prevent a lot of thieves from getting to the valuables. Sure, there
are higher level thieves, but you've weeded out a lot of the population around you,
and the benefit is very real. Now some punk kids can't just go in and vandalize and
"casually steal" your valuables.<br /><br />
But for computerized tech, the "bar" is the highest level attacker. If your valuable
is "cracking my serial verification code", as soon as the "high level theif" cracks
it, he can go write a simple program anyone can download. So the REAL bar is "user
googles for a crack". That's what needs to sink past all the emotional nonsense developers
go through when protecting their code. No matter what kind of complex protection schemes
you put in, then obfuscate it on top of that, if the product has value, _someone_
will crack it, and all your users can just download the crack. 
<br /><br />
This isn't a maybe, this isn't a "possibly", this isn't theoretic, this is the exact
reality. There is *nothing* you as a developer can do to prevent this (apart from
make your product suck so much no one cares). [If there is, I'd love to hear it.]<br /><br />
So, obfuscation has zero value in preventing cracks, serials from getting out. And
it has downsides. Just read the VistaDB blogs/forums to see real world problems only
because they use an obfuscator.<br /><br />
What about "protecting special algorithms"? From who? If your competitors are good,
they'll figure things out regardless. If they suck, they won't be able to do much
with it anyways. I think the biggest threat is some overseas group disassembling your
code, slapping their logos on it, and reselling it. That's a clear and obvious loss
if they are making sales. But, obfuscation isn't really going to stop it, just raise
the bar a tiny bit. In this case, since you're dealing with a limited number of "pirate
companies" that exist for profit, perhaps obfuscating has a bit of value. But think:
If someone can not know your source code, not be able to provide support, etc. etc.,
but can still outsell you and your marketing, perhaps you have business issues.<br /><br />
The one other place I hear people using obfuscation is to protect an app from "casual
hacking". WTF does that mean? You mean you're afraid your sales clerk might decompile
the PoS application, but give up quickly? You think it means you can safely store
passwords in the binary? I'm not sure what such developers are thinking, but I'm guessing
they did a poor security analysis of the situation.<br /><br />
As a side note, this is not particular to VM platforms like Java and .NET. Check out <a href="http://www.hex-rays.com/">Hex
Rays</a>. They do a fine job *decompiling* optimized native code. I've seen it in
action; it makes it easy to take any native app, decompile it, figure it out, then
work with the assembly code. So these .NET devs thinking they are so leet cause Reflector
messes up and hence no one can figure it out... sigh.<br /><br />
Finally, a nice real-live demo. Look at Spore and other games using heavy DRM and
protection mechanisms. Obviously Eletronic Arts has an unlimited budget for getting
the "best" type of protection. Yet the protection proved utterly useless against piracy.
Just goto ThePirateBay.org and search. Yet they certainly introduced more bugs and
user hate. (Of course, the REAL motive behind such DRM is killing the used games market.
For this, all they need is stuff that honest users won't break.)<br /><br />
P.S. The reason I finally wrote all this is because VistaDB just took the silliness
to the next level. I got their 3.4 Trial, but it crashes on Mono because the obfuscator
emits totally invalid IL code. Their official response was that Trials arent tested
on Mono. I bought the product and the "stable" builds still have the same busted IL
code. Awesome protection; stopping paying users from using the software rocks!<br /><br />
I suppose I could understand IF they had some awesome trade secrets. BUT, they provide
a source code license. So an evil VistaDB competitor just buys a source code license
to get all the details. How is obfuscation helping ANYONE here? (Note the runtime
has no licensing; only the developer install.)<br /><br /><p></p><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=9db695f2-3740-4bf5-b16a-adeb4020b0fc" /></body>
      <title>Software protection</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,9db695f2-3740-4bf5-b16a-adeb4020b0fc.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/11/08/Software+Protection.aspx</link>
      <pubDate>Sat, 08 Nov 2008 00:06:00 GMT</pubDate>
      <description>I've been meaning to write about this for a while. It's a very simple topic, but developers get all emotional and stop being rational as soon as the magic "code protection" and "piracy" words get invoked. I'd like to say I'm not promoting copyright infringement nor saying developers don't deserve to be compensated for their work. Now that that's out of the way...&lt;br&gt;
&lt;br&gt;
The two things most developers want to stop are unauthorized installing (license enforcement)
and "code protection". Code protection is a very weak concept, mainly revolving around
thinking people are gonna steal your precious algorithms. Protection is easy to deal
with, so I'm going to cover that now.&lt;br&gt;
&lt;br&gt;
Before VMs like .NET were popular, most of the code protection I've seen revolved
around the code that implements the license enforcement. Developers would write all
sorts of nasty-clever-clever code to make things hard for the crackers. You see this
sometimes when you run an application and it complains about a debugger being installed
or running. With Java and .NET, disassembly got easier. This made it extra easy to
patch any license code, since the dissassembled code was in a high level language
like IL. The response, and our first enemy of the day, was obfuscation.&lt;br&gt;
&lt;br&gt;
Obfuscation takes your assembly and screws up all the metadata. On top of that, it
might go and rewrite sections of your code to obfuscate the flow of the program, or
perhaps indirectly load strings. The downside of course is that debugging gets really
hard cause all your method names are now unreadable, reflection is broken, etc. Depending
on the techniques an obfuscator uses, you can run into some other troubles. For instance,
whatever obfuscator VistaDB uses is really broken, as it generates bad IL that just
happens to work on MS CLR, but crashes (rightly so) on Mono. Not to mention that certain
IL tricks are not verifiable, hence you can't use the code in lower-trust scenarios.&lt;br&gt;
&lt;br&gt;
But what does obfuscation accomplish? Crackers ALWAYS win. Even the "most difficult"
license system with hardware dongles and activation get cracked. The response I usually
hear is "well it raises the bar". So. What. "Raising the bar" is totally pointless.
Bruce Schneier talked about this. 
&lt;br&gt;
&lt;br&gt;
For physical security, raising the bar is good in general. For example, if you buy
a safe, it'll prevent a lot of thieves from getting to the valuables. Sure, there
are higher level thieves, but you've weeded out a lot of the population around you,
and the benefit is very real. Now some punk kids can't just go in and vandalize and
"casually steal" your valuables.&lt;br&gt;
&lt;br&gt;
But for computerized tech, the "bar" is the highest level attacker. If your valuable
is "cracking my serial verification code", as soon as the "high level theif" cracks
it, he can go write a simple program anyone can download. So the REAL bar is "user
googles for a crack". That's what needs to sink past all the emotional nonsense developers
go through when protecting their code. No matter what kind of complex protection schemes
you put in, then obfuscate it on top of that, if the product has value, _someone_
will crack it, and all your users can just download the crack. 
&lt;br&gt;
&lt;br&gt;
This isn't a maybe, this isn't a "possibly", this isn't theoretic, this is the exact
reality. There is *nothing* you as a developer can do to prevent this (apart from
make your product suck so much no one cares). [If there is, I'd love to hear it.]&lt;br&gt;
&lt;br&gt;
So, obfuscation has zero value in preventing cracks, serials from getting out. And
it has downsides. Just read the VistaDB blogs/forums to see real world problems only
because they use an obfuscator.&lt;br&gt;
&lt;br&gt;
What about "protecting special algorithms"? From who? If your competitors are good,
they'll figure things out regardless. If they suck, they won't be able to do much
with it anyways. I think the biggest threat is some overseas group disassembling your
code, slapping their logos on it, and reselling it. That's a clear and obvious loss
if they are making sales. But, obfuscation isn't really going to stop it, just raise
the bar a tiny bit. In this case, since you're dealing with a limited number of "pirate
companies" that exist for profit, perhaps obfuscating has a bit of value. But think:
If someone can not know your source code, not be able to provide support, etc. etc.,
but can still outsell you and your marketing, perhaps you have business issues.&lt;br&gt;
&lt;br&gt;
The one other place I hear people using obfuscation is to protect an app from "casual
hacking". WTF does that mean? You mean you're afraid your sales clerk might decompile
the PoS application, but give up quickly? You think it means you can safely store
passwords in the binary? I'm not sure what such developers are thinking, but I'm guessing
they did a poor security analysis of the situation.&lt;br&gt;
&lt;br&gt;
As a side note, this is not particular to VM platforms like Java and .NET. Check out &lt;a href="http://www.hex-rays.com/"&gt;Hex
Rays&lt;/a&gt;. They do a fine job *decompiling* optimized native code. I've seen it in
action; it makes it easy to take any native app, decompile it, figure it out, then
work with the assembly code. So these .NET devs thinking they are so leet cause Reflector
messes up and hence no one can figure it out... sigh.&lt;br&gt;
&lt;br&gt;
Finally, a nice real-live demo. Look at Spore and other games using heavy DRM and
protection mechanisms. Obviously Eletronic Arts has an unlimited budget for getting
the "best" type of protection. Yet the protection proved utterly useless against piracy.
Just goto ThePirateBay.org and search. Yet they certainly introduced more bugs and
user hate. (Of course, the REAL motive behind such DRM is killing the used games market.
For this, all they need is stuff that honest users won't break.)&lt;br&gt;
&lt;br&gt;
P.S. The reason I finally wrote all this is because VistaDB just took the silliness
to the next level. I got their 3.4 Trial, but it crashes on Mono because the obfuscator
emits totally invalid IL code. Their official response was that Trials arent tested
on Mono. I bought the product and the "stable" builds still have the same busted IL
code. Awesome protection; stopping paying users from using the software rocks!&lt;br&gt;
&lt;br&gt;
I suppose I could understand IF they had some awesome trade secrets. BUT, they provide
a source code license. So an evil VistaDB competitor just buys a source code license
to get all the details. How is obfuscation helping ANYONE here? (Note the runtime
has no licensing; only the developer install.)&lt;br&gt;
&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=9db695f2-3740-4bf5-b16a-adeb4020b0fc" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,9db695f2-3740-4bf5-b16a-adeb4020b0fc.aspx</comments>
      <category>Code</category>
      <category>Security</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=0dfb63a3-b66c-4317-9e6c-affe59c86041</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,0dfb63a3-b66c-4317-9e6c-affe59c86041.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,0dfb63a3-b66c-4317-9e6c-affe59c86041.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=0dfb63a3-b66c-4317-9e6c-affe59c86041</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">Several times I've had to explain a few
basic F# things to new users. I ran into some of these too when I first looked at
F#. If you've been looking at F#, but some things still don't click, I hope this will
help break the chains of C/imperative languages. I'm assuming you know a bit about
F#, perhaps from the <a href="http://research.microsoft.com/fsharp/manual/quicktour.aspx">Quick
Tour</a> or the F# Tutorial file that comes with the Visual Studio integration.<br /><br /><b>Functions always take and receive exactly one argument.</b><br />
Despite anything you see, in F#, there's only one argument, and only one return value.
Let's look at how this plays out (I suggest firing up F# interactive and playing around):<br /><br /><font face="Courier New">&gt; let inc x = x + 1;;<br />
val inc : int -&gt; int<br /><br />
&gt; let add x y = x + y;;<br />
val add : int -&gt; int -&gt; int<br /></font><br />
[I like to read -&gt; as "to", because it's short and sweet.] So, for the case of
"inc x", we see the signature is quite simple and expected "int to int". But for add?
We see "int to int to int". What this actually means is "a function that takes an
integer, and returns a function that takes an integer and returns an integer". 
<br /><br />
The same signature in C# would look like this: <font face="Courier New">Func&lt;int,
&lt;Func&lt;int,int&gt;&gt;&gt;</font> or "<font face="Courier New">Func&lt;int,int&gt;
Add(int x)</font>". [Some day, think how odd it is to have two ways of representing
the function.] So when we call the F# function, we're really passing in the first
argument, getting a new function, then applying the second argument. Something like
this:<br /><br />
1. add x y<br />
2. (add x) y<br />
3. closure1 y<br />
4. final-result<br /><br />
"closure1" is what we get from the "partial" application of add. I'll touch on this
in a minute.<br /><br />
So how do we _really_ pass in two arguments at once? We put two arguments into one
value, a tuple. We write it like this:<br /><font face="Courier New"><br />
&gt; let add (x, y) = x + y;;<br />
val add : int * int -&gt; int<br /></font><br />
Notice the new type signature: "int by int to int" or "int int tuple to int". In C#,
this would be:<br /><br />
int add(Tuple&lt;int,int&gt; arguments) { return Tuple.A + Tuple.B; }<br /><br />
But F# nicely provides support for tuples [via pattern matching], so we can write
them much more naturally. This syntax also works on the way out:<br /><font face="Courier New"><br />
&gt; let pow23 x = x*x, x*x*x;;<br />
val pow23 : int -&gt; int * int<br />
// "int to int int tuple"<br /><br />
&gt; let square, cube = pow23 7;;<br />
val square : int<br />
val cube : int<br /><br />
&gt; square, cube;;<br />
val it : int * int = (49, 343)</font><br /><br /><b>There's never no value</b><br />
Another common typo/misunderstanding is when creating a function with no arguments:<br /><br /><font face="Courier New">&gt; let sayHi = printfn "Hi";;<br />
val sayHi : unit<br /><br />
Hi<br />
&gt; sayHi;;<br />
val it : unit = ()<br /></font><br />
Oh, what happened here? Remember how _everything_ takes and returns exactly one value?
The same is true of functions that "don't return a value", such as printf. Instead
of "not returning a value" like C's <font face="Courier New">void</font>, functions
return a special type called <font face="Courier New">unit</font> with one value, <font face="Courier New">()</font>. 
<br /><br />
Armed with this, let's see what the <font face="Courier New">sayHi </font>definition
actually says. It says "let a value called sayHi equal to the result of printfn".
Well, since the result of <font face="Courier New">printfn </font>is <font face="Courier New">unit</font>, <font face="Courier New">sayHi </font>becomes <font face="Courier New">unit</font>.
The execution happens immediately, and subsequent uses of <font face="Courier New">sayHi </font>just
get the value, <font face="Courier New">unit</font>. 
<br /><br />
To actually do what we want, we need to take an argument. Then F# knows we're a function
value:<br /><br /><font face="Courier New">&gt; let sayHi() = printfn "Hi";;<br />
val sayHi : unit -&gt; unit<br /><br />
&gt; sayHi;;<br />
val it : (unit -&gt; unit) = &lt;fun:clo@0&gt;<br /><br />
&gt; sayHi();;<br />
Hi<br />
val it : unit = ()</font><br /><br />
By explicitly taking a <font face="Courier New">unit </font>parameter, <font face="Courier New">sayHi</font> becomes
a function (type unit to unit). Notice that if we just write "sayHi", we're just going
to get the _value_ of it (a function), not apply (execute) the function.<br /><br /><b>Partial application</b><br />
OK, so a side effect of this system of "take on param and return a function that takes
the next", is that we can compose with just parts of a function. For instance, to
write an increment function, we can do this:<br /><br /><font face="Courier New">&gt; let add x y = x + y;;<br />
val add : int -&gt; int -&gt; int<br /><br />
&gt; let inc x = add x 1;;<br />
val inc : int -&gt; int</font><br /><br />
So far, nothing interesting. However, we can also write this more effectively:<br /><font face="Courier New"><br />
&gt; let inc = add 1;;<br />
val inc : (int -&gt; int)</font><br /><br />
Aha! What's happening here is what happens "secretly" each time we call add with 2
parameters. We're just using the intermediate result, the closure of "add 1", and
assigning that function value to inc. In C#, it'd be something like this:<br /><pre><span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">public</span><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">static</span> Func&lt;<span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">int</span>, <span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">int</span>&gt;
Add(<span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">int</span> x)
{ <span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">return</span> y
=&gt; x <span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;">+</span> y;
} <span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">public</span><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">static</span> Func&lt;<span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">int</span>, <span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">int</span>&gt;
Inc <span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;">=</span> Add(1); <span style="color: Green; background-color: transparent; font-family: Courier New; font-size: 11px;">//
and "full application" of add looks like this: Add(1)(2)</span></span></pre>[<i>BTW</i>,
this isn't really currying in F#. Currying is taking a method of type "a' * 'b -&gt;
'c" and turning it into "'a -&gt; 'b -&gt; 'c". Since F# methods are "automatically
curried", there's no need for a "curry" step (well, except perhaps when using .NET
methods, which are always "tupled", but that's another story).]<br /><br />
[<i>Side note</i>: a function like "add" is superfluous, because in F#, operators
are functions:<br /><font face="Courier New">&gt; (+);;<br />
val it : (int -&gt; int -&gt; int) = &lt;fun:clo@18&gt;<br />
&gt; let inc = (+) 1;;<br />
val inc : (int -&gt; int)</font>]<br /><b><br />
The pipeline</b><br /><br />
F# appears to have all this complicated syntax, with<font face="Courier New"> |&gt;
&lt;| &gt;&gt; &lt;&lt;</font> and so on. But, these operators are defined in F# code,
and follow some basic rules. They aren't magic or have any special compiler support.<br /><br />
The most important function operator is <font face="Courier New">|&gt;</font>. A quick
search of the F# source shows:<br /><font face="Courier New">C:\Program Files\FSharp-1.9.6.2\source\fsharp\FSharp.Core\prim-types.fs(2062):        
<br />
        let inline (|&gt;) x f = f x</font><br /><br />
(Operators are surrounded in parentheses to define them and to use them as functions
with prefix notation.)<br />
The type signature is:<br /><font face="Courier New">&gt; (|&gt;);;<br />
val it : ('a -&gt; ('a -&gt; 'b) -&gt; 'b) = &lt;fun:clo@23&gt;<br /></font><br />
This is "alpha to a function alpha to beta to beta". That probably didn't help. Perhaps
looking at the type of function application will help:<br /><br /><font face="Courier New">&gt; let apply f x = f x;;<br />
val apply : ('a -&gt; 'b) -&gt; 'a -&gt; 'b</font><br /><br />
This demonstrates that a function application is really just taking a function "alpha
to beta", giving it an alpha, and getting a beta. [I'm open to suggestions on better
ways to pronounce type arguments.]<br /><br />
So, glance back up at the pipeline operator. We can see it's really just function
application _in reverse_. What is the use of such a construct? If you've used C# 3.0's
LINQ extension methods or a Unix shell, you probably already know. By reversing the
function application, we can write things in a much more natural order. To modify
something from the F# Quick Tour:<br /><br /><font face="Courier New">&gt; let filterTypes name =<br />
-   System.AppDomain.CurrentDomain.GetAssemblies()<br />
-   |&gt; Seq.map (fun a -&gt; a.GetTypes()) |&gt; Seq.concat<br />
-   |&gt; Seq.map (fun a -&gt; a.Name)<br />
-   |&gt; Seq.filter (fun s-&gt; s.Contains name);;<br /><br />
val filterTypes : string -&gt; seq&lt;string&gt;<br /><br />
&gt; filterTypes "Coll";;<br />
val it : seq&lt;string&gt;<br />
= seq ["ICollection"; "EvidenceCollection"; "GCCollectionMode"; "CollectionBase";
...]<br />
&gt;</font><br /><br />
Now, this is a bit embarrassing, but this took me a long time to get. I stared at
this and re-read the F# manual for probably an hour. How could something so simple
do such "complex" stuff?? Once I finally got used to the idea of functions being normal
values, and the whole "one arg one value" bit, it snapped together. The other operators
(<font face="Courier New">&lt;|, &gt;&gt;, &lt;&lt;</font>) are pretty easy to follow
once the basics are understood (going through prim-types.fs is a great experience).<br /><br /><b>What else?<br /></b>I hope this all helps fit some pieces together. Feel free to use the MSN thing
on the side of my site to ask questions or give me suggestions. Thanks!<br /><br />
Edit: Also check out <a href="http://lorgonblog.spaces.live.com/blog/cns%21701679AD17B6D310%21169.entry">F#
function types: fun with tuples and currying</a> (From an F# team member's blog.)<br /><br /><br /><p></p><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=0dfb63a3-b66c-4317-9e6c-affe59c86041" /></body>
      <title>Common Conceptual Issues with F# </title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,0dfb63a3-b66c-4317-9e6c-affe59c86041.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/11/03/Common+Conceptual+Issues+With+F.aspx</link>
      <pubDate>Mon, 03 Nov 2008 21:07:15 GMT</pubDate>
      <description>Several times I've had to explain a few basic F# things to new users. I ran into some of these too when I first looked at F#. If you've been looking at F#, but some things still don't click, I hope this will help break the chains of C/imperative languages. I'm assuming you know a bit about F#, perhaps from the &lt;a href="http://research.microsoft.com/fsharp/manual/quicktour.aspx"&gt;Quick
Tour&lt;/a&gt; or the F# Tutorial file that comes with the Visual Studio integration.&lt;br&gt;
&lt;br&gt;
&lt;b&gt;Functions always take and receive exactly one argument.&lt;/b&gt;
&lt;br&gt;
Despite anything you see, in F#, there's only one argument, and only one return value.
Let's look at how this plays out (I suggest firing up F# interactive and playing around):&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;&amp;gt; let inc x = x + 1;;&lt;br&gt;
val inc : int -&amp;gt; int&lt;br&gt;
&lt;br&gt;
&amp;gt; let add x y = x + y;;&lt;br&gt;
val add : int -&amp;gt; int -&amp;gt; int&lt;br&gt;
&lt;/font&gt;
&lt;br&gt;
[I like to read -&amp;gt; as "to", because it's short and sweet.] So, for the case of
"inc x", we see the signature is quite simple and expected "int to int". But for add?
We see "int to int to int". What this actually means is "a function that takes an
integer, and returns a function that takes an integer and returns an integer". 
&lt;br&gt;
&lt;br&gt;
The same signature in C# would look like this: &lt;font face="Courier New"&gt;Func&amp;lt;int,
&amp;lt;Func&amp;lt;int,int&amp;gt;&amp;gt;&amp;gt;&lt;/font&gt; or "&lt;font face="Courier New"&gt;Func&amp;lt;int,int&amp;gt;
Add(int x)&lt;/font&gt;". [Some day, think how odd it is to have two ways of representing
the function.] So when we call the F# function, we're really passing in the first
argument, getting a new function, then applying the second argument. Something like
this:&lt;br&gt;
&lt;br&gt;
1. add x y&lt;br&gt;
2. (add x) y&lt;br&gt;
3. closure1 y&lt;br&gt;
4. final-result&lt;br&gt;
&lt;br&gt;
"closure1" is what we get from the "partial" application of add. I'll touch on this
in a minute.&lt;br&gt;
&lt;br&gt;
So how do we _really_ pass in two arguments at once? We put two arguments into one
value, a tuple. We write it like this:&lt;br&gt;
&lt;font face="Courier New"&gt;
&lt;br&gt;
&amp;gt; let add (x, y) = x + y;;&lt;br&gt;
val add : int * int -&amp;gt; int&lt;br&gt;
&lt;/font&gt;
&lt;br&gt;
Notice the new type signature: "int by int to int" or "int int tuple to int". In C#,
this would be:&lt;br&gt;
&lt;br&gt;
int add(Tuple&amp;lt;int,int&amp;gt; arguments) { return Tuple.A + Tuple.B; }&lt;br&gt;
&lt;br&gt;
But F# nicely provides support for tuples [via pattern matching], so we can write
them much more naturally. This syntax also works on the way out:&lt;br&gt;
&lt;font face="Courier New"&gt;
&lt;br&gt;
&amp;gt; let pow23 x = x*x, x*x*x;;&lt;br&gt;
val pow23 : int -&amp;gt; int * int&lt;br&gt;
// "int to int int tuple"&lt;br&gt;
&lt;br&gt;
&amp;gt; let square, cube = pow23 7;;&lt;br&gt;
val square : int&lt;br&gt;
val cube : int&lt;br&gt;
&lt;br&gt;
&amp;gt; square, cube;;&lt;br&gt;
val it : int * int = (49, 343)&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
&lt;b&gt;There's never no value&lt;/b&gt;
&lt;br&gt;
Another common typo/misunderstanding is when creating a function with no arguments:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;&amp;gt; let sayHi = printfn "Hi";;&lt;br&gt;
val sayHi : unit&lt;br&gt;
&lt;br&gt;
Hi&lt;br&gt;
&amp;gt; sayHi;;&lt;br&gt;
val it : unit = ()&lt;br&gt;
&lt;/font&gt;
&lt;br&gt;
Oh, what happened here? Remember how _everything_ takes and returns exactly one value?
The same is true of functions that "don't return a value", such as printf. Instead
of "not returning a value" like C's &lt;font face="Courier New"&gt;void&lt;/font&gt;, functions
return a special type called &lt;font face="Courier New"&gt;unit&lt;/font&gt; with one value, &lt;font face="Courier New"&gt;()&lt;/font&gt;. 
&lt;br&gt;
&lt;br&gt;
Armed with this, let's see what the &lt;font face="Courier New"&gt;sayHi &lt;/font&gt;definition
actually says. It says "let a value called sayHi equal to the result of printfn".
Well, since the result of &lt;font face="Courier New"&gt;printfn &lt;/font&gt;is &lt;font face="Courier New"&gt;unit&lt;/font&gt;, &lt;font face="Courier New"&gt;sayHi &lt;/font&gt;becomes &lt;font face="Courier New"&gt;unit&lt;/font&gt;.
The execution happens immediately, and subsequent uses of &lt;font face="Courier New"&gt;sayHi &lt;/font&gt;just
get the value, &lt;font face="Courier New"&gt;unit&lt;/font&gt;. 
&lt;br&gt;
&lt;br&gt;
To actually do what we want, we need to take an argument. Then F# knows we're a function
value:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;&amp;gt; let sayHi() = printfn "Hi";;&lt;br&gt;
val sayHi : unit -&amp;gt; unit&lt;br&gt;
&lt;br&gt;
&amp;gt; sayHi;;&lt;br&gt;
val it : (unit -&amp;gt; unit) = &amp;lt;fun:clo@0&amp;gt;&lt;br&gt;
&lt;br&gt;
&amp;gt; sayHi();;&lt;br&gt;
Hi&lt;br&gt;
val it : unit = ()&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
By explicitly taking a &lt;font face="Courier New"&gt;unit &lt;/font&gt;parameter, &lt;font face="Courier New"&gt;sayHi&lt;/font&gt; becomes
a function (type unit to unit). Notice that if we just write "sayHi", we're just going
to get the _value_ of it (a function), not apply (execute) the function.&lt;br&gt;
&lt;br&gt;
&lt;b&gt;Partial application&lt;/b&gt;
&lt;br&gt;
OK, so a side effect of this system of "take on param and return a function that takes
the next", is that we can compose with just parts of a function. For instance, to
write an increment function, we can do this:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;&amp;gt; let add x y = x + y;;&lt;br&gt;
val add : int -&amp;gt; int -&amp;gt; int&lt;br&gt;
&lt;br&gt;
&amp;gt; let inc x = add x 1;;&lt;br&gt;
val inc : int -&amp;gt; int&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
So far, nothing interesting. However, we can also write this more effectively:&lt;br&gt;
&lt;font face="Courier New"&gt;
&lt;br&gt;
&amp;gt; let inc = add 1;;&lt;br&gt;
val inc : (int -&amp;gt; int)&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
Aha! What's happening here is what happens "secretly" each time we call add with 2
parameters. We're just using the intermediate result, the closure of "add 1", and
assigning that function value to inc. In C#, it'd be something like this:&lt;br&gt;
&lt;pre&gt;&lt;span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;public&lt;/span&gt; &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;static&lt;/span&gt; Func&amp;lt;&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;int&lt;/span&gt;, &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;int&lt;/span&gt;&amp;gt;
Add(&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;int&lt;/span&gt; x)
{ &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;return&lt;/span&gt; y
=&amp;gt; x &lt;span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;+&lt;/span&gt; y;
} &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;public&lt;/span&gt; &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;static&lt;/span&gt; Func&amp;lt;&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;int&lt;/span&gt;, &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;int&lt;/span&gt;&amp;gt;
Inc &lt;span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;=&lt;/span&gt; Add(1); &lt;span style="color: Green; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;//
and "full application" of add looks like this: Add(1)(2)&lt;/span&gt; &lt;/span&gt;&lt;/pre&gt;[&lt;i&gt;BTW&lt;/i&gt;,
this isn't really currying in F#. Currying is taking a method of type "a' * 'b -&amp;gt;
'c" and turning it into "'a -&amp;gt; 'b -&amp;gt; 'c". Since F# methods are "automatically
curried", there's no need for a "curry" step (well, except perhaps when using .NET
methods, which are always "tupled", but that's another story).]&lt;br&gt;
&lt;br&gt;
[&lt;i&gt;Side note&lt;/i&gt;: a function like "add" is superfluous, because in F#, operators
are functions:&lt;br&gt;
&lt;font face="Courier New"&gt;&amp;gt; (+);;&lt;br&gt;
val it : (int -&amp;gt; int -&amp;gt; int) = &amp;lt;fun:clo@18&amp;gt;&lt;br&gt;
&amp;gt; let inc = (+) 1;;&lt;br&gt;
val inc : (int -&amp;gt; int)&lt;/font&gt;]&lt;br&gt;
&lt;b&gt;
&lt;br&gt;
The pipeline&lt;/b&gt;
&lt;br&gt;
&lt;br&gt;
F# appears to have all this complicated syntax, with&lt;font face="Courier New"&gt; |&amp;gt;
&amp;lt;| &amp;gt;&amp;gt; &amp;lt;&amp;lt;&lt;/font&gt; and so on. But, these operators are defined in F# code,
and follow some basic rules. They aren't magic or have any special compiler support.&lt;br&gt;
&lt;br&gt;
The most important function operator is &lt;font face="Courier New"&gt;|&amp;gt;&lt;/font&gt;. A quick
search of the F# source shows:&lt;br&gt;
&lt;font face="Courier New"&gt;C:\Program Files\FSharp-1.9.6.2\source\fsharp\FSharp.Core\prim-types.fs(2062):&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; let inline (|&amp;gt;) x f = f x&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
(Operators are surrounded in parentheses to define them and to use them as functions
with prefix notation.)&lt;br&gt;
The type signature is:&lt;br&gt;
&lt;font face="Courier New"&gt;&amp;gt; (|&amp;gt;);;&lt;br&gt;
val it : ('a -&amp;gt; ('a -&amp;gt; 'b) -&amp;gt; 'b) = &amp;lt;fun:clo@23&amp;gt;&lt;br&gt;
&lt;/font&gt;
&lt;br&gt;
This is "alpha to a function alpha to beta to beta". That probably didn't help. Perhaps
looking at the type of function application will help:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;&amp;gt; let apply f x = f x;;&lt;br&gt;
val apply : ('a -&amp;gt; 'b) -&amp;gt; 'a -&amp;gt; 'b&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
This demonstrates that a function application is really just taking a function "alpha
to beta", giving it an alpha, and getting a beta. [I'm open to suggestions on better
ways to pronounce type arguments.]&lt;br&gt;
&lt;br&gt;
So, glance back up at the pipeline operator. We can see it's really just function
application _in reverse_. What is the use of such a construct? If you've used C# 3.0's
LINQ extension methods or a Unix shell, you probably already know. By reversing the
function application, we can write things in a much more natural order. To modify
something from the F# Quick Tour:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;&amp;gt; let filterTypes name =&lt;br&gt;
-&amp;nbsp;&amp;nbsp; System.AppDomain.CurrentDomain.GetAssemblies()&lt;br&gt;
-&amp;nbsp;&amp;nbsp; |&amp;gt; Seq.map (fun a -&amp;gt; a.GetTypes()) |&amp;gt; Seq.concat&lt;br&gt;
-&amp;nbsp;&amp;nbsp; |&amp;gt; Seq.map (fun a -&amp;gt; a.Name)&lt;br&gt;
-&amp;nbsp;&amp;nbsp; |&amp;gt; Seq.filter (fun s-&amp;gt; s.Contains name);;&lt;br&gt;
&lt;br&gt;
val filterTypes : string -&amp;gt; seq&amp;lt;string&amp;gt;&lt;br&gt;
&lt;br&gt;
&amp;gt; filterTypes "Coll";;&lt;br&gt;
val it : seq&amp;lt;string&amp;gt;&lt;br&gt;
= seq ["ICollection"; "EvidenceCollection"; "GCCollectionMode"; "CollectionBase";
...]&lt;br&gt;
&amp;gt;&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
Now, this is a bit embarrassing, but this took me a long time to get. I stared at
this and re-read the F# manual for probably an hour. How could something so simple
do such "complex" stuff?? Once I finally got used to the idea of functions being normal
values, and the whole "one arg one value" bit, it snapped together. The other operators
(&lt;font face="Courier New"&gt;&amp;lt;|, &amp;gt;&amp;gt;, &amp;lt;&amp;lt;&lt;/font&gt;) are pretty easy to follow
once the basics are understood (going through prim-types.fs is a great experience).&lt;br&gt;
&lt;br&gt;
&lt;b&gt;What else?&lt;br&gt;
&lt;/b&gt;I hope this all helps fit some pieces together. Feel free to use the MSN thing
on the side of my site to ask questions or give me suggestions. Thanks!&lt;br&gt;
&lt;br&gt;
Edit: Also check out &lt;a href="http://lorgonblog.spaces.live.com/blog/cns%21701679AD17B6D310%21169.entry"&gt;F#
function types: fun with tuples and currying&lt;/a&gt; (From an F# team member's blog.)&lt;br&gt;
&lt;br&gt;
&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=0dfb63a3-b66c-4317-9e6c-affe59c86041" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,0dfb63a3-b66c-4317-9e6c-affe59c86041.aspx</comments>
      <category>Code</category>
      <category>FSharp</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=8046151c-913f-4bef-b5a2-6e5cc3203aca</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,8046151c-913f-4bef-b5a2-6e5cc3203aca.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,8046151c-913f-4bef-b5a2-6e5cc3203aca.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=8046151c-913f-4bef-b5a2-6e5cc3203aca</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <a href="http://wiki.freeswitch.org/wiki/Mod_managed">mod_managed</a> is
now in the <a href="http://www.freeswitch.org/">FreeSWITCH </a>tree. This replaces
mod_mono, and allows selection of either the Microsoft CLR or Mono 2.0+ as the runtime
engine to use. All the interfaces, and most of the code, are identical for both versions.
Modules written on Mono will work on the CLR version and vice versa.<br /><br />
Check it out.<br /><p></p><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=8046151c-913f-4bef-b5a2-6e5cc3203aca" /></body>
      <title>Mono or CLR in FreeSWITCH</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,8046151c-913f-4bef-b5a2-6e5cc3203aca.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/10/13/Mono+Or+CLR+In+FreeSWITCH.aspx</link>
      <pubDate>Mon, 13 Oct 2008 22:43:10 GMT</pubDate>
      <description>&lt;a href="http://wiki.freeswitch.org/wiki/Mod_managed"&gt;mod_managed&lt;/a&gt; is now in the &lt;a href="http://www.freeswitch.org/"&gt;FreeSWITCH &lt;/a&gt;tree.
This replaces mod_mono, and allows selection of either the Microsoft CLR or Mono 2.0+
as the runtime engine to use. All the interfaces, and most of the code, are identical
for both versions. Modules written on Mono will work on the CLR version and vice versa.&lt;br&gt;
&lt;br&gt;
Check it out.&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=8046151c-913f-4bef-b5a2-6e5cc3203aca" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,8046151c-913f-4bef-b5a2-6e5cc3203aca.aspx</comments>
      <category>Code</category>
      <category>FreeSWITCH</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=d38fb77d-7feb-4db7-90b0-4207bf2cdb54</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,d38fb77d-7feb-4db7-90b0-4207bf2cdb54.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,d38fb77d-7feb-4db7-90b0-4207bf2cdb54.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=d38fb77d-7feb-4db7-90b0-4207bf2cdb54</wfw:commentRss>
      <slash:comments>8</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">One common issue with IEnumerables is that
you can't find out anything about them until you use them. A frequent scenario is
wanting to know if the IEnumerable is empty before you go ahead and use it. For example,
you may want to write a result set to a file, but only if there's actually data. 
<br /><br />
As far as I know, the .NET Framework has no built-in classes to facilitate this, so
I hacked up my own. You use it by wrapping an IEnumerable inside an EmptyCheckEnumerable.
Then, when you check the IsEmpty property, it gets the enumerator and calls MoveNext
once. When you then go to consume it, it intercepts the MoveNext call and simply returns
the previous value. From then on, it just passes through. The result is that you don't
consume the IE twice, which can be necesary for performance or other reasons.<br /><br />
Example:<br /><pre><span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;">var
res <span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;">=</span><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">new</span> EmptyCheckEnumerable&lt;<span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">object</span>&gt;(dc.Execute&lt;<span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">object</span>&gt;(<span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"SELECT
* FROM foo"</span>)); <span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">if</span> (!res.IsEmpty)
{ <span style="color: Green; background-color: transparent; font-family: Courier New; font-size: 11px;">//
allocate resources and consume the IE - will only execute the SELECT once</span> }</span></pre>I
suggest creating a "ToEmptyCheck" extension method to flow type information. 
<br />
Code: 
<p></p><a href="http://www.atrevido.net/blog/content/binary/EmptyCheckEnumerable.cs.txt">EmptyCheckEnumerable.cs.txt
(2.14 KB)</a><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=d38fb77d-7feb-4db7-90b0-4207bf2cdb54" /></body>
      <title>Empty check on IEnumerable without consuming</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,d38fb77d-7feb-4db7-90b0-4207bf2cdb54.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/09/24/Empty+Check+On+IEnumerable+Without+Consuming.aspx</link>
      <pubDate>Wed, 24 Sep 2008 22:11:30 GMT</pubDate>
      <description>One common issue with IEnumerables is that you can't find out anything about them until you use them. A frequent scenario is wanting to know if the IEnumerable is empty before you go ahead and use it. For example, you may want to write a result set to a file, but only if there's actually data. &lt;br&gt;
&lt;br&gt;
As far as I know, the .NET Framework has no built-in classes to facilitate this, so
I hacked up my own. You use it by wrapping an IEnumerable inside an EmptyCheckEnumerable.
Then, when you check the IsEmpty property, it gets the enumerator and calls MoveNext
once. When you then go to consume it, it intercepts the MoveNext call and simply returns
the previous value. From then on, it just passes through. The result is that you don't
consume the IE twice, which can be necesary for performance or other reasons.&lt;br&gt;
&lt;br&gt;
Example:&lt;br&gt;
&lt;pre&gt;&lt;span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;var
res &lt;span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;=&lt;/span&gt; &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;new&lt;/span&gt; EmptyCheckEnumerable&amp;lt;&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;object&lt;/span&gt;&amp;gt;(dc.Execute&amp;lt;&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;object&lt;/span&gt;&amp;gt;(&lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"SELECT
* FROM foo"&lt;/span&gt;)); &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;if&lt;/span&gt; (!res.IsEmpty)
{ &lt;span style="color: Green; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;//
allocate resources and consume the IE - will only execute the SELECT once&lt;/span&gt; }&lt;/span&gt;&lt;/pre&gt;I
suggest creating a "ToEmptyCheck" extension method to flow type information. 
&lt;br&gt;
Code: 
&lt;p&gt;
&lt;/p&gt;
&lt;a href="http://www.atrevido.net/blog/content/binary/EmptyCheckEnumerable.cs.txt"&gt;EmptyCheckEnumerable.cs.txt
(2.14 KB)&lt;/a&gt;&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=d38fb77d-7feb-4db7-90b0-4207bf2cdb54" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,d38fb77d-7feb-4db7-90b0-4207bf2cdb54.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=b97a9b39-f255-4021-95ea-3ecafd48b536</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,b97a9b39-f255-4021-95ea-3ecafd48b536.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,b97a9b39-f255-4021-95ea-3ecafd48b536.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=b97a9b39-f255-4021-95ea-3ecafd48b536</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">In a previous comment, someone mentioned
the OO mindset ("mold" -- quite appropriate). I don't want to go into it much, but
simply "quote for win" something from here <a href="http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html">http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html</a>.
It's a nice take on things and I got a kick out of it:<br /><br />
"<br />
  The venerable master Qc Na was walking with his student, Anton.  Hoping
to<br />
prompt the master into a discussion, Anton said "Master, I have heard that<br />
objects are a very good thing - is this true?"  Qc Na looked pityingly at<br />
his student and replied, "Foolish pupil - objects are merely a poor man's<br />
closures."<br /><br />
  Chastised, Anton took his leave from his master and returned to his cell,<br />
intent on studying closures.  He carefully read the entire "Lambda: The<br />
Ultimate..." series of papers and its cousins, and implemented a small<br />
Scheme interpreter with a closure-based object system.  He learned much, and<br />
looked forward to informing his master of his progress.<br /><br />
  On his next walk with Qc Na, Anton attempted to impress his master by<br />
saying "Master, I have diligently studied the matter, and now understand<br />
that objects are truly a poor man's closures."  Qc Na responded by hitting<br />
Anton with his stick, saying "When will you learn? Closures are a poor man's<br />
object."  At that moment, Anton became enlightened.<br /><br />
"<br /><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=b97a9b39-f255-4021-95ea-3ecafd48b536" /></body>
      <title>Objects versus Closures - a koan</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,b97a9b39-f255-4021-95ea-3ecafd48b536.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/09/19/Objects+Versus+Closures+A+Koan.aspx</link>
      <pubDate>Fri, 19 Sep 2008 18:00:50 GMT</pubDate>
      <description>In a previous comment, someone mentioned the OO mindset ("mold" -- quite appropriate). I don't want to go into it much, but simply "quote for win" something from here &lt;a href="http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html"&gt;http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html&lt;/a&gt;.
It's a nice take on things and I got a kick out of it:&lt;br&gt;
&lt;br&gt;
"&lt;br&gt;
&amp;nbsp; The venerable master Qc Na was walking with his student, Anton.&amp;nbsp; Hoping
to&lt;br&gt;
prompt the master into a discussion, Anton said "Master, I have heard that&lt;br&gt;
objects are a very good thing - is this true?"&amp;nbsp; Qc Na looked pityingly at&lt;br&gt;
his student and replied, "Foolish pupil - objects are merely a poor man's&lt;br&gt;
closures."&lt;br&gt;
&lt;br&gt;
&amp;nbsp; Chastised, Anton took his leave from his master and returned to his cell,&lt;br&gt;
intent on studying closures.&amp;nbsp; He carefully read the entire "Lambda: The&lt;br&gt;
Ultimate..." series of papers and its cousins, and implemented a small&lt;br&gt;
Scheme interpreter with a closure-based object system.&amp;nbsp; He learned much, and&lt;br&gt;
looked forward to informing his master of his progress.&lt;br&gt;
&lt;br&gt;
&amp;nbsp; On his next walk with Qc Na, Anton attempted to impress his master by&lt;br&gt;
saying "Master, I have diligently studied the matter, and now understand&lt;br&gt;
that objects are truly a poor man's closures."&amp;nbsp; Qc Na responded by hitting&lt;br&gt;
Anton with his stick, saying "When will you learn? Closures are a poor man's&lt;br&gt;
object."&amp;nbsp; At that moment, Anton became enlightened.&lt;br&gt;
&lt;br&gt;
"&lt;br&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=b97a9b39-f255-4021-95ea-3ecafd48b536" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,b97a9b39-f255-4021-95ea-3ecafd48b536.aspx</comments>
      <category>Code</category>
      <category>FSharp</category>
      <category>Humour</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=1f85dc10-c273-42be-ae90-471f5472710f</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,1f85dc10-c273-42be-ae90-471f5472710f.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,1f85dc10-c273-42be-ae90-471f5472710f.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=1f85dc10-c273-42be-ae90-471f5472710f</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">I hacked up a little class to enable us
to use <a href="http://msdn.microsoft.com/en-us/library/cc280462.aspx">SQL 2008's
Change Tracking</a> feature with LINQ-to-SQL. Change Tracking allows you to see which
keys (and optionally columns) have changed in the database from a specific version.
The SQL docs have a great overview with lots of examples and information.<br /><br />
Basically, we get a special CHANGETABLE function to SELECT from, which gives us the
change information and keys. Additionally, there is the issue of versioning. Changes
are only kept so long, so we want to make sure the last version we sync'd is still
compatible, otherwise we have to re-initialize.<br /><br />
Finally, in order for our change SELECTs to be coherent, we need to snapshot the database.
The easiest way to get this is by turning on <a href="http://msdn.microsoft.com/en-us/library/ms130975.aspx">Snapshot
Isolation</a>. Snapshot isolation allows us to read a virtual snapshot of the database.
Any changes made from when we begin our transactions are not visible to us and we
do not lock anything we read. 
<br /><br />
Here's an excerpt from a class I have to provide change tracking for our database:<br /><pre><span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">public</span> DbDataChangeProvider(<span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">long</span> lastVersion)
{ <span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">this</span>.lastVersion <span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;">=</span> lastVersion; <span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">this</span>.txScope <span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;">=</span> ChangeTracking.GetSnapshotScope();
var validV <span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;">=</span> ChangeTracking.GetValidVersionForAll(dataContext);
baseline <span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;">=</span> lastVersion
&lt; validV; currentVersion <span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;">=</span> ChangeTracking.GetCurrentVersion(dataContext);
}</span></pre>We take in the last version, then initialize a SnapshotScope. We get
the minimum valid version and see if we're going to have to generate a baseline (re-init)
or not. Next, we grab the current version of the database, so consumers can save the
version for when they sync up next.<br /><br />
To get changed keys, you can do this:<br /><font face="Courier New">ChangeTracking.GetChangedKeys&lt;string&gt;(dataContext,
"Accounts", "AccountName", lastVersion, System.Data.Linq.ChangeAction.Delete);</font><br /><br />
This will give you an enumeration of all the Deleted keys; use other ChangeActions
to get Insert or Updated. There's also a filter (SQL string) to limit further.<br /><br />
To get changed _items_, you can pass in a Queryable, like this:<br /><font face="Courier New">ChangeTracking.GetChangedItems&lt;Account&gt;(dataContext,
dataContext.Accounts.Where(a=&gt;a.Balance&gt;10), "Accounts", "AccountName", lastVersion);</font><br /><br />
The code should (seems to work for me) figure out your query and inject the JOIN to
the CHANGETABLE function. The code is linked at the end of this article. Some of the
functions use a Tuple type; if you don't have it, I've posted it elsewhere on this
site. Or, you can delete those methods; they are only for 2-key tables.<br /><p></p><a href="http://www.atrevido.net/blog/content/binary/ChangeTracking.cs.txt">ChangeTracking.cs.txt
(9 KB)</a><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=1f85dc10-c273-42be-ae90-471f5472710f" /></body>
      <title>SQL 2008 Change Tracking with LINQ-to-SQL</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,1f85dc10-c273-42be-ae90-471f5472710f.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/09/18/SQL+2008+Change+Tracking+With+LINQtoSQL.aspx</link>
      <pubDate>Thu, 18 Sep 2008 02:03:46 GMT</pubDate>
      <description>I hacked up a little class to enable us to use &lt;a href="http://msdn.microsoft.com/en-us/library/cc280462.aspx"&gt;SQL
2008's Change Tracking&lt;/a&gt; feature with LINQ-to-SQL. Change Tracking allows you to
see which keys (and optionally columns) have changed in the database from a specific
version. The SQL docs have a great overview with lots of examples and information.&lt;br&gt;
&lt;br&gt;
Basically, we get a special CHANGETABLE function to SELECT from, which gives us the
change information and keys. Additionally, there is the issue of versioning. Changes
are only kept so long, so we want to make sure the last version we sync'd is still
compatible, otherwise we have to re-initialize.&lt;br&gt;
&lt;br&gt;
Finally, in order for our change SELECTs to be coherent, we need to snapshot the database.
The easiest way to get this is by turning on &lt;a href="http://msdn.microsoft.com/en-us/library/ms130975.aspx"&gt;Snapshot
Isolation&lt;/a&gt;. Snapshot isolation allows us to read a virtual snapshot of the database.
Any changes made from when we begin our transactions are not visible to us and we
do not lock anything we read. 
&lt;br&gt;
&lt;br&gt;
Here's an excerpt from a class I have to provide change tracking for our database:&lt;br&gt;
&lt;pre&gt;&lt;span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;public&lt;/span&gt; DbDataChangeProvider(&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;long&lt;/span&gt; lastVersion)
{ &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;this&lt;/span&gt;.lastVersion &lt;span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;=&lt;/span&gt; lastVersion; &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;this&lt;/span&gt;.txScope &lt;span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;=&lt;/span&gt; ChangeTracking.GetSnapshotScope();
var validV &lt;span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;=&lt;/span&gt; ChangeTracking.GetValidVersionForAll(dataContext);
baseline &lt;span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;=&lt;/span&gt; lastVersion
&amp;lt; validV; currentVersion &lt;span style="color: Red; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;=&lt;/span&gt; ChangeTracking.GetCurrentVersion(dataContext);
}&lt;/span&gt;&lt;/pre&gt;We take in the last version, then initialize a SnapshotScope. We get
the minimum valid version and see if we're going to have to generate a baseline (re-init)
or not. Next, we grab the current version of the database, so consumers can save the
version for when they sync up next.&lt;br&gt;
&lt;br&gt;
To get changed keys, you can do this:&lt;br&gt;
&lt;font face="Courier New"&gt;ChangeTracking.GetChangedKeys&amp;lt;string&amp;gt;(dataContext,
"Accounts", "AccountName", lastVersion, System.Data.Linq.ChangeAction.Delete);&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
This will give you an enumeration of all the Deleted keys; use other ChangeActions
to get Insert or Updated. There's also a filter (SQL string) to limit further.&lt;br&gt;
&lt;br&gt;
To get changed _items_, you can pass in a Queryable, like this:&lt;br&gt;
&lt;font face="Courier New"&gt;ChangeTracking.GetChangedItems&amp;lt;Account&amp;gt;(dataContext,
dataContext.Accounts.Where(a=&amp;gt;a.Balance&amp;gt;10), "Accounts", "AccountName", lastVersion);&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
The code should (seems to work for me) figure out your query and inject the JOIN to
the CHANGETABLE function. The code is linked at the end of this article. Some of the
functions use a Tuple type; if you don't have it, I've posted it elsewhere on this
site. Or, you can delete those methods; they are only for 2-key tables.&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;a href="http://www.atrevido.net/blog/content/binary/ChangeTracking.cs.txt"&gt;ChangeTracking.cs.txt
(9 KB)&lt;/a&gt;&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=1f85dc10-c273-42be-ae90-471f5472710f" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,1f85dc10-c273-42be-ae90-471f5472710f.aspx</comments>
      <category>Code</category>
      <category>Misc. Technology</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=1a161d7d-0d6e-456d-804f-f621766f10af</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,1a161d7d-0d6e-456d-804f-f621766f10af.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,1a161d7d-0d6e-456d-804f-f621766f10af.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=1a161d7d-0d6e-456d-804f-f621766f10af</wfw:commentRss>
      <slash:comments>6</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">Something I've heard often is that "F#
is too complex/functional programming is too hard". This is something that sorta came
up in the comments here: <a href="http://www.atrevido.net/blog/2008/09/16/Why+NOT+F.aspx">http://www.atrevido.net/blog/2008/09/16/Why+NOT+F.aspx</a>. 
<br /><br />
Why is this irrelevant? You only learn a language once. You pay the learning curve
cost one time; after that, you have the techniques and power at your disposal. However,
you pay the cost of code every time you read or write it. Since I'm going to read
and write a lot more code than number of languages I learn, I'd much, much, prefer
to pay this overhead once, up front, rather than in my code each time.<br /><br />
Of course, it's not necessarily this simple. It's possible to design a powerful language
that renders code even more difficult. Regular expressions are perhaps a nice example
of this; they're often called "write only" code. Every time I do a non-trivial regexp,
I'm always going back to the reference. Another example are C macros -- text-based,
they quickly let you get into trouble. The design of C# runs away from this and tries
to make it very difficult to write code that is "hard" to figure out -- if there's
any edge case where a feature might be confusing or not work, C# tends to not allow
it at all. 
<br /><br />
F# design is different. F# doesn't try to shelter users - it gives you tools and lets
you decide how to use them. It makes the assumption that if you're writing a program,
*you have some clue of what you're doing*. F#'s tools are still safe (compared to
say, C), but sure, you can go create a mess if you'd like. 
<br /><br />
Poor code quality is *not* something that should be fixed solely via technical measures.
I liken it to using web filters to make sure "employees aren't goofing off on the
Internet" -- this is a policy/management issue and should be solved via administrative
means. If one of my devs is spending all day on 4chan but gets work done and adds
value, what do I care? Similarly, if the code quality coming out is acceptable and
the solutions work correctly, I don't care if it used macros, custom operators, "difficult"
code, etc. The process to make sure code quality is high (code reviews) will take
care of anyone abusing language features in stupid ways.<br /><br />
But in truth, F# isn't actually much more complex to use. To the beginner, what seems
to be "unnecessary terseness" and a lot of complicated syntax is actually a very basic
system in action. Many of the "built-in" F# features such as the |&gt; pipeline operator
are defined right in the language itself. There's no magic going on -- you can create
your own functionality in exactly the same way. Once you understand the basic rules,
you'll see that most everything else follows them.<br /><br />
But at any rate, why is "easy to learn" a benefit? Sure, it's handy to promote a language
if people can pick it up easily, but it's not indicitive of long-term power. True,
if you have a "web developer" who's going to add a few server-side scripts, it's nice
that he doesn't have to learn much. But if you're developing an application of any
substance, I fail to see how these help, given the negative effects of having a "simple"
language.<br /><br />
P.S. On my site I'm not trying to infer that F# will take over the world or that C#
will go away. I've met too many "professional developers" to realise that anything
that requires thinking isn't going to achieve stellar adoption. I'm simply pointing
out that the reasons come down to apathy and intelligence (with respect to the learning
curve; there could be other reasons as well), regardless of how politically correct
one phrases it.<br /><br /><p></p><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=1a161d7d-0d6e-456d-804f-f621766f10af" /></body>
      <title>The learning curve is irrelevant</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,1a161d7d-0d6e-456d-804f-f621766f10af.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/09/17/The+Learning+Curve+Is+Irrelevant.aspx</link>
      <pubDate>Wed, 17 Sep 2008 20:49:06 GMT</pubDate>
      <description>Something I've heard often is that "F# is too complex/functional programming is too hard". This is something that sorta came up in the comments here: &lt;a href="http://www.atrevido.net/blog/2008/09/16/Why+NOT+F.aspx"&gt;http://www.atrevido.net/blog/2008/09/16/Why+NOT+F.aspx&lt;/a&gt;. 
&lt;br&gt;
&lt;br&gt;
Why is this irrelevant? You only learn a language once. You pay the learning curve
cost one time; after that, you have the techniques and power at your disposal. However,
you pay the cost of code every time you read or write it. Since I'm going to read
and write a lot more code than number of languages I learn, I'd much, much, prefer
to pay this overhead once, up front, rather than in my code each time.&lt;br&gt;
&lt;br&gt;
Of course, it's not necessarily this simple. It's possible to design a powerful language
that renders code even more difficult. Regular expressions are perhaps a nice example
of this; they're often called "write only" code. Every time I do a non-trivial regexp,
I'm always going back to the reference. Another example are C macros -- text-based,
they quickly let you get into trouble. The design of C# runs away from this and tries
to make it very difficult to write code that is "hard" to figure out -- if there's
any edge case where a feature might be confusing or not work, C# tends to not allow
it at all. 
&lt;br&gt;
&lt;br&gt;
F# design is different. F# doesn't try to shelter users - it gives you tools and lets
you decide how to use them. It makes the assumption that if you're writing a program,
*you have some clue of what you're doing*. F#'s tools are still safe (compared to
say, C), but sure, you can go create a mess if you'd like. 
&lt;br&gt;
&lt;br&gt;
Poor code quality is *not* something that should be fixed solely via technical measures.
I liken it to using web filters to make sure "employees aren't goofing off on the
Internet" -- this is a policy/management issue and should be solved via administrative
means. If one of my devs is spending all day on 4chan but gets work done and adds
value, what do I care? Similarly, if the code quality coming out is acceptable and
the solutions work correctly, I don't care if it used macros, custom operators, "difficult"
code, etc. The process to make sure code quality is high (code reviews) will take
care of anyone abusing language features in stupid ways.&lt;br&gt;
&lt;br&gt;
But in truth, F# isn't actually much more complex to use. To the beginner, what seems
to be "unnecessary terseness" and a lot of complicated syntax is actually a very basic
system in action. Many of the "built-in" F# features such as the |&amp;gt; pipeline operator
are defined right in the language itself. There's no magic going on -- you can create
your own functionality in exactly the same way. Once you understand the basic rules,
you'll see that most everything else follows them.&lt;br&gt;
&lt;br&gt;
But at any rate, why is "easy to learn" a benefit? Sure, it's handy to promote a language
if people can pick it up easily, but it's not indicitive of long-term power. True,
if you have a "web developer" who's going to add a few server-side scripts, it's nice
that he doesn't have to learn much. But if you're developing an application of any
substance, I fail to see how these help, given the negative effects of having a "simple"
language.&lt;br&gt;
&lt;br&gt;
P.S. On my site I'm not trying to infer that F# will take over the world or that C#
will go away. I've met too many "professional developers" to realise that anything
that requires thinking isn't going to achieve stellar adoption. I'm simply pointing
out that the reasons come down to apathy and intelligence (with respect to the learning
curve; there could be other reasons as well), regardless of how politically correct
one phrases it.&lt;br&gt;
&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=1a161d7d-0d6e-456d-804f-f621766f10af" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,1a161d7d-0d6e-456d-804f-f621766f10af.aspx</comments>
      <category>Code</category>
      <category>FSharp</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=12fc8c25-a371-4992-9b49-6e21fdd10e3a</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,12fc8c25-a371-4992-9b49-6e21fdd10e3a.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,12fc8c25-a371-4992-9b49-6e21fdd10e3a.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=12fc8c25-a371-4992-9b49-6e21fdd10e3a</wfw:commentRss>
      <slash:comments>17</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">This is actually an open request for comments.
I'm honestly interested in hearing why F# is not always the better candidate versus
C#. What can C# do well that F# cannot? In nearly everything, F# seems to come out
on top, as far as I can see. 
<br /><br />
Let's get these out of the way:<br /><br />
   - <i>Personal preference.</i> Enough said.<br />
   - <i>In beta.</i> Enough said.<br />
   - <i>Legacy code.</i> Sure, if you have a project in C#, it may not make
too much sense to switch mid-way.<br />
   - <i>Management.</i> Enough said.<br />
   - <i>No benefit. </i>This is simply lack of education and needs to be
addressed separately.<br />
   - <i>F#'s too hard/it's hard to hire F# devs.</i> This is a non-issue
that is a separate topic. In summary, anyone worth hiring for C# work should be able
to handle F#. [Exception being a very small deadline with an existing team...]<br /><br />
The only code reason I've seen is heavy native interop/pointer work. F# seems to be
slightly more verbose than C# in this case. It's not much more, but I could see if
you're doing just pointer code then it could get annoying. (Interestingly enough,
F# COM interop is much nicer than C# because it supports named and optional parameters
(<a href="http://blogs.msdn.com/dsyme/archive/2008/05/02/full-release-notes-for-f-1-9-4.aspx">http://blogs.msdn.com/dsyme/archive/2008/05/02/full-release-notes-for-f-1-9-4.aspx</a>,
search for "chart")...)<br /><br />
What other reasons are there for C# over F#?<br /><br /><b>Edit: </b>Good point in the comments about C# being a standard with open source
implementations. That could be a big issue for some. Another good point is the current
lack of tool support (like ClickOnce, ASPX and WPF designers, etc.). I don't see any
intrinsic reason F# wouldn't have those, except for limited resources.<br /><p></p><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=12fc8c25-a371-4992-9b49-6e21fdd10e3a" /></body>
      <title>Why NOT F#?</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,12fc8c25-a371-4992-9b49-6e21fdd10e3a.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/09/16/Why+NOT+F.aspx</link>
      <pubDate>Tue, 16 Sep 2008 05:06:28 GMT</pubDate>
      <description>This is actually an open request for comments. I'm honestly interested in hearing why F# is not always the better candidate versus C#. What can C# do well that F# cannot? In nearly everything, F# seems to come out on top, as far as I can see. &lt;br&gt;
&lt;br&gt;
Let's get these out of the way:&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp; - &lt;i&gt;Personal preference.&lt;/i&gt; Enough said.&lt;br&gt;
&amp;nbsp;&amp;nbsp; - &lt;i&gt;In beta.&lt;/i&gt; Enough said.&lt;br&gt;
&amp;nbsp;&amp;nbsp; - &lt;i&gt;Legacy code.&lt;/i&gt; Sure, if you have a project in C#, it may not make
too much sense to switch mid-way.&lt;br&gt;
&amp;nbsp;&amp;nbsp; - &lt;i&gt;Management.&lt;/i&gt; Enough said.&lt;br&gt;
&amp;nbsp;&amp;nbsp; - &lt;i&gt;No benefit. &lt;/i&gt;This is simply lack of education and needs to be
addressed separately.&lt;br&gt;
&amp;nbsp;&amp;nbsp; - &lt;i&gt;F#'s too hard/it's hard to hire F# devs.&lt;/i&gt; This is a non-issue
that is a separate topic. In summary, anyone worth hiring for C# work should be able
to handle F#. [Exception being a very small deadline with an existing team...]&lt;br&gt;
&lt;br&gt;
The only code reason I've seen is heavy native interop/pointer work. F# seems to be
slightly more verbose than C# in this case. It's not much more, but I could see if
you're doing just pointer code then it could get annoying. (Interestingly enough,
F# COM interop is much nicer than C# because it supports named and optional parameters
(&lt;a href="http://blogs.msdn.com/dsyme/archive/2008/05/02/full-release-notes-for-f-1-9-4.aspx"&gt;http://blogs.msdn.com/dsyme/archive/2008/05/02/full-release-notes-for-f-1-9-4.aspx&lt;/a&gt;,
search for "chart")...)&lt;br&gt;
&lt;br&gt;
What other reasons are there for C# over F#?&lt;br&gt;
&lt;br&gt;
&lt;b&gt;Edit: &lt;/b&gt;Good point in the comments about C# being a standard with open source
implementations. That could be a big issue for some. Another good point is the current
lack of tool support (like ClickOnce, ASPX and WPF designers, etc.). I don't see any
intrinsic reason F# wouldn't have those, except for limited resources.&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=12fc8c25-a371-4992-9b49-6e21fdd10e3a" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,12fc8c25-a371-4992-9b49-6e21fdd10e3a.aspx</comments>
      <category>Code</category>
      <category>FSharp</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=f4b59a78-5937-484a-8ab8-9b4052981359</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,f4b59a78-5937-484a-8ab8-9b4052981359.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,f4b59a78-5937-484a-8ab8-9b4052981359.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=f4b59a78-5937-484a-8ab8-9b4052981359</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">When specifying a connection string to
use with LINQ-to-SQL, make sure you "correctly" case MultipleActiveResultSets. If
you have something like this: "Server=(local);Database=master;Integrated Security=true;App=dcdemo;MultipleActiveResultsets=true",
LINQ-to-SQL will determine MARS is disabled even though it is not. 
<br /><br />
This is because inside the LINQ-to-SQL implementation, a normal String.Contains is
performed on the connection string. Since this is an ordinal compare, it won't find
MARS turned on if you spell it differently. Without MARS enabled, if you execute multiple
queries on a single DataContext, it will force the outstanding queries to buffer.
This means that instead of a nice lazy reading from the SQL server, you'll end up
bringing it all into local memory.<br /><br />
More info here: <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=366444">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=366444</a><br /><p></p><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=f4b59a78-5937-484a-8ab8-9b4052981359" /></body>
      <title>MARS is case-sensitive for LINQ-to-SQL</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,f4b59a78-5937-484a-8ab8-9b4052981359.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/09/16/MARS+Is+Casesensitive+For+LINQtoSQL.aspx</link>
      <pubDate>Tue, 16 Sep 2008 05:02:00 GMT</pubDate>
      <description>When specifying a connection string to use with LINQ-to-SQL, make sure you "correctly" case MultipleActiveResultSets. If you have something like this: "Server=(local);Database=master;Integrated Security=true;App=dcdemo;MultipleActiveResultsets=true", LINQ-to-SQL will determine MARS is disabled even though it is not. &lt;br&gt;
&lt;br&gt;
This is because inside the LINQ-to-SQL implementation, a normal String.Contains is
performed on the connection string. Since this is an ordinal compare, it won't find
MARS turned on if you spell it differently. Without MARS enabled, if you execute multiple
queries on a single DataContext, it will force the outstanding queries to buffer.
This means that instead of a nice lazy reading from the SQL server, you'll end up
bringing it all into local memory.&lt;br&gt;
&lt;br&gt;
More info here: &lt;a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=366444"&gt;https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=366444&lt;/a&gt;
&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=f4b59a78-5937-484a-8ab8-9b4052981359" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,f4b59a78-5937-484a-8ab8-9b4052981359.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=8ba440f9-e54b-4948-bb85-387e67765a41</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,8ba440f9-e54b-4948-bb85-387e67765a41.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,8ba440f9-e54b-4948-bb85-387e67765a41.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=8ba440f9-e54b-4948-bb85-387e67765a41</wfw:commentRss>
      <slash:comments>4</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
There are other great books out there such as <a href="http://www.amazon.com/Expert-F-Experts-Voice-Net/dp/1590598504">Expert
F#</a>. The F# Dev center has links to many other "learn F#" articles. All of these
are great.<br /><br />
But, something I found helpful is going "purely functional", and Haskell is the perfect
vehicle. When you're forced to think only functional, and don't have the other "escapes"
F# has, you bend your mind into understanding how you can accomplish things without
using mutation or object-orientation.<br /><br />
The downside of Haskell is that many resources seem to be very challenging to get
into. There's no doubt that the learning curve for Haskell can be tough. On top of
that, many materials tend to dive right into monads and it tends to end up too scary.
I've even bought several other good books on functional programming, but none of them
were easily approachable. (They have good content, but you can't start from zero by
using them.) 
<br /><br />
Enter <a href="http://book.realworldhaskell.org/">Real World Haskell</a>. This is
a *very* easy to follow book and really drives functional programming home. It doesn’t
assume you know anything about functional programming at all, so the learning curve
is a gentle slope.
</p>
        <p>
Even better? It's completely available online, so you can start reading it <a href="http://book.realworldhaskell.org/read/index.html">right
now</a>! Plus, it has reader-submitted comments which are of tremendous use, as they
ask and answer many common questions that might arise as you read along, without interfering
with the flow. You can read the entire book here: <a href="http://book.realworldhaskell.org/read/">http://book.realworldhaskell.org/read/</a> [But
buy it to support the excellent work the authors have done!]<br /><br />
I've found that my F# skills have gone up tremendously by reading Real World Haskell.
For instance, I "sorta" understood F#'s computation expressions and builder. Say,
enough to use them -- that's easy, like most things in F#), but understanding the
concepts behind them? Starting to learn Haskell really brings the understanding around.
This isn't to say that you'll eschew mutation and OO in F# -- such concepts can be
very useful (and increase performance on the CLR). But at least you'll know when a
more elegant solution is available. 
<br /><br />
(Plus, it's fun! As someone in #haskell on freenode put it to me: "Learning Haskell
will f*ck with your brain, and you'll like it.")
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=8ba440f9-e54b-4948-bb85-387e67765a41" />
      </body>
      <title>Become a better F# programmer via Real World Haskell</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,8ba440f9-e54b-4948-bb85-387e67765a41.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/09/02/Become+A+Better+F+Programmer+Via+Real+World+Haskell.aspx</link>
      <pubDate>Tue, 02 Sep 2008 04:00:06 GMT</pubDate>
      <description>&lt;p &gt;
There are other great books out there such as &lt;a href="http://www.amazon.com/Expert-F-Experts-Voice-Net/dp/1590598504"&gt;Expert
F#&lt;/a&gt;. The F# Dev center has links to many other "learn F#" articles. All of these
are great.&lt;br&gt;
&lt;br&gt;
But, something I found helpful is going "purely functional", and Haskell is the perfect
vehicle. When you're forced to think only functional, and don't have the other "escapes"
F# has, you bend your mind into understanding how you can accomplish things without
using mutation or object-orientation.&lt;br&gt;
&lt;br&gt;
The downside of Haskell is that many resources seem to be very challenging to get
into. There's no doubt that the learning curve for Haskell can be tough. On top of
that, many materials tend to dive right into monads and it tends to end up too scary.
I've even bought several other good books on functional programming, but none of them
were easily approachable. (They have good content, but you can't start from zero by
using them.) 
&lt;br&gt;
&lt;br&gt;
Enter &lt;a href="http://book.realworldhaskell.org/"&gt;Real World Haskell&lt;/a&gt;. This is
a *very* easy to follow book and really drives functional programming home. It doesn’t
assume you know anything about functional programming at all, so the learning curve
is a gentle slope.
&lt;/p&gt;
&lt;p &gt;
Even better? It's completely available online, so you can start reading it &lt;a href="http://book.realworldhaskell.org/read/index.html"&gt;right
now&lt;/a&gt;! Plus, it has reader-submitted comments which are of tremendous use, as they
ask and answer many common questions that might arise as you read along, without interfering
with the flow. You can read the entire book here: &lt;a href="http://book.realworldhaskell.org/read/"&gt;http://book.realworldhaskell.org/read/&lt;/a&gt; [But
buy it to support the excellent work the authors have done!]&lt;br&gt;
&lt;br&gt;
I've found that my F# skills have gone up tremendously by reading Real World Haskell.
For instance, I "sorta" understood F#'s computation expressions and builder. Say,
enough to use them -- that's easy, like most things in F#), but understanding the
concepts behind them? Starting to learn Haskell really brings the understanding around.
This isn't to say that you'll eschew mutation and OO in F# -- such concepts can be
very useful (and increase performance on the CLR). But at least you'll know when a
more elegant solution is available. 
&lt;br&gt;
&lt;br&gt;
(Plus, it's fun! As someone in #haskell on freenode put it to me: "Learning Haskell
will f*ck with your brain, and you'll like it.")
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=8ba440f9-e54b-4948-bb85-387e67765a41" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,8ba440f9-e54b-4948-bb85-387e67765a41.aspx</comments>
      <category>Code</category>
      <category>FSharp</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=4c444a50-11b9-4209-9aa6-dbc3fced5f35</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,4c444a50-11b9-4209-9aa6-dbc3fced5f35.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,4c444a50-11b9-4209-9aa6-dbc3fced5f35.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=4c444a50-11b9-4209-9aa6-dbc3fced5f35</wfw:commentRss>
      <title>No, really, the Event-based Asynchronous Pattern IS bad</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,4c444a50-11b9-4209-9aa6-dbc3fced5f35.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/08/29/No+Really+The+Eventbased+Asynchronous+Pattern+IS+Bad.aspx</link>
      <pubDate>Fri, 29 Aug 2008 21:03:55 GMT</pubDate>
      <description>Came across this:&lt;br&gt;
&lt;a href="http://michaelcurbanski.com/log/2008/08/29/functional-programmers-hate-events/"&gt;http://michaelcurbanski.com/log/2008/08/29/functional-programmers-hate-events/&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
His main point is that async total sucks, but that "Events don’t necessarily make
async code tragically unreadable!" As a demonstration, he shows some simple async
HTTP code without full or exception continuations. His code just enforces my point. 
&lt;br&gt;
&lt;br&gt;
At any rate, yes, sure, if your continuation code isn't too related to your calling
code, events can work. I mentioned this in my &lt;a href="http://www.atrevido.net/blog/2008/08/28/Tsk+Tsk+Silverlight+Events+Are+Not+Asyncs+Friend.aspx"&gt;post&lt;/a&gt;:
"events are a bad choice for code that is not loosely coupled" followed with "sometimes
a simple delegate field would be a better choice". Indeed, looking at Mike's sample
code, it seems as if using a simple delegate field would allow some nice refactoring.&lt;br&gt;
&lt;br&gt;
But a point of the &lt;a href="http://msdn.microsoft.com/en-us/library/wewwczdw.aspx"&gt;Event-based
Asynchronous Pattern&lt;/a&gt; is, and I quote, to "Wait for resources to become available
without stopping ("hanging") your application". So basically, you want to take an
existing method, say, in response to a user action, but you can't let it block. This
is exactly perfect for a continuation based approach and not so much for a loosely-coupled
event-based approach. The act of "firing" an event should indicate that you're letting
_other listeners_ (notice the plural) know when you did something. 
&lt;br&gt;
&lt;br&gt;
More on when events are appropriate: Say you're listening for SNMP messages and when
you receive one, you let "everyone" know that you did. You don't care what they do
with the result, and they just go off on their own. Events can work. Or, take, for
example, the &lt;a href="http://msdn.microsoft.com/en-us/library/8xs8549b.aspx"&gt;BackgroundWorker&lt;/a&gt;.
The BackgroundWorker doesn't help thread your blocking code, it just pushes the block
to a background thread you don't care about. Your HTTP code will still be all sync,
and you'll still burn a thread. BackgroundWorker main help is that it coordinates
back to your "UI" thread, since many UI frameworks have strong thread affinity and
will crash otherwise.&lt;br&gt;
&lt;br&gt;
&lt;b&gt;But that was the whole point&lt;/b&gt;
&lt;br&gt;
The event async pattern, specifically in things like Silverlight, is completely aimed
at *not letting the thread block*. That's the _only_ problem it is trying to solve.
Silverlight only forces this because the main thread is the UI thread, and they won't
want the browser hanging by dumb apps that don't put the block on a background thread.
If they didn't want to do continuations, they could have at least kept the sync APIs,
and thrown an exception if called from the main thread (thus letting people who know
what they're doing not have to deal with the ugly event syntax). 
&lt;br&gt;
&lt;br&gt;
&lt;b&gt;BTW, F# kicks the crap out of your language&lt;/b&gt;
&lt;br&gt;
I didn't mention it in my previous event post, but F#'s computation expressions let
you deal with continuations in a totally sexy way. &lt;a href="http://research.microsoft.com/%7Edsyme/"&gt;H.H.
Don Syme&lt;/a&gt;, writes about it here: &lt;a href="http://blogs.msdn.com/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx"&gt;Introducing
F# Asynchronous Workflows&lt;/a&gt;. You learn F# if you don't know it. But just to demonstrate,
here's an example from that introduction:&lt;br&gt;
&lt;br&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 0pt;"&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue;"&gt;let&lt;/span&gt; AsyncHttp(url:string)
=&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 0pt;"&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;async
{&lt;span style=""&gt;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style="color: green;"&gt;//
Create the web request object&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 0pt;"&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue;"&gt;let&lt;/span&gt; req
= WebRequest.Create(url)&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 0pt;"&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;
&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 0pt;"&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style="color: green;"&gt;//
Get the response, asynchronously 
&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 0pt;"&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue;"&gt;let!&lt;/span&gt; rsp
= req.GetResponseAsync()&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 0pt;"&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;
&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 0pt;"&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style="color: green;"&gt;//
Grab the response stream and a reader. Clean up when we're done&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 0pt;"&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue;"&gt;use&lt;/span&gt; stream
= rsp.GetResponseStream()&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 0pt;"&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue;"&gt;use&lt;/span&gt; reader
= &lt;span style="color: blue;"&gt;new&lt;/span&gt; System.IO.StreamReader(stream)&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 0pt;"&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;
&lt;o:p&gt;&amp;nbsp;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin: 0cm 0cm 0pt;"&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: green;"&gt;//
synchronous read-to-end&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;span style="font-size: 10pt; font-family: 'Lucida Console';"&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue;"&gt;return&lt;/span&gt; reader.ReadToEnd()
}&lt;/span&gt;
&lt;br&gt;
&lt;br&gt;
The let! binding handles things asynchronously; the rest of the body becomes a continuation.
If that isn't superior to any C# approach and doesn't make async easy, I don't know
what would.&lt;br&gt;
&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=4c444a50-11b9-4209-9aa6-dbc3fced5f35" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,4c444a50-11b9-4209-9aa6-dbc3fced5f35.aspx</comments>
      <category>Code</category>
      <category>FSharp</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=bb24026b-ab9e-409d-a72a-362a2e08496d</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,bb24026b-ab9e-409d-a72a-362a2e08496d.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,bb24026b-ab9e-409d-a72a-362a2e08496d.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=bb24026b-ab9e-409d-a72a-362a2e08496d</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">OK, so Silverlight 2 is still in Beta 2
and hopefully will have time to change. But I would have thought this fix would have
gotten into Beta 2 (as far as I can tell, it has not). At any rate, it applies to
async design in general.<br /><br /><b>Scenario: </b>You are writing an async method and need to call code when your async
process finishes. How do you expose this to your caller? For some reason (I'd love
to know what it is), it seems to be getting more popular to expose an event to accomplish
this. 
<br /><br /><b>Events suck: </b>Let's use a simple case. You want to get two URLs, using the return
of one to get the other, then print the result to the console. You have a few local
variables you need to use as well. Let's see what it'd look like without async:<br /><br /><font face="Courier New">// Inside some method:<br />
var url1 = Console.ReadLine();<br />
var url2 = Console.ReadLine();<br /></font><font face="Courier New">var someData = Console.ReadLine();</font><br /><font face="Courier New">// onEx = some exception handler<br />
try {<br />
    var res1 = webThingy.Download(url1);<br /></font><font face="Courier New">    </font><font face="Courier New">var
res2 = webThingy.Download(url2</font><font face="Courier New"> + "?data=" + res1.Data);</font><br /><font face="Courier New">    Console.WriteLine(someData + res2);</font><font face="Courier New"></font><br />
} catch (Exception ex) {<br />
    onEx(ex);<br />
}<br /><br />
Straightforward, eh? Now, with async + events? You _could_ go create a new object
type and add all sorts of fields and methods and whatnot, but that's a lot of work
and gets ugly quickly. Closures are a natural help here. So how does the event-based
async code look?<br /><font face="Courier New"><br /></font><font face="Courier New">// Inside some method:<br /></font><font face="Courier New"> var url1 = Console.ReadLine();<br />
var url2 = Console.ReadLine();<br /></font><font face="Courier New">var someData = Console.ReadLine();<br />
// onEx = some exception handler<br />
OnDownloadCompleteEventHandler first;<br />
webThingy.OnDownloadComplete += first = (o, res1) =&gt; {<br />
    if (res1.Exception != null) { 
<br />
        onEx(res1.Exception);<br />
        return;<br />
    }<br />
    webThingy.OnDownloadComplete -= first;<br />
    webThingy.OnDownloadComplete += (o2, res2) =&gt; {<br />
        if (res2.Exception != null) {<br />
            onEx(res2.Exception);<br />
            return;<br />
        }<br />
        try {<br />
            Console.WriteLine(someData
+ res2.Data);<br />
        } catch (Exception ex) { onEx(ex); }<br />
    }<br />
    try {<br />
        webThingy.DownloadAsync(url2 + "?data=" + res1.Data);<br />
    } catch (Exception ex) { onEx(ex); }<br />
};<br />
try {<br />
    webThingy.DownloadAsync(url1);<br />
} catch (Exception ex) { onEx(ex); }</font><br /><br />
I think this judges itself.<br /><br /><b>Better</b><br />
The way it SHOULD be is that any async method should take two arguments, one to call
for result, one for exception. Let's see how that would look:<br /><font face="Courier New"><br /></font><font face="Courier New">// Inside some method:<br /></font><font face="Courier New"> var url1 = Console.ReadLine();<br />
var url2 = Console.ReadLine();<br /></font><font face="Courier New">var someData = Console.ReadLine();<br />
// onEx = some exception handler<br />
webThingy.DownloadAsync(url1, onEx, res1 =&gt; {<br />
    webThingy.DownloadAsync(url2 + ?data=" + res1, onEx, res2 =&gt;
{<br />
        Console.WriteLine(someData + res2);<br />
    });<br />
});<br /></font><br />
This code isn't perfect, but it's sure a ton better than the event-based system. With
a bit extra work, you could build a simple async framework. Every Async method could
return an Async object that would allow you to consolidate stuff like exception handling
and cancellation. But even without that, this code straight away is much superior.<br /><br /><b>The extra downside</b><br />
Interestingly enough, .NET 1 had the concept of BeginXXX/EndXXX, but because there
were no closures, it was always a bit more of a pain to implement. BeginXXX/EndXXX,
while not making exception handling as easy, are at least a good start. 
<br /><br />
The cool thing about BeginXXX/EndXXX was that you could refactor them generically
into nice async syntax. Heres a quick and dirty example [F#'s async stuff works similarly.]:<br /><br /><font face="Courier New">static Action&lt;A1, Action&lt;Exception&gt;, Action&lt;R&gt;&gt;
ToAsync&lt;A1, R&gt;(<br />
    Func&lt;A1, AsyncCallback, object, IAsyncResult&gt; begin, 
<br />
    Func&lt;IAsyncResult, R&gt; end) {<br />
    return (arg, onEx, cont) =&gt; {<br />
        begin(arg, iar =&gt; {<br />
            try { cont(end(iar));
} catch (Exception ex) { onEx(ex); }<br />
        }, null);<br />
    };<br />
}<br />
static void BeginAcceptAsync(this Socket s, int timeout,<br />
    Action&lt;Exception&gt; onEx, Action&lt;Socket&gt; cont) {<br />
    ToAsync&lt;int, Socket&gt;(s.BeginAccept, s.EndAccept)(timeout,
onEx, cont);<br />
}<br />
static void Main() {<br />
    Socket s = ...;<br />
    s.BeginAcceptAsync(10, 
<br />
        ex =&gt; Console.WriteLine(ex),<br />
        sock =&gt; sock.Close());<br />
}<br /><br /></font>(Yes, I think this is a legitimate use of type extensions, but again, only
because the original library had a design flaw. And even the non-extension syntax
wouldn't necesarily be bad.)<br /><br />
But, to my knowledge, since there's no way to reference an event, this is not possible
with the async + event approach t hat is becoming all the rage (yes, SocketAsyncEventArgs,
I'm talking about you too). If you know of a way to ease the pain of async+events, <i>tell
me</i>.<br /><br /><b>In summary</b><br />
It seems that events are a bad choice for code that is not loosely coupled, such as
UIs. Even when loosely coupled, sometimes a simple delegate field would be a better
choice, since you can compose (like tacking on a filter or otherwise augmenting the
callback). But in the case of async, I cannot see how it is good.<br /><p></p><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=bb24026b-ab9e-409d-a72a-362a2e08496d" /></body>
      <title>Tsk, tsk, Silverlight  - Events are not async's friend</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,bb24026b-ab9e-409d-a72a-362a2e08496d.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/08/28/Tsk+Tsk+Silverlight+Events+Are+Not+Asyncs+Friend.aspx</link>
      <pubDate>Thu, 28 Aug 2008 01:48:31 GMT</pubDate>
      <description>OK, so Silverlight 2 is still in Beta 2 and hopefully will have time to change. But I would have thought this fix would have gotten into Beta 2 (as far as I can tell, it has not). At any rate, it applies to async design in general.&lt;br&gt;
&lt;br&gt;
&lt;b&gt;Scenario: &lt;/b&gt;You are writing an async method and need to call code when your async
process finishes. How do you expose this to your caller? For some reason (I'd love
to know what it is), it seems to be getting more popular to expose an event to accomplish
this. 
&lt;br&gt;
&lt;br&gt;
&lt;b&gt;Events suck: &lt;/b&gt;Let's use a simple case. You want to get two URLs, using the return
of one to get the other, then print the result to the console. You have a few local
variables you need to use as well. Let's see what it'd look like without async:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;// Inside some method:&lt;br&gt;
var url1 = Console.ReadLine();&lt;br&gt;
var url2 = Console.ReadLine();&lt;br&gt;
&lt;/font&gt;&lt;font face="Courier New"&gt;var someData = Console.ReadLine();&lt;/font&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;// onEx = some exception handler&lt;br&gt;
try {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; var res1 = webThingy.Download(url1);&lt;br&gt;
&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/font&gt;&lt;font face="Courier New"&gt;var
res2 = webThingy.Download(url2&lt;/font&gt;&lt;font face="Courier New"&gt; + "?data=" + res1.Data);&lt;/font&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(someData + res2);&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;
&lt;br&gt;
} catch (Exception ex) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; onEx(ex);&lt;br&gt;
}&lt;br&gt;
&lt;br&gt;
Straightforward, eh? Now, with async + events? You _could_ go create a new object
type and add all sorts of fields and methods and whatnot, but that's a lot of work
and gets ugly quickly. Closures are a natural help here. So how does the event-based
async code look?&lt;br&gt;
&lt;font face="Courier New"&gt;
&lt;br&gt;
&lt;/font&gt;&lt;font face="Courier New"&gt;// Inside some method:&lt;br&gt;
&lt;/font&gt;&lt;font face="Courier New"&gt; var url1 = Console.ReadLine();&lt;br&gt;
var url2 = Console.ReadLine();&lt;br&gt;
&lt;/font&gt;&lt;font face="Courier New"&gt;var someData = Console.ReadLine();&lt;br&gt;
// onEx = some exception handler&lt;br&gt;
OnDownloadCompleteEventHandler first;&lt;br&gt;
webThingy.OnDownloadComplete += first = (o, res1) =&amp;gt; {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; if (res1.Exception != null) { 
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; onEx(res1.Exception);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;
&amp;nbsp; &amp;nbsp; webThingy.OnDownloadComplete -= first;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; webThingy.OnDownloadComplete += (o2, res2) =&amp;gt; {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (res2.Exception != null) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; onEx(res2.Exception);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; try {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(someData
+ res2.Data);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; } catch (Exception ex) { onEx(ex); }&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; try {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; webThingy.DownloadAsync(url2 + "?data=" + res1.Data);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; } catch (Exception ex) { onEx(ex); }&lt;br&gt;
};&lt;br&gt;
try {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; webThingy.DownloadAsync(url1);&lt;br&gt;
} catch (Exception ex) { onEx(ex); }&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
I think this judges itself.&lt;br&gt;
&lt;br&gt;
&lt;b&gt;Better&lt;/b&gt;
&lt;br&gt;
The way it SHOULD be is that any async method should take two arguments, one to call
for result, one for exception. Let's see how that would look:&lt;br&gt;
&lt;font face="Courier New"&gt;
&lt;br&gt;
&lt;/font&gt;&lt;font face="Courier New"&gt;// Inside some method:&lt;br&gt;
&lt;/font&gt;&lt;font face="Courier New"&gt; var url1 = Console.ReadLine();&lt;br&gt;
var url2 = Console.ReadLine();&lt;br&gt;
&lt;/font&gt;&lt;font face="Courier New"&gt;var someData = Console.ReadLine();&lt;br&gt;
// onEx = some exception handler&lt;br&gt;
webThingy.DownloadAsync(url1, onEx, res1 =&amp;gt; {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; webThingy.DownloadAsync(url2 + ?data=" + res1, onEx, res2 =&amp;gt;
{&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(someData + res2);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; });&lt;br&gt;
});&lt;br&gt;
&lt;/font&gt;
&lt;br&gt;
This code isn't perfect, but it's sure a ton better than the event-based system. With
a bit extra work, you could build a simple async framework. Every Async method could
return an Async object that would allow you to consolidate stuff like exception handling
and cancellation. But even without that, this code straight away is much superior.&lt;br&gt;
&lt;br&gt;
&lt;b&gt;The extra downside&lt;/b&gt;
&lt;br&gt;
Interestingly enough, .NET 1 had the concept of BeginXXX/EndXXX, but because there
were no closures, it was always a bit more of a pain to implement. BeginXXX/EndXXX,
while not making exception handling as easy, are at least a good start. 
&lt;br&gt;
&lt;br&gt;
The cool thing about BeginXXX/EndXXX was that you could refactor them generically
into nice async syntax. Heres a quick and dirty example [F#'s async stuff works similarly.]:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;static Action&amp;lt;A1, Action&amp;lt;Exception&amp;gt;, Action&amp;lt;R&amp;gt;&amp;gt;
ToAsync&amp;lt;A1, R&amp;gt;(&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Func&amp;lt;A1, AsyncCallback, object, IAsyncResult&amp;gt; begin, 
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Func&amp;lt;IAsyncResult, R&amp;gt; end) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; return (arg, onEx, cont) =&amp;gt; {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; begin(arg, iar =&amp;gt; {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; try { cont(end(iar));
} catch (Exception ex) { onEx(ex); }&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }, null);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; };&lt;br&gt;
}&lt;br&gt;
static void BeginAcceptAsync(this Socket s, int timeout,&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Action&amp;lt;Exception&amp;gt; onEx, Action&amp;lt;Socket&amp;gt; cont) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; ToAsync&amp;lt;int, Socket&amp;gt;(s.BeginAccept, s.EndAccept)(timeout,
onEx, cont);&lt;br&gt;
}&lt;br&gt;
static void Main() {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Socket s = ...;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; s.BeginAcceptAsync(10, 
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ex =&amp;gt; Console.WriteLine(ex),&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; sock =&amp;gt; sock.Close());&lt;br&gt;
}&lt;br&gt;
&lt;br&gt;
&lt;/font&gt;(Yes, I think this is a legitimate use of type extensions, but again, only
because the original library had a design flaw. And even the non-extension syntax
wouldn't necesarily be bad.)&lt;br&gt;
&lt;br&gt;
But, to my knowledge, since there's no way to reference an event, this is not possible
with the async + event approach t hat is becoming all the rage (yes, SocketAsyncEventArgs,
I'm talking about you too). If you know of a way to ease the pain of async+events, &lt;i&gt;tell
me&lt;/i&gt;.&lt;br&gt;
&lt;br&gt;
&lt;b&gt;In summary&lt;/b&gt;
&lt;br&gt;
It seems that events are a bad choice for code that is not loosely coupled, such as
UIs. Even when loosely coupled, sometimes a simple delegate field would be a better
choice, since you can compose (like tacking on a filter or otherwise augmenting the
callback). But in the case of async, I cannot see how it is good.&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=bb24026b-ab9e-409d-a72a-362a2e08496d" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,bb24026b-ab9e-409d-a72a-362a2e08496d.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=e19e35a8-24d1-4a0f-8444-0314b79743c6</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,e19e35a8-24d1-4a0f-8444-0314b79743c6.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,e19e35a8-24d1-4a0f-8444-0314b79743c6.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=e19e35a8-24d1-4a0f-8444-0314b79743c6</wfw:commentRss>
      <slash:comments>11</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">Can someone explain to me the point of
having delegate types in C#/.NET? They made sense in the non-generic .NET 1 world,
but with generics they should have no reason to exist (except maybe purely as a type
alias). All the delegates in common use are representable with a generic definition
(think Action/Func&lt;...&gt;). But for some reason, you cannot automatically use
an equivalent delegate in C#.<br /><br />
This manifests a bit more when you consider a local such as:<br /><br />
var inc = (int x) =&gt; i + 1;<br /><br />
As Expression&lt;T&gt; syntax takes the same form, the compiler cannot tell if it's
an expression or a delegate. Additionally, since Func&lt;int,int&gt; is "just as good"
as any other generic type, even if the compiler wanted to create a delegate, it wouldn't
know to use Func&lt;int,int&gt;. Thus, you must specify it, and inner functions are
too clunky to be used in C#.<br /><br />
The answer I got from Microsoft (not an official answer, just a response to a Connect
item) was that C# might allow auto-conversion in version 4, but also that delegates
aren't totally useless because recursive delegate types can't be declared in that
fashion. But for the relatively few uses (fixed-point combinators?) of such types,
built-in, specific support would be a small sacrifice, wouldn't it?<br /><br />
This is just something I've been wondering about.<br /><br /><i>Update:</i> Thanks for <a href="http://www.jprl.com/">Jonathan Pryor</a> for pointing
out in the comments what my limited functional mind missed: ref/out parameters and
of course, and high-arity delegates. While these should be easy to work around, they
are accurate technical reasons. Thanks.<br /><p></p><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=e19e35a8-24d1-4a0f-8444-0314b79743c6" /></body>
      <title>Why are there still delegates?</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,e19e35a8-24d1-4a0f-8444-0314b79743c6.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/08/28/Why+Are+There+Still+Delegates.aspx</link>
      <pubDate>Thu, 28 Aug 2008 00:18:44 GMT</pubDate>
      <description>Can someone explain to me the point of having delegate types in C#/.NET? They made sense in the non-generic .NET 1 world, but with generics they should have no reason to exist (except maybe purely as a type alias). All the delegates in common use are representable with a generic definition (think Action/Func&amp;lt;...&amp;gt;). But for some reason, you cannot automatically use an equivalent delegate in C#.&lt;br&gt;
&lt;br&gt;
This manifests a bit more when you consider a local such as:&lt;br&gt;
&lt;br&gt;
var inc = (int x) =&amp;gt; i + 1;&lt;br&gt;
&lt;br&gt;
As Expression&amp;lt;T&amp;gt; syntax takes the same form, the compiler cannot tell if it's
an expression or a delegate. Additionally, since Func&amp;lt;int,int&amp;gt; is "just as good"
as any other generic type, even if the compiler wanted to create a delegate, it wouldn't
know to use Func&amp;lt;int,int&amp;gt;. Thus, you must specify it, and inner functions are
too clunky to be used in C#.&lt;br&gt;
&lt;br&gt;
The answer I got from Microsoft (not an official answer, just a response to a Connect
item) was that C# might allow auto-conversion in version 4, but also that delegates
aren't totally useless because recursive delegate types can't be declared in that
fashion. But for the relatively few uses (fixed-point combinators?) of such types,
built-in, specific support would be a small sacrifice, wouldn't it?&lt;br&gt;
&lt;br&gt;
This is just something I've been wondering about.&lt;br&gt;
&lt;br&gt;
&lt;i&gt;Update:&lt;/i&gt; Thanks for &lt;a href="http://www.jprl.com/"&gt;Jonathan Pryor&lt;/a&gt; for pointing
out in the comments what my limited functional mind missed: ref/out parameters and
of course, and high-arity delegates. While these should be easy to work around, they
are accurate technical reasons. Thanks.&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=e19e35a8-24d1-4a0f-8444-0314b79743c6" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,e19e35a8-24d1-4a0f-8444-0314b79743c6.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=d7828ef8-8c3f-4ac5-82c7-84b292ce1595</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,d7828ef8-8c3f-4ac5-82c7-84b292ce1595.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,d7828ef8-8c3f-4ac5-82c7-84b292ce1595.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=d7828ef8-8c3f-4ac5-82c7-84b292ce1595</wfw:commentRss>
      <slash:comments>10</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <style>
          <!--
 /* Font Definitions */
 @font-face
	{font-family:"Cambria Math";
	panose-1:2 4 5 3 5 4 6 3 2 4;}
@font-face
	{font-family:Calibri;
	panose-1:2 15 5 2 2 2 4 3 2 4;}
@font-face
	{font-family:Consolas;
	panose-1:2 11 6 9 2 2 4 3 2 4;}
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{margin-top:0in;
	margin-right:0in;
	margin-bottom:10.0pt;
	margin-left:0in;
	line-height:115%;
	font-size:11.0pt;
	font-family:"Calibri","sans-serif";}
a:link, span.MsoHyperlink
	{color:blue;
	text-decoration:underline;}
a:visited, span.MsoHyperlinkFollowed
	{color:purple;
	text-decoration:underline;}
.MsoPapDefault
	{margin-bottom:10.0pt;
	line-height:115%;}
@page Section1
	{size:8.5in 11.0in;
	margin:1.0in 1.0in 1.0in 1.0in;}
div.Section1
	{page:Section1;}
-->
        </style>
        <p class="MsoNormal">
[Yea, I’m not a web dev, and actively avoid it as much as possible, so I’m late to
this party.] 
</p>
        <p class="MsoNormal">
The interesting thing about ASP.NET MVC is that it takes an opposite approach to ASP.NET
in general. ASP.NET concepts try to “build up”, so as to shelter us from the evolved
idiocy that is HTML, as well as clean up the inherently stateless nature of HTTP.
ASP.NET MVC makes no attempt and forces you to deal with reality. Considering ASP.NET’s
abstraction isn’t really perfect (example: databinding sucks), MVC’s approach is unfortunately
refreshing.
</p>
        <p class="MsoNormal">
Because of its “raw” nature, you’ll be writing a lot more HTML than you’d do with
ASP.NET, and this HTML must line up with code on your server. To make this less of
a pain, there are some HTML helper functions. Rob “<a href="http://blog.wekeroad.com/2007/08/24/linq-understanding-linq-vars-and-lambdas/"> type
inference”</a> Conery has an overview <a href="http://blog.wekeroad.com/blog/aspnet-mvc-preview-using-the-mvc-ui-helpers/">here</a>.
</p>
        <p class="MsoNormal">
Here’s the signature for one of the functions:
</p>
        <p class="MsoNormal">
          <font face="Courier New">    public static string CheckBox(this HtmlHelper
helper, string htmlName, string text, string value, bool isChecked, <b>object htmlAttributes</b>);</font>
        </p>
        <p class="MsoNormal">
The last parameter confused me. Why would it be an object? Am I supposed to pass in
an IDictionary&lt;string,string&gt;? Just a long string? To make it more confusing,
other helpers had two overloads:
</p>
        <p class="MsoNormal">
          <font face="Courier New">    public static string TextArea(this HtmlHelper
helper, string htmlName, object value, <b>IDictionary&lt;string, object&gt; htmlAttributes</b>);</font>
        </p>
        <p class="MsoNormal">
          <font face="Courier New">    public static string TextArea(this HtmlHelper
helper, string htmlName, object value, <b>object htmlAttributes</b>);</font>
        </p>
        <p class="MsoNormal">
OK, so they explicitly called out the IDictionary there – THEN WHO WAS OBJECT HTMLATTRIBUTES?
</p>
        <p class="MsoNormal">
Rob covers in his overview. The idea is that you’re supposed to use anonymous types
to hack around the lack of tuples. 
</p>
        <p class="MsoNormal" style="margin-left: 0.5in; text-indent: 0.5in;">
          <font face="Courier New">&lt;%=Html.Whatever(arg1, bla, …,<br />
                            
new { @class=”cssx”, style=”x:f” …}) %&gt;</font>
        </p>
        <p class="MsoNormal">
What a great case of not-having-built-in-tuples-is-lame. It’s so lame, Microsoft’s
own developer teams have to resort to weird (but quite creative!) hacks like this
so that their syntax won’t completely suck*. Damn.
</p>
        <p class="MsoNormal">
          <b>And now, a duck</b>
        </p>
        <p class="MsoNormal">
For bonus points, there is another C# compiler feature that the MVC team could have
[ab]used, and it would arguably have made more sense (although the syntax isn’t as
tight). C# supports duck typing on collection initializers! So, they could create
a class like this: 
<br /></p>
        <p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;">
          <span style="font-family: Consolas;">    <span style="color: blue;">public</span><span style="color: blue;">class</span><span style="color: rgb(43, 145, 175);">HtmlAttributes</span> :
System.Collections.<span style="color: rgb(43, 145, 175);">IEnumerable</span></span>
        </p>
        <p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;">
          <span style="font-family: Consolas;">    {</span>
        </p>
        <p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;">
          <span style="font-family: Consolas;">        <span style="color: blue;">public</span> System.Collections.<span style="color: rgb(43, 145, 175);">IEnumerator</span> GetEnumerator()
{ ... }</span>
        </p>
        <p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;">
          <span style="font-family: Consolas;">        <span style="color: blue;">public</span><span style="color: blue;">void</span> Add(<span style="color: blue;">string</span> name, <span style="color: blue;">object</span> val)
{ ... }</span>
        </p>
        <p class="MsoNormal">
          <span style="font-family: Consolas;">    }</span>
        </p>
        <p class="MsoNormal">
And then they can write this:
</p>
        <p class="MsoNormal">
          <span style="font-family: Consolas; color: blue;">new</span>
          <span style="font-family: Consolas;">
            <span style="color: rgb(43, 145, 175);">HtmlAttributes</span> {
{ <span style="color: rgb(163, 21, 21);">"A"</span>, 123} , {<span style="color: rgb(163, 21, 21);">"B"</span>, <span style="color: rgb(163, 21, 21);">"test"</span>}
}</span>
        </p>
        <p class="MsoNormal">
No, it’s not as tight as the anonymous type syntax, but it does make a lot more sense. 
And tuples still make much more sense than either approach, and have benefits for
the rest of the language to boot (death to out parameters!). 
<br /></p>
        <p class="MsoNormal">
 *The only benefit I see in anonymous types is that, at compile time, you'll 
know there are no key conflicts - but that is totally trivial in the way they use
them, since all the keys are declared right there.<br /></p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=d7828ef8-8c3f-4ac5-82c7-84b292ce1595" />
      </body>
      <title>ASP.NET MVC Begs for Tuples</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,d7828ef8-8c3f-4ac5-82c7-84b292ce1595.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/08/27/ASPNET+MVC+Begs+For+Tuples.aspx</link>
      <pubDate>Wed, 27 Aug 2008 01:12:13 GMT</pubDate>
      <description>&lt;style&gt;
&lt;!--
 /* Font Definitions */
 @font-face
	{font-family:"Cambria Math";
	panose-1:2 4 5 3 5 4 6 3 2 4;}
@font-face
	{font-family:Calibri;
	panose-1:2 15 5 2 2 2 4 3 2 4;}
@font-face
	{font-family:Consolas;
	panose-1:2 11 6 9 2 2 4 3 2 4;}
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{margin-top:0in;
	margin-right:0in;
	margin-bottom:10.0pt;
	margin-left:0in;
	line-height:115%;
	font-size:11.0pt;
	font-family:"Calibri","sans-serif";}
a:link, span.MsoHyperlink
	{color:blue;
	text-decoration:underline;}
a:visited, span.MsoHyperlinkFollowed
	{color:purple;
	text-decoration:underline;}
.MsoPapDefault
	{margin-bottom:10.0pt;
	line-height:115%;}
@page Section1
	{size:8.5in 11.0in;
	margin:1.0in 1.0in 1.0in 1.0in;}
div.Section1
	{page:Section1;}
--&gt;
&lt;/style&gt;
&lt;p class="MsoNormal"&gt;
[Yea, I’m not a web dev, and actively avoid it as much as possible, so I’m late to
this party.] 
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
The interesting thing about ASP.NET MVC is that it takes an opposite approach to ASP.NET
in general. ASP.NET concepts try to “build up”, so as to shelter us from the evolved
idiocy that is HTML, as well as clean up the inherently stateless nature of HTTP.
ASP.NET MVC makes no attempt and forces you to deal with reality. Considering ASP.NET’s
abstraction isn’t really perfect (example: databinding sucks), MVC’s approach is unfortunately
refreshing.
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
Because of its “raw” nature, you’ll be writing a lot more HTML than you’d do with
ASP.NET, and this HTML must line up with code on your server. To make this less of
a pain, there are some HTML helper functions. Rob “&lt;a href="http://blog.wekeroad.com/2007/08/24/linq-understanding-linq-vars-and-lambdas/"&gt; type
inference”&lt;/a&gt; Conery has an overview &lt;a href="http://blog.wekeroad.com/blog/aspnet-mvc-preview-using-the-mvc-ui-helpers/"&gt;here&lt;/a&gt;.
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
Here’s the signature for one of the functions:
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static string CheckBox(this HtmlHelper
helper, string htmlName, string text, string value, bool isChecked, &lt;b&gt;object htmlAttributes&lt;/b&gt;);&lt;/font&gt;
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
The last parameter confused me. Why would it be an object? Am I supposed to pass in
an IDictionary&amp;lt;string,string&amp;gt;? Just a long string? To make it more confusing,
other helpers had two overloads:
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static string TextArea(this HtmlHelper
helper, string htmlName, object value, &lt;b&gt;IDictionary&amp;lt;string, object&amp;gt; htmlAttributes&lt;/b&gt;);&lt;/font&gt;
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static string TextArea(this HtmlHelper
helper, string htmlName, object value, &lt;b&gt;object htmlAttributes&lt;/b&gt;);&lt;/font&gt;
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
OK, so they explicitly called out the IDictionary there – THEN WHO WAS OBJECT HTMLATTRIBUTES?
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
Rob covers in his overview. The idea is that you’re supposed to use anonymous types
to hack around the lack of tuples. 
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-left: 0.5in; text-indent: 0.5in;"&gt;
&lt;font face="Courier New"&gt;&amp;lt;%=Html.Whatever(arg1, bla, …,&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
new { @class=”cssx”, style=”x:f” …}) %&amp;gt;&lt;/font&gt;
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
What a great case of not-having-built-in-tuples-is-lame. It’s so lame, Microsoft’s
own developer teams have to resort to weird (but quite creative!) hacks like this
so that their syntax won’t completely suck*. Damn.
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
&lt;b&gt;And now, a duck&lt;/b&gt;
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
For bonus points, there is another C# compiler feature that the MVC team could have
[ab]used, and it would arguably have made more sense (although the syntax isn’t as
tight). C# supports duck typing on collection initializers! So, they could create
a class like this: 
&lt;br&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;public&lt;/span&gt; &lt;span style="color: blue;"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43, 145, 175);"&gt;HtmlAttributes&lt;/span&gt; :
System.Collections.&lt;span style="color: rgb(43, 145, 175);"&gt;IEnumerable&lt;/span&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;public&lt;/span&gt; System.Collections.&lt;span style="color: rgb(43, 145, 175);"&gt;IEnumerator&lt;/span&gt; GetEnumerator()
{ ... }&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal" style="margin-bottom: 0.0001pt; line-height: normal;"&gt;
&lt;span style="font-family: Consolas;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;public&lt;/span&gt; &lt;span style="color: blue;"&gt;void&lt;/span&gt; Add(&lt;span style="color: blue;"&gt;string&lt;/span&gt; name, &lt;span style="color: blue;"&gt;object&lt;/span&gt; val)
{ ... }&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
&lt;span style="font-family: Consolas;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
And then they can write this:
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
&lt;span style="font-family: Consolas; color: blue;"&gt;new&lt;/span&gt;&lt;span style="font-family: Consolas;"&gt; &lt;span style="color: rgb(43, 145, 175);"&gt;HtmlAttributes&lt;/span&gt; {
{ &lt;span style="color: rgb(163, 21, 21);"&gt;"A"&lt;/span&gt;, 123} , {&lt;span style="color: rgb(163, 21, 21);"&gt;"B"&lt;/span&gt;, &lt;span style="color: rgb(163, 21, 21);"&gt;"test"&lt;/span&gt;}
}&lt;/span&gt;
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
No, it’s not as tight as the anonymous type syntax, but it does make a lot more sense.&amp;nbsp;
And tuples still make much more sense than either approach, and have benefits for
the rest of the language to boot (death to out parameters!). 
&lt;br&gt;
&lt;/p&gt;
&lt;p class="MsoNormal"&gt;
&amp;nbsp;*The only benefit I see in anonymous types is that, at compile time, you'll&amp;nbsp;
know there are no key conflicts - but that is totally trivial in the way they use
them, since all the keys are declared right there.&lt;br&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=d7828ef8-8c3f-4ac5-82c7-84b292ce1595" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,d7828ef8-8c3f-4ac5-82c7-84b292ce1595.aspx</comments>
      <category>ASP.NET</category>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=06e1766b-c068-415a-89f6-fdb0e73906eb</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,06e1766b-c068-415a-89f6-fdb0e73906eb.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,06e1766b-c068-415a-89f6-fdb0e73906eb.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=06e1766b-c068-415a-89f6-fdb0e73906eb</wfw:commentRss>
      <slash:comments>15</slash:comments>
      <title>Extension Methods Suck</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,06e1766b-c068-415a-89f6-fdb0e73906eb.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/08/27/Extension+Methods+Suck.aspx</link>
      <pubDate>Wed, 27 Aug 2008 00:17:53 GMT</pubDate>
      <description>
Been meaning to write this for a while, and I think I touched on it &lt;a href="http://www.atrevido.net/blog/2007/09/05/C+30+And+LINQ+Misunderstandings.aspx"&gt;here&lt;/a&gt;,
but I'd like to expand a bit. C# Extension Methods are just a hack to compensate for
C#'s poor handling of functions in general. As far as I can tell, they were added
solely so you can do this type of thing in LINQ:&lt;br&gt;
&lt;br&gt;
&lt;span style="font-family: &amp;quot;Courier New&amp;quot;;"&gt;&amp;nbsp; var squares = myInts.Select(i
=&amp;gt; i * i)&lt;/span&gt;
&lt;br&gt;
&lt;br&gt;
Instead of:&lt;br&gt;
&lt;br&gt;
&lt;span style="font-family: &amp;quot;Courier New&amp;quot;;"&gt;&amp;nbsp; var squares = Enumerable.Select(myInts,
i =&amp;gt; i * i)&lt;/span&gt;
&lt;br&gt;
&lt;br&gt;
In other words, they wanted to provide some simple infix syntax for functions. Well,
that's a poor approach to the problem. 
&lt;br&gt;
&lt;p&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; - First off, it only works on function specially declared to be
"extensions", which means your composition options are limited to whatever the library
has built in. I can't send arguments to arbitrary static methods, like, say, "someVar.Console.WriteLine". 
&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; - Second, since extension methods are defined solely by their method
name, ambiguity is quite easy to come across. There's no way to qualify Foo.Function
versus Bar.Function.&lt;span style=""&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p style=""&gt;
&lt;b style=""&gt;Pipeline&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/b&gt;
&lt;br&gt;
Other languages approach this with two simple things (which actually simplify the
entire language/type system overall). First off, we need to be able to define function
operators. I'll demonstrate with F#'s pipeline operator:&lt;br&gt;
&lt;br&gt;
&lt;span style="font-family: &amp;quot;Courier New&amp;quot;;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; let (|&amp;gt;)
x f = f x&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
[As a side note, any language that lets you toss around operators and functions will
allow this kind of syntax – it isn’t that F# had to have compiler support for this
particular operator.]
&lt;/p&gt;
&lt;p&gt;
&lt;span style=""&gt;In fake C#, it’d be something like (for fun, notice the lack of type
inference):&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p style="text-indent: 0.5in;"&gt;
&lt;span style="font-family: &amp;quot;Courier New&amp;quot;;"&gt;B operator|&amp;gt; &amp;lt;A, B&amp;gt;(A
x, Func&amp;lt;A, B&amp;gt; f) { return f(x); }&lt;/span&gt;
&lt;br&gt;
&lt;br&gt;
This means that the |&amp;gt; operator will take x on the left and apply it to f on the
right side. If this existed in C#, you'd be able to write something like:&lt;br&gt;
&lt;br&gt;
&lt;span style="font-family: &amp;quot;Courier New&amp;quot;;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; "Hello" |&amp;gt;
Console.WriteLine&lt;br&gt;
&lt;/span&gt;or&lt;br&gt;
&lt;span style="font-family: &amp;quot;Courier New&amp;quot;;"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (myInts
|&amp;gt; Enumerable.Any) { .... }&lt;br style=""&gt;
&lt;!--[if !supportLineBreakNewLine]--&gt;
&lt;br style=""&gt;
&lt;!--[endif]--&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Now we can pass in a parameter to static methods. But, hey, whaddya know? With this,
Extension Methods are solved for all single-argument static methods! That was easy.
But what about Select – it takes two parameters, so this won’t work. 
&lt;br&gt;
&lt;br&gt;
&lt;b style=""&gt;Enter the Lambda&lt;/b&gt;
&lt;br&gt;
What if ALL functions took one parameter and output one parameter? If that were the
case, then we’d be set. But how do allow more than one parameter? Well, what if, every
time you declared a method with more than one parameter, it actually returned a method
that took the next parameter? For example, we could write “Add” as:&lt;br&gt;
&lt;br&gt;
&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style=""&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="font-family: &amp;quot;Courier New&amp;quot;;"&gt;Func&amp;lt;int,int&amp;gt;
Add(Func&amp;lt;int,int&amp;gt; a) { return b =&amp;gt; &lt;span style=""&gt;&amp;nbsp;&lt;/span&gt;a + b; }&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
This is known as the curried form of Add. We’d now call it as: Add(5)(6). We can do
cute stuff like “var inc = Add(1)”. But, as the Add declaration shows, in C# this
is too unwieldy (and this is a simple example!). The compiler should actually do all
this for us, so we can just write our functions normally but use them as if they were
written in curried form.
&lt;/p&gt;
&lt;p&gt;
Now, if we simply swap the order of arguments for Enumerable.Select, we have our extension
method ready to roll: Enumerable.Select(Func, IEnumerable) can be used so:
&lt;/p&gt;
&lt;p style="text-indent: 0.5in;"&gt;
&lt;font face="Courier New"&gt;var squares = myInts |&amp;gt; Enumerable.Select(i =&amp;gt; i *
i)&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
Now the call to Select takes the lambda (i * i) and returns a function that takes
an Enumerable. It is then given the myInts, and everyone is happy. This is just a
quick, crap, explanation. Google can lead you to many more interesting resources about
partial application, currying and so on.&lt;br&gt;
&lt;/p&gt;
At any rate, I think if C# had taken this approach, we'd all be much better off. To
top it off, more functions would take their arguments in a proper style. As it is,
uncurried versions of Extension Methods are incompatible with normal function pipelining.
Oh well.&lt;br&gt;
&lt;br&gt;
&lt;p&gt;
&lt;br&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=06e1766b-c068-415a-89f6-fdb0e73906eb" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,06e1766b-c068-415a-89f6-fdb0e73906eb.aspx</comments>
      <category>Code</category>
      <category>FSharp</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=41902041-dd54-4407-ac4b-46ae041a3e57</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,41902041-dd54-4407-ac4b-46ae041a3e57.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,41902041-dd54-4407-ac4b-46ae041a3e57.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=41902041-dd54-4407-ac4b-46ae041a3e57</wfw:commentRss>
      <slash:comments>4</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">Someone on our team started using ASP.NET
MVC for a new web interface we're doing. I must say I'm impressed with the level that
the MVC team [ab]uses the C# compiler, mostly in a good way. On the plus side, they
end up with a bit more compiler time checking than would be possible otherwise (we
can only hope WPF will follow suit some day). 
<br /><br />
But one thing struck me odd was how their helper method for generating an HTML form
works. The goal is to generate an HTML form tag with the right action, and they use
lambdas as symbolic references to figure out the action. The next problem is making
sure that the &lt;form&gt; gets closed with a &lt;/form&gt;. The straightforward answer
to this is "create a function that takes a function". The C# signature would be: void
Form&lt;A&gt;(Expression&lt;Action&lt;A&gt;&gt;, Action). Then your ASPX code would
be:<br /><br />
&lt;% Html.Form&lt;FooController&gt;(x =&gt; x.Edit(someVar.FieldX), () =&gt; { %&gt;<br />
    Some Html &lt;% SomeCode%&gt;<br />
&lt;% }); %&gt;<br /><br />
The code is nicely bracketed and works fine. But ASP.NET MVC doesn't actually do that.
Instead, the Form method returns an IDisposable! The code to use it is:<br /><br />
&lt;% using (Html.Form&lt;FooController&gt;(x =&gt; x.Edit(someVar.FieldX)) { %&gt;<br />
    Some Html &lt;% SomeCode%&gt;<br />
&lt;% } %&gt;<br /><br />
Why do they use an IDisposable? The rest of the MVC framework seems to assumes people
are somewhat familiar with lambdas, closures and what not. The only thing I can think
of is that <a href="http://www.atrevido.net/blog/2008/03/31/The+Reason+VBNET+Is+Truly+A+Second+Class+Citizen.aspx">VB
doesn't support anonymous methods</a>. So in order to make it VB friendly, they come
up with quite a strange use of IDisposable to abuse language support for it. Overall,
I'm not sure if this is dumb or cute. 
<br /><p></p><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=41902041-dd54-4407-ac4b-46ae041a3e57" /></body>
      <title>ASP.NET MVC - Abusing Using (At VB's request?)</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,41902041-dd54-4407-ac4b-46ae041a3e57.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/08/26/ASPNET+MVC+Abusing+Using+At+VBs+Request.aspx</link>
      <pubDate>Tue, 26 Aug 2008 21:19:59 GMT</pubDate>
      <description>Someone on our team started using ASP.NET MVC for a new web interface we're doing. I must say I'm impressed with the level that the MVC team [ab]uses the C# compiler, mostly in a good way. On the plus side, they end up with a bit more compiler time checking than would be possible otherwise (we can only hope WPF will follow suit some day). &lt;br&gt;
&lt;br&gt;
But one thing struck me odd was how their helper method for generating an HTML form
works. The goal is to generate an HTML form tag with the right action, and they use
lambdas as symbolic references to figure out the action. The next problem is making
sure that the &amp;lt;form&amp;gt; gets closed with a &amp;lt;/form&amp;gt;. The straightforward answer
to this is "create a function that takes a function". The C# signature would be: void
Form&amp;lt;A&amp;gt;(Expression&amp;lt;Action&amp;lt;A&amp;gt;&amp;gt;, Action). Then your ASPX code would
be:&lt;br&gt;
&lt;br&gt;
&amp;lt;% Html.Form&amp;lt;FooController&amp;gt;(x =&amp;gt; x.Edit(someVar.FieldX), () =&amp;gt; { %&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Some Html &amp;lt;% SomeCode%&amp;gt;&lt;br&gt;
&amp;lt;% }); %&amp;gt;&lt;br&gt;
&lt;br&gt;
The code is nicely bracketed and works fine. But ASP.NET MVC doesn't actually do that.
Instead, the Form method returns an IDisposable! The code to use it is:&lt;br&gt;
&lt;br&gt;
&amp;lt;% using (Html.Form&amp;lt;FooController&amp;gt;(x =&amp;gt; x.Edit(someVar.FieldX)) { %&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Some Html &amp;lt;% SomeCode%&amp;gt;&lt;br&gt;
&amp;lt;% } %&amp;gt;&lt;br&gt;
&lt;br&gt;
Why do they use an IDisposable? The rest of the MVC framework seems to assumes people
are somewhat familiar with lambdas, closures and what not. The only thing I can think
of is that &lt;a href="http://www.atrevido.net/blog/2008/03/31/The+Reason+VBNET+Is+Truly+A+Second+Class+Citizen.aspx"&gt;VB
doesn't support anonymous methods&lt;/a&gt;. So in order to make it VB friendly, they come
up with quite a strange use of IDisposable to abuse language support for it. Overall,
I'm not sure if this is dumb or cute. 
&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=41902041-dd54-4407-ac4b-46ae041a3e57" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,41902041-dd54-4407-ac4b-46ae041a3e57.aspx</comments>
      <category>Code</category>
      <category>ASP.NET</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=0a572828-5362-4d33-acf0-696d0ff30f4f</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,0a572828-5362-4d33-acf0-696d0ff30f4f.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,0a572828-5362-4d33-acf0-696d0ff30f4f.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=0a572828-5362-4d33-acf0-696d0ff30f4f</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
          <font face="Verdana">I
saw this stack implementation (</font>
          <a href="http://blogs.msdn.com/jaredpar/archive/2008/08/15/immutablestack-in-f.aspx">
            <font face="Verdana">http://blogs.msdn.com/jaredpar/archive/2008/08/15/immutablestack-in-f.aspx</font>
          </a>
          <font face="Verdana">)
and wanted to see how I'd approach it:</font>
        </div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"> 
</div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">#light<br /><span style="COLOR: blue">open</span><span style="COLOR: black"> System<br /><br /></span><span style="COLOR: blue">type</span><span style="COLOR: black"> 'a ImmutableStack
= 
<br />
   | Empty<br />
   | Stack </span><span style="COLOR: blue">of</span><span style="COLOR: black"> 'a
* 'a ImmutableStack<br />
   </span><span style="COLOR: blue">member</span><span style="COLOR: black"> x.Peek()
= </span><span style="COLOR: blue">match</span><span style="COLOR: black"> x </span><span style="COLOR: blue">with</span><span style="COLOR: black"> |
Stack (v, _) </span><span style="COLOR: blue">-&gt;</span><span style="COLOR: black"> Some
v | _ </span><span style="COLOR: blue">-&gt;</span><span style="COLOR: black"> None<br />
   </span><span style="COLOR: blue">member</span><span style="COLOR: black"> x.Pop()
= </span><span style="COLOR: blue">match</span><span style="COLOR: black"> x </span><span style="COLOR: blue">with</span><span style="COLOR: black"> |
Stack (_, s) </span><span style="COLOR: blue">-&gt;</span><span style="COLOR: black"> s
| _ </span><span style="COLOR: blue">-&gt;</span><span style="COLOR: black"> failwith </span><span style="COLOR: #a31515">"empty
stack"<br /></span><span style="COLOR: black">   </span><span style="COLOR: blue">member</span><span style="COLOR: black"> x.Push
a = Stack(a, x)<br />
   </span><span style="COLOR: blue">member</span><span style="COLOR: black"> x.IsEmpty
= x = Empty 
<br /></span></div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"> 
</div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
          <font face="Verdana">(Well,
I'd probably just use a list in most cases.) But interestingly, he has an All function,
which returns a sequence of the entire stack. </font>
          <a href="http://blogs.msdn.com/chrsmith/default.aspx">
            <font face="Verdana">Chris</font>
          </a>
          <font face="Verdana"> suggested
using sequence expressions and then recursively calling the function:</font>
        </div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"> 
</div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
          <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
            <span style="COLOR: blue">member</span>
            <span style="COLOR: black"> x.All
=<br /></span>
            <span style="COLOR: blue">    match</span>
            <span style="COLOR: black"> data </span>
            <span style="COLOR: blue">with</span>
            <span style="COLOR: black">
              <br />
        | Empty </span>
            <span style="COLOR: blue">-&gt;</span>
            <span style="COLOR: black"> Seq.empty<br />
        | Value (v,n) </span>
            <span style="COLOR: blue">-&gt;</span>
            <span style="COLOR: black">
              <br />
            seq {<br />
                </span>
            <span style="COLOR: blue">yield</span>
            <span style="COLOR: black"> v<br />
                </span>
            <span style="COLOR: blue">yield!</span>
            <span style="COLOR: black"> n.All
}<br /></span>
          </div>
        </div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"> 
</div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
          <font face="Verdana">This
is pretty nice as far as syntax goes. For some reason, I wanted to see how it'd look
without the recursion (which needs to generate a new enumerator, unless the compiler
is doing some wicked awesome stuff, which wouldn't surprise me). Here are some of
the things I came up with:</font>
        </div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"> 
</div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
          <span style="COLOR: blue">member</span>
          <span style="COLOR: black"> x.All1
= <br />
   </span>
          <span style="COLOR: blue">let</span>
          <span style="COLOR: black"> until
f = Seq.generate (</span>
          <span style="COLOR: blue">fun</span>
          <span style="COLOR: black"> () </span>
          <span style="COLOR: blue">-&gt;</span>
          <span style="COLOR: black"> ref
x) f (</span>
          <span style="COLOR: blue">fun</span>
          <span style="COLOR: black"> _ </span>
          <span style="COLOR: blue">-&gt;</span>
          <span style="COLOR: black"> ())<br />
   until (</span>
          <span style="COLOR: blue">fun</span>
          <span style="COLOR: black"> cur </span>
          <span style="COLOR: blue">-&gt;</span>
          <span style="COLOR: black">
          </span>
          <span style="COLOR: blue">match</span>
          <span style="COLOR: black"> (!cur) </span>
          <span style="COLOR: blue">with</span>
          <span style="COLOR: black"> <br />
                        |
Stack(v, s) </span>
          <span style="COLOR: blue">-&gt;</span>
          <span style="COLOR: black"> cur
:= s<br />
                                        
Some v <br />
                        |
_ </span>
          <span style="COLOR: blue">-&gt;</span>
          <span style="COLOR: black"> None)</span>
        </div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"> 
</div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
          <font face="Verdana">Seq.generate
continues calling the function until None is returned, so this provides the loop termination.
Another similar approach:</font>
        </div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"> 
</div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
          <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
            <span style="COLOR: blue">member</span>
            <span style="COLOR: black"> x.All2
= 
<br />
      </span>
            <span style="COLOR: blue">let</span>
            <span style="COLOR: black"> until
f = Seq.generate (</span>
            <span style="COLOR: blue">fun</span>
            <span style="COLOR: black"> () </span>
            <span style="COLOR: blue">-&gt;</span>
            <span style="COLOR: black"> ref
x) f (</span>
            <span style="COLOR: blue">fun</span>
            <span style="COLOR: black"> _ </span>
            <span style="COLOR: blue">-&gt;</span>
            <span style="COLOR: black"> ())<br />
      until (</span>
            <span style="COLOR: blue">fun</span>
            <span style="COLOR: black"> cur </span>
            <span style="COLOR: blue">-&gt;</span>
            <span style="COLOR: black">
            </span>
            <span style="COLOR: blue">try</span>
            <span style="COLOR: black"> (!cur).Peek()<br />
                        </span>
            <span style="COLOR: blue">finally</span>
            <span style="COLOR: black">
            </span>
            <span style="COLOR: blue">if</span>
            <span style="COLOR: black"> not
(!cur).IsEmpty </span>
            <span style="COLOR: blue">then</span>
            <span style="COLOR: black"> cur
:= (!cur).Pop())</span>
          </div>
          <span style="COLOR: black">
          </span>
        </div>
        <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
          <span style="COLOR: black">
            <br />
            <font face="Verdana">Since Peek already returns 'a option, we can use it directly.
The problem is that we need to update cur to cur.Pop </font>
            <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
              <font face="Verdana">and then
return a value. The try/finally works, but the whole deal still doesn't seem very
elegant. Sequence expressions allow us to yield:</font>
            </div>
            <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"> 
</div>
            <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
              <span style="COLOR: blue">member</span>
              <span style="COLOR: black"> x.All3
=<br />
      </span>
              <span style="COLOR: blue">let</span>
              <span style="COLOR: black"> cur
= ref x<br />
      { </span>
              <span style="COLOR: blue">while</span>
              <span style="COLOR: black"> not
(!cur).IsEmpty </span>
              <span style="COLOR: blue">do<br /></span>
              <span style="COLOR: black">          </span>
              <span style="COLOR: blue">yield</span>
              <span style="COLOR: black"> (!cur).Peek()<br />
          </span>
              <span style="COLOR: blue">do</span>
              <span style="COLOR: black"> cur
:= (!cur).Pop() }<br />
      |&gt; Seq.choose(</span>
              <span style="COLOR: blue">fun</span>
              <span style="COLOR: black"> x </span>
              <span style="COLOR: blue">-&gt;</span>
              <span style="COLOR: black"> x)<br /></span>
            </div>
          </span>
        </div>
        <p>
          <span style="COLOR: black">I dislike this one. Because we're not doing the pattern
match ourselves, we end up yielding 'a option. But None is never valid because
we guard on IsEmpty. This makes us stick a Seq.choose on with an identity function
to strip off the Some. [Side note, is there no built-in identity function?] Bringing
the match into the seq fixes the issue, but the code is pretty long:</span>
        </p>
        <span style="COLOR: black">
          <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
            <span style="COLOR: blue">member</span>
            <span style="COLOR: black"> x.All4
=<br />
      </span>
            <span style="COLOR: blue">let</span>
            <span style="COLOR: black"> cur
= ref x<br />
      { </span>
            <span style="COLOR: blue">while</span>
            <span style="COLOR: black"> not
(!cur).IsEmpty </span>
            <span style="COLOR: blue">do<br /></span>
            <span style="COLOR: black">          </span>
            <span style="COLOR: blue">match</span>
            <span style="COLOR: black"> (!cur).Peek() </span>
            <span style="COLOR: blue">with</span>
            <span style="COLOR: black">
              <br />
                      |
None </span>
            <span style="COLOR: blue">-&gt;</span>
            <span style="COLOR: black">
            </span>
            <span style="COLOR: blue">do</span>
            <span style="COLOR: black"> ()<br />
                      |
Some v </span>
            <span style="COLOR: blue">-&gt;</span>
            <span style="COLOR: black">
            </span>
            <span style="COLOR: blue">do</span>
            <span style="COLOR: black"> cur
:= (!cur).Pop() 
<br />
                                  </span>
            <span style="COLOR: blue">yield</span>
            <span style="COLOR: black"> v
}<br /></span>
          </div>
          <p>
 I think what bothers me the most here is that the while and match are redundant.
The None case will never be matches because we guard on IsEmpty. Moving that into
a separate function gives:
</p>
          <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
            <span style="COLOR: blue">member</span>
            <span style="COLOR: black"> x.All5
=<br /></span>
            <span style="COLOR: black">      </span>
            <span style="COLOR: blue">let</span>
            <span style="COLOR: black"> v
= </span>
            <span style="COLOR: blue">function</span>
            <span style="COLOR: black"> Stack(vl,
_) </span>
            <span style="COLOR: blue">-&gt;</span>
            <span style="COLOR: black"> vl | _ </span>
            <span style="COLOR: blue">-&gt;</span>
            <span style="COLOR: black"> failwith </span>
            <span style="COLOR: #a31515">"dont
call on empty"<br /></span>
            <span style="COLOR: black">      <span style="COLOR: blue">let</span><span style="COLOR: black"> cur
= ref x<br /></span>      { </span>
            <span style="COLOR: blue">while</span>
            <span style="COLOR: black"> (!cur)
&lt;&gt; Empty </span>
            <span style="COLOR: blue">do<br /></span>
            <span style="COLOR: black">          </span>
            <span style="COLOR: blue">yield</span>
            <span style="COLOR: black"> v
(!cur)<br />
          </span>
            <span style="COLOR: blue">do</span>
            <span style="COLOR: black"> cur
:= (!cur).Pop() }<br /></span>
          </div>
          <p>
I prefer All5 to All4, but still think All1 or All2 are nicer. (Chris's original is
best as far as I can tell.) How else can this be done?<br /></p>
          <p>
            <em>Edit:</em> I lost sight of one of the principals of functional programming: Composition.
Here's a simple update to All5 that, IMHO, vastly improves it:
</p>
          <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white">
            <span style="COLOR: blue">member</span>
            <span style="COLOR: black"> x.All6
=<br />
      </span>
            <span style="COLOR: blue">let</span>
            <span style="COLOR: black"> cur
= ref x<br />
      </span>
            <span style="COLOR: blue">let</span>
            <span style="COLOR: black"> toVal
= </span>
            <span style="COLOR: blue">function</span>
            <span style="COLOR: black"> Stack(v,
_) </span>
            <span style="COLOR: blue">-&gt;</span>
            <span style="COLOR: black"> v | _ </span>
            <span style="COLOR: blue">-&gt;</span>
            <span style="COLOR: black"> failwith </span>
            <span style="COLOR: #a31515">"dont
call on empty"<br /></span>
            <span style="COLOR: black">      </span>
            <span style="COLOR: blue">let</span>
            <span style="COLOR: black"> next
() = </span>
            <span style="COLOR: blue">try</span>
            <span style="COLOR: black"> toVal
(!cur) </span>
            <span style="COLOR: blue">finally</span>
            <span style="COLOR: black"> cur
:= (!cur).Pop()<br />
      { </span>
            <span style="COLOR: blue">while</span>
            <span style="COLOR: black"> (!cur)
&lt;&gt; Empty </span>
            <span style="COLOR: blue">do</span>
            <span style="COLOR: black">
            </span>
            <span style="COLOR: blue">yield</span>
            <span style="COLOR: black"> next
() }</span>
          </div>
          <div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"> 
</div>
          <p>
          </p>
        </span>Every line builds up and you don't have to keep its details "active" in
your mind. This makes the sequence expression (which is the driver of the algorithm)
easy to verify. And again, to clarify, in a real system I'd probably use what Chris
suggested since it's the nicest syntax. The other versions are only seeing what it
looks like if we toss recursion and use a reference cell.
<img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=0a572828-5362-4d33-acf0-696d0ff30f4f" /></body>
      <title>Reference cells in F# sequences</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,0a572828-5362-4d33-acf0-696d0ff30f4f.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/08/16/Reference+Cells+In+F+Sequences.aspx</link>
      <pubDate>Sat, 16 Aug 2008 04:09:49 GMT</pubDate>
      <description>&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;font face=Verdana&gt;I
saw this stack implementation (&lt;/font&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/08/15/immutablestack-in-f.aspx"&gt;&lt;font face=Verdana&gt;http://blogs.msdn.com/jaredpar/archive/2008/08/15/immutablestack-in-f.aspx&lt;/font&gt;&lt;/a&gt;&lt;font face=Verdana&gt;)
and wanted to see how I'd approach it:&lt;/font&gt;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;#light&lt;br&gt;
&gt;&lt;span style="COLOR: blue"&gt;open&lt;/span&gt;&lt;span style="COLOR: black"&gt; System&lt;br&gt;
&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;type&lt;/span&gt;&lt;span style="COLOR: black"&gt; 'a ImmutableStack
= 
&lt;br&gt;
&amp;nbsp;&amp;nbsp; | Empty&lt;br&gt;
&amp;nbsp;&amp;nbsp; | Stack &lt;/span&gt;&lt;span style="COLOR: blue"&gt;of&lt;/span&gt;&lt;span style="COLOR: black"&gt; 'a
* 'a ImmutableStack&lt;br&gt;
&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;member&lt;/span&gt;&lt;span style="COLOR: black"&gt; x.Peek()
= &lt;/span&gt;&lt;span style="COLOR: blue"&gt;match&lt;/span&gt;&lt;span style="COLOR: black"&gt; x &lt;/span&gt;&lt;span style="COLOR: blue"&gt;with&lt;/span&gt;&lt;span style="COLOR: black"&gt; |
Stack (v, _) &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; Some
v | _ &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; None&lt;br&gt;
&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;member&lt;/span&gt;&lt;span style="COLOR: black"&gt; x.Pop()
= &lt;/span&gt;&lt;span style="COLOR: blue"&gt;match&lt;/span&gt;&lt;span style="COLOR: black"&gt; x &lt;/span&gt;&lt;span style="COLOR: blue"&gt;with&lt;/span&gt;&lt;span style="COLOR: black"&gt; |
Stack (_, s) &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; s
| _ &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; failwith &lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;"empty
stack"&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: black"&gt;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;member&lt;/span&gt;&lt;span style="COLOR: black"&gt; x.Push
a = Stack(a, x)&lt;br&gt;
&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;member&lt;/span&gt;&lt;span style="COLOR: black"&gt; x.IsEmpty
= x = Empty 
&lt;br&gt;
&lt;/span&gt;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;font face=Verdana&gt;(Well,
I'd probably just use a list in most cases.) But interestingly, he has an All function,
which returns a sequence of the entire stack. &lt;/font&gt;&lt;a href="http://blogs.msdn.com/chrsmith/default.aspx"&gt;&lt;font face=Verdana&gt;Chris&lt;/font&gt;&lt;/a&gt;&lt;font face=Verdana&gt; suggested
using sequence expressions and then recursively calling the function:&lt;/font&gt;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;span style="COLOR: blue"&gt;member&lt;/span&gt;&lt;span style="COLOR: black"&gt; x.All
=&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; match&lt;/span&gt;&lt;span style="COLOR: black"&gt; data &lt;/span&gt;&lt;span style="COLOR: blue"&gt;with&lt;/span&gt;&lt;span style="COLOR: black"&gt; 
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; | Empty &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; Seq.empty&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; | Value (v,n) &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; 
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;seq {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;yield&lt;/span&gt;&lt;span style="COLOR: black"&gt; v&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;yield!&lt;/span&gt;&lt;span style="COLOR: black"&gt; n.All
}&lt;br&gt;
&lt;/span&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;font face=Verdana&gt;This
is pretty nice as far as syntax goes. For some reason, I wanted to see how it'd look
without the recursion (which needs to generate a new enumerator, unless the compiler
is doing some wicked awesome stuff, which wouldn't surprise me). Here are some of
the things I came up with:&lt;/font&gt;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;span style="COLOR: blue"&gt;member&lt;/span&gt;&lt;span style="COLOR: black"&gt; x.All1
=&amp;nbsp;&lt;br&gt;
&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;let&lt;/span&gt;&lt;span style="COLOR: black"&gt; until
f = Seq.generate (&lt;/span&gt;&lt;span style="COLOR: blue"&gt;fun&lt;/span&gt;&lt;span style="COLOR: black"&gt; () &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; ref
x) f (&lt;/span&gt;&lt;span style="COLOR: blue"&gt;fun&lt;/span&gt;&lt;span style="COLOR: black"&gt; _ &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; ())&lt;br&gt;
&amp;nbsp;&amp;nbsp; until (&lt;/span&gt;&lt;span style="COLOR: blue"&gt;fun&lt;/span&gt;&lt;span style="COLOR: black"&gt; cur &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;match&lt;/span&gt;&lt;span style="COLOR: black"&gt; (!cur) &lt;/span&gt;&lt;span style="COLOR: blue"&gt;with&lt;/span&gt;&lt;span style="COLOR: black"&gt;&amp;nbsp;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;|
Stack(v, s) &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; cur
:= s&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
Some v&amp;nbsp;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;|
_ &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; None)&lt;/span&gt; 
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;font face=Verdana&gt;Seq.generate
continues calling the function until None is returned, so this provides the loop termination.
Another similar approach:&lt;/font&gt;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;span style="COLOR: blue"&gt;member&lt;/span&gt;&lt;span style="COLOR: black"&gt; x.All2
= 
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;let&lt;/span&gt;&lt;span style="COLOR: black"&gt; until
f = Seq.generate (&lt;/span&gt;&lt;span style="COLOR: blue"&gt;fun&lt;/span&gt;&lt;span style="COLOR: black"&gt; () &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; ref
x) f (&lt;/span&gt;&lt;span style="COLOR: blue"&gt;fun&lt;/span&gt;&lt;span style="COLOR: black"&gt; _ &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; ())&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;until (&lt;/span&gt;&lt;span style="COLOR: blue"&gt;fun&lt;/span&gt;&lt;span style="COLOR: black"&gt; cur &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;try&lt;/span&gt;&lt;span style="COLOR: black"&gt; (!cur).Peek()&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;finally&lt;/span&gt;&lt;span style="COLOR: black"&gt; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;if&lt;/span&gt;&lt;span style="COLOR: black"&gt; not
(!cur).IsEmpty &lt;/span&gt;&lt;span style="COLOR: blue"&gt;then&lt;/span&gt;&lt;span style="COLOR: black"&gt; cur
:= (!cur).Pop())&lt;/span&gt;
&lt;/div&gt;
&lt;span style="COLOR: black"&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;span style="COLOR: black"&gt;
&lt;br&gt;
&lt;font face=Verdana&gt;Since Peek already returns 'a option, we can use it directly. The
problem is that we need to update cur to cur.Pop &lt;/font&gt; 
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;font face=Verdana&gt;and&amp;nbsp;then
return a value. The try/finally works, but the whole deal still doesn't seem very
elegant. Sequence expressions allow us to yield:&lt;/font&gt;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&amp;nbsp;
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;span style="COLOR: blue"&gt;member&lt;/span&gt;&lt;span style="COLOR: black"&gt; x.All3
=&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;let&lt;/span&gt;&lt;span style="COLOR: black"&gt; cur
= ref x&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{ &lt;/span&gt;&lt;span style="COLOR: blue"&gt;while&lt;/span&gt;&lt;span style="COLOR: black"&gt; not
(!cur).IsEmpty &lt;/span&gt;&lt;span style="COLOR: blue"&gt;do&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: black"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;yield&lt;/span&gt;&lt;span style="COLOR: black"&gt; (!cur).Peek()&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;do&lt;/span&gt;&lt;span style="COLOR: black"&gt; cur
:= (!cur).Pop() }&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;|&amp;gt; Seq.choose(&lt;/span&gt;&lt;span style="COLOR: blue"&gt;fun&lt;/span&gt;&lt;span style="COLOR: black"&gt; x &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; x)&lt;br&gt;
&lt;/span&gt;
&lt;/div&gt;
&lt;/span&gt;
&lt;/div&gt;
&lt;p&gt;
&lt;span style="COLOR: black"&gt;I dislike this one. Because we're not doing the pattern
match ourselves, we end up yielding 'a option. But None is never valid&amp;nbsp;because
we guard on IsEmpty. This makes us stick a Seq.choose on with an identity function
to strip off the Some. [Side note, is there no built-in identity function?] Bringing
the match into the seq fixes the issue, but the code is pretty long:&lt;/span&gt;
&lt;/p&gt;
&lt;span style="COLOR: black"&gt; 
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;span style="COLOR: blue"&gt;member&lt;/span&gt;&lt;span style="COLOR: black"&gt; x.All4
=&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;let&lt;/span&gt;&lt;span style="COLOR: black"&gt; cur
= ref x&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{ &lt;/span&gt;&lt;span style="COLOR: blue"&gt;while&lt;/span&gt;&lt;span style="COLOR: black"&gt; not
(!cur).IsEmpty &lt;/span&gt;&lt;span style="COLOR: blue"&gt;do&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: black"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;match&lt;/span&gt;&lt;span style="COLOR: black"&gt; (!cur).Peek() &lt;/span&gt;&lt;span style="COLOR: blue"&gt;with&lt;/span&gt;&lt;span style="COLOR: black"&gt; 
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;|
None &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;do&lt;/span&gt;&lt;span style="COLOR: black"&gt; ()&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;|
Some v &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;do&lt;/span&gt;&lt;span style="COLOR: black"&gt; cur
:= (!cur).Pop() 
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;yield&lt;/span&gt;&lt;span style="COLOR: black"&gt; v
}&lt;br&gt;
&lt;/span&gt;
&lt;/div&gt;
&lt;p&gt;
&amp;nbsp;I think what bothers me the most here is that the while and match are redundant.
The None case will never be matches because we guard on IsEmpty. Moving that into
a separate function gives:
&lt;/p&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;span style="COLOR: blue"&gt;member&lt;/span&gt;&lt;span style="COLOR: black"&gt; x.All5
=&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: black"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;let&lt;/span&gt;&lt;span style="COLOR: black"&gt; v
= &lt;/span&gt;&lt;span style="COLOR: blue"&gt;function&lt;/span&gt;&lt;span style="COLOR: black"&gt; Stack(vl,
_) &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; vl | _ &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; failwith &lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;"dont
call on empty"&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: black"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;let&lt;/span&gt;&lt;span style="COLOR: black"&gt; cur
= ref x&lt;br&gt;
&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{ &lt;/span&gt;&lt;span style="COLOR: blue"&gt;while&lt;/span&gt;&lt;span style="COLOR: black"&gt; (!cur)
&amp;lt;&amp;gt; Empty &lt;/span&gt;&lt;span style="COLOR: blue"&gt;do&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: black"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;yield&lt;/span&gt;&lt;span style="COLOR: black"&gt; v
(!cur)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;do&lt;/span&gt;&lt;span style="COLOR: black"&gt; cur
:= (!cur).Pop() }&lt;br&gt;
&lt;/span&gt;
&lt;/div&gt;
&lt;p&gt;
I prefer All5 to All4, but still think All1 or All2 are nicer. (Chris's original is
best as far as I can tell.)&amp;nbsp;How else can this be done?&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;em&gt;Edit:&lt;/em&gt; I lost sight of one of the principals of functional programming: Composition.
Here's a simple update to All5 that, IMHO, vastly improves it:
&lt;/p&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&lt;span style="COLOR: blue"&gt;member&lt;/span&gt;&lt;span style="COLOR: black"&gt; x.All6
=&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;let&lt;/span&gt;&lt;span style="COLOR: black"&gt; cur
= ref x&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;let&lt;/span&gt;&lt;span style="COLOR: black"&gt; toVal
= &lt;/span&gt;&lt;span style="COLOR: blue"&gt;function&lt;/span&gt;&lt;span style="COLOR: black"&gt; Stack(v,
_) &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; v | _ &lt;/span&gt;&lt;span style="COLOR: blue"&gt;-&amp;gt;&lt;/span&gt;&lt;span style="COLOR: black"&gt; failwith &lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;"dont
call on empty"&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: black"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;let&lt;/span&gt;&lt;span style="COLOR: black"&gt; next
() = &lt;/span&gt;&lt;span style="COLOR: blue"&gt;try&lt;/span&gt;&lt;span style="COLOR: black"&gt; toVal
(!cur) &lt;/span&gt;&lt;span style="COLOR: blue"&gt;finally&lt;/span&gt;&lt;span style="COLOR: black"&gt; cur
:= (!cur).Pop()&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{ &lt;/span&gt;&lt;span style="COLOR: blue"&gt;while&lt;/span&gt;&lt;span style="COLOR: black"&gt; (!cur)
&amp;lt;&amp;gt; Empty &lt;/span&gt;&lt;span style="COLOR: blue"&gt;do&lt;/span&gt;&lt;span style="COLOR: black"&gt; &lt;/span&gt;&lt;span style="COLOR: blue"&gt;yield&lt;/span&gt;&lt;span style="COLOR: black"&gt; next
() }&lt;/span&gt; 
&lt;/div&gt;
&lt;div style="FONT-SIZE: 10pt; FONT-FAMILY: Monospace; BACKGROUND-COLOR: white"&gt;&amp;nbsp;
&lt;/div&gt;
&lt;p&gt;
&lt;/span&gt;Every line builds up and you don't have to keep its details "active" in your
mind. This makes the sequence expression (which is the driver of the algorithm) easy
to verify. And again, to clarify, in a real system I'd probably use what Chris suggested
since it's the nicest syntax. The other versions are only seeing what it looks like
if we toss recursion and use a reference cell.&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=0a572828-5362-4d33-acf0-696d0ff30f4f" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,0a572828-5362-4d33-acf0-696d0ff30f4f.aspx</comments>
      <category>Code</category>
      <category>FSharp</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=bbc4ba47-0413-4dcd-b33c-313943c66aad</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,bbc4ba47-0413-4dcd-b33c-313943c66aad.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,bbc4ba47-0413-4dcd-b33c-313943c66aad.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=bbc4ba47-0413-4dcd-b33c-313943c66aad</wfw:commentRss>
      <slash:comments>8</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I just read these two posts:<br /><a href="http://blogs.msdn.com/simonince/archive/2008/08/15/strongly-typed-primitives.aspx">http://blogs.msdn.com/simonince/archive/2008/08/15/strongly-typed-primitives.aspx</a><br /><a href="http://www.thejoyofcode.com/Avoiding_Primitive_Obsession_to_tip_developers_into_the_pit_of_success.aspx">http://www.thejoyofcode.com/Avoiding_Primitive_Obsession_to_tip_developers_into_the_pit_of_success.aspx</a></p>
        <p>
And that reminded me about something we recently did. One system we're working on
uses a lot of string identifiers for many different types of objects. There are many,
many of these stored and passed around, so keeping things efficient was of high concern. <br /><br />
The downside of string IDs (really, using any common type as an ID) is that it's legal
to pass any primitive of the same type. Strings and integers abound, both
as IDs of other classes, as well as general use. So it's not unimaginable that someone
could pass the wrong parameter some where. This could lead to runtime crashes
or unexpected results (if the ID is actually a real record of another class of object). Finally,
using common types for IDs reduces usability. The signature "public void Delete(int
id)" leaves a lot to be desired.
</p>
        <p>
We wanted to hit all these issues, in addition to keeping things simple. There are
times when untyped data needs to be converted, and this should be easy and clear.
We wanted to avoid having to define new types when we had new classes of objects to
identify It is also customer-visible code, so C# is used.<br /><br />
Using a reference type was unacceptable, because it'd add at least 12 bytes overhead
(I think more on x64). Using a struct fixes this, in addition to dealing with silly
nullability issues. [If a type can be null, it should always be explicit. C#'s "references
types can be null" makes this hard.] 
</p>
        <p>
The end result was quite simple. Wrap a string in a structure so equality and hashing
pass through. But, take advantage and remove case/cultural sensitivity (since in many
systems, data IDs are not case sensitive). Provide explicit conversions so you
can easily convert to and from strings, but never by accident. (If the conversions
were implicit, you're back in the starting point.) Finally, add a generic
parameter that is never used. The generic parameter gives you distinct types without
having to define them. Now the APIs can look like:<br /><br />
    public void Delete(Id&lt;Product&gt; id)...<br /><br />
    Dictionary&lt;Id&lt;Group&gt;, List&lt;Id&lt;User&gt;&gt;&gt; members...<br /><br />
When you do have hardcoded IDs, as the blog entries I mentioned do, you can convert
easily: (Id&lt;User&gt;)"Admin". Nulls are treated as empty, all the time (empty may
be a valid value anyways). 
</p>
        <p>
When a truly optional ID is needed, use nullable types: "Id&lt;Whatever&gt;?". This fully
captures how values are handled. This is vastly better than "It's a reference
type, so maybe null is allowed. Or maybe null will crash. Empty string might
be considered null, or maybe empty string means optional." With explicit nullability,
the type system says it all.<br /><br />
The best part is that there should be pretty much no overhead. I'd expect the equality
functions to be inlined, and there's no memory overhead, since the struct is simply
a string reference.<br /></p>
        <br />
Here's the class.:<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">struct</span> Id&lt;T&gt;
: IEquatable&lt;Id&lt;T&gt;&gt; { <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">public</span> Id(<span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">string</span> name)
{ <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">this</span>.name <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> name
?? <span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">""</span>;
} <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">readonly</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">string</span> name; <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">explicit</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">operator</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">string</span>(Id&lt;T&gt;
x) { <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">return</span> x.name
?? <span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">""</span>;
} <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">explicit</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">operator</span> Id&lt;T&gt;(<span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">string</span> s)
{ <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">new</span> Id&lt;T&gt;(s);
} <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">override</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">bool</span> Equals(<span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">object</span> obj)
{ <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">return</span> !(obj <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">is</span> Id&lt;T&gt;)
? <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">false</span> :
((Id&lt;T&gt;)obj) == <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">this</span>;
} <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">bool</span> Equals(Id&lt;T&gt;
other) { <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">return</span> other
== <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">this</span>;
} <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">override</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">int</span> GetHashCode()
{ <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">return</span> (name
?? <span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">""</span>).GetHashCode();
} <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">override</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">string</span> ToString()
{ <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">return</span> name
?? <span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">""</span>;
} <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">bool</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">operator</span> ==(Id&lt;T&gt;
a, Id&lt;T&gt; b) { <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">return</span> StringComparer.InvariantCultureIgnoreCase.Compare(a.name,
b.name) == 0; } <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">bool</span><span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">operator</span> !<span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span>(Id&lt;T&gt;
a, Id&lt;T&gt; b) { <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">return</span> !(a
== b); } }</span><span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"></span></pre>I'd
be interested in seeing a more generic, yet very simple, solution: one that doesn't
rely on the underlying type to be string, but still provides all the same functionality.
I don't think it's possible, since there's no way to get a generic constraint that'd
allow similar handling of "string" and "int?". Additionally, structs can't inherit,
so you'd end up using "Id&lt;string, Product&gt;" everywhere, which is far from elegant.<img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=bbc4ba47-0413-4dcd-b33c-313943c66aad" /></body>
      <title>Typing string IDs</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,bbc4ba47-0413-4dcd-b33c-313943c66aad.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/08/15/Typing+String+IDs.aspx</link>
      <pubDate>Fri, 15 Aug 2008 19:39:11 GMT</pubDate>
      <description>&lt;p&gt;
I just read these two posts:&lt;br&gt;
&lt;a href="http://blogs.msdn.com/simonince/archive/2008/08/15/strongly-typed-primitives.aspx"&gt;http://blogs.msdn.com/simonince/archive/2008/08/15/strongly-typed-primitives.aspx&lt;/a&gt;
&lt;br&gt;
&lt;a href="http://www.thejoyofcode.com/Avoiding_Primitive_Obsession_to_tip_developers_into_the_pit_of_success.aspx"&gt;http://www.thejoyofcode.com/Avoiding_Primitive_Obsession_to_tip_developers_into_the_pit_of_success.aspx&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
And that reminded me about something we recently did. One system we're working on
uses a lot of string identifiers for many different types of objects. There are many,
many of these stored and passed around, so keeping things efficient was of high concern.&amp;nbsp;&lt;br&gt;
&lt;br&gt;
The downside of string IDs (really, using any common type as an ID) is that it's legal
to pass&amp;nbsp;any primitive of the same type.&amp;nbsp;Strings and integers abound, both
as IDs of other classes, as well as general use. So it's not unimaginable that someone
could pass the&amp;nbsp;wrong parameter some where.&amp;nbsp;This could lead to runtime crashes
or unexpected results (if the ID is actually a real record of another class of object).&amp;nbsp;Finally,
using common types for IDs reduces usability. The signature "public void Delete(int
id)" leaves a lot to be desired.
&lt;/p&gt;
&lt;p&gt;
We wanted to hit all these issues, in addition to keeping things simple. There are
times when untyped data needs to be converted, and this should be easy and clear.
We wanted to avoid having to define new types when we had new classes of objects to
identify It is&amp;nbsp;also&amp;nbsp;customer-visible code, so C# is used.&lt;br&gt;
&lt;br&gt;
Using a reference type was unacceptable, because it'd add at least 12 bytes overhead
(I think more on x64). Using a struct fixes this, in addition to dealing with silly
nullability issues. [If a type can be null, it should always be explicit. C#'s "references
types can be null" makes this hard.] 
&lt;/p&gt;
&lt;p&gt;
The end result was quite simple. Wrap a string in a structure so equality and hashing
pass through. But, take advantage and remove case/cultural sensitivity (since in many
systems, data IDs are not case sensitive).&amp;nbsp;Provide explicit conversions so you
can easily convert to and from strings, but never by accident. (If&amp;nbsp;the conversions
were implicit, you're back&amp;nbsp;in the&amp;nbsp;starting point.)&amp;nbsp;Finally, add a generic
parameter that is never used. The generic parameter gives you distinct types without
having to define them. Now the APIs can look like:&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; public void Delete(Id&amp;lt;Product&amp;gt; id)...&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Dictionary&amp;lt;Id&amp;lt;Group&amp;gt;, List&amp;lt;Id&amp;lt;User&amp;gt;&amp;gt;&amp;gt; members...&lt;br&gt;
&lt;br&gt;
When you do have hardcoded IDs, as the blog entries I mentioned do, you can convert
easily: (Id&amp;lt;User&amp;gt;)"Admin". Nulls are treated as empty, all the time (empty may
be a valid value anyways). 
&lt;/p&gt;
&lt;p&gt;
When a truly optional ID is needed, use nullable types: "Id&amp;lt;Whatever&amp;gt;?". This&amp;nbsp;fully
captures how values are handled. This is vastly better than&amp;nbsp;"It's a reference
type, so maybe null is&amp;nbsp;allowed. Or maybe null will crash. Empty string might
be considered null, or maybe empty string means optional." With explicit nullability,
the type system says it all.&lt;br&gt;
&lt;br&gt;
The best part is that there should be pretty much no overhead. I'd expect the equality
functions to be inlined, and there's no memory overhead, since the struct is simply
a string reference.&lt;br&gt;
&lt;/p&gt;
&lt;br&gt;
Here's the class.:&lt;pre&gt;&lt;span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;public&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;struct&lt;/span&gt; Id&amp;lt;T&amp;gt;
: IEquatable&amp;lt;Id&amp;lt;T&amp;gt;&amp;gt; { &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;public&lt;/span&gt; Id(&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;string&lt;/span&gt; name)
{ &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;this&lt;/span&gt;.name &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; name
?? &lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;""&lt;/span&gt;;
} &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;readonly&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;string&lt;/span&gt; name; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;public&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;static&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;explicit&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;operator&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;string&lt;/span&gt;(Id&amp;lt;T&amp;gt;
x) { &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; x.name
?? &lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;""&lt;/span&gt;;
} &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;public&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;static&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;explicit&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;operator&lt;/span&gt; Id&amp;lt;T&amp;gt;(&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;string&lt;/span&gt; s)
{ &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;new&lt;/span&gt; Id&amp;lt;T&amp;gt;(s);
} &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;public&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;override&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;bool&lt;/span&gt; Equals(&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;object&lt;/span&gt; obj)
{ &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; !(obj &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;is&lt;/span&gt; Id&amp;lt;T&amp;gt;)
? &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;false&lt;/span&gt; :
((Id&amp;lt;T&amp;gt;)obj) == &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;this&lt;/span&gt;;
} &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;public&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;bool&lt;/span&gt; Equals(Id&amp;lt;T&amp;gt;
other) { &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; other
== &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;this&lt;/span&gt;;
} &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;public&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;override&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;int&lt;/span&gt; GetHashCode()
{ &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; (name
?? &lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;""&lt;/span&gt;).GetHashCode();
} &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;public&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;override&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;string&lt;/span&gt; ToString()
{ &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; name
?? &lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;""&lt;/span&gt;;
} &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;public&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;static&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;bool&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;operator&lt;/span&gt; ==(Id&amp;lt;T&amp;gt;
a, Id&amp;lt;T&amp;gt; b) { &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; StringComparer.InvariantCultureIgnoreCase.Compare(a.name,
b.name) == 0; } &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;public&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;static&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;bool&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;operator&lt;/span&gt; !&lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt;(Id&amp;lt;T&amp;gt;
a, Id&amp;lt;T&amp;gt; b) { &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; !(a
== b); } }&lt;/span&gt;&lt;span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt; &lt;/span&gt;&lt;/pre&gt;I'd
be interested in seeing a more generic, yet very simple, solution: one that doesn't
rely on the underlying type to be string, but still provides all the same functionality.
I don't think it's possible, since there's no way to get a generic constraint that'd
allow similar handling of "string" and "int?". Additionally, structs can't inherit,
so you'd end up using "Id&amp;lt;string, Product&amp;gt;" everywhere, which is far from elegant.&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=bbc4ba47-0413-4dcd-b33c-313943c66aad" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,bbc4ba47-0413-4dcd-b33c-313943c66aad.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=ae23e7f3-a43e-4bc5-90cc-12b2b74dff99</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,ae23e7f3-a43e-4bc5-90cc-12b2b74dff99.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,ae23e7f3-a43e-4bc5-90cc-12b2b74dff99.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=ae23e7f3-a43e-4bc5-90cc-12b2b74dff99</wfw:commentRss>
      <body 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" />
      </body>
      <title>I underestimated the power of query comprehensions</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,ae23e7f3-a43e-4bc5-90cc-12b2b74dff99.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/06/26/I+Underestimated+The+Power+Of+Query+Comprehensions.aspx</link>
      <pubDate>Thu, 26 Jun 2008 06:15:10 GMT</pubDate>
      <description>&lt;p&gt;
In my &lt;a href="http://www.atrevido.net/blog/2008/06/26/LINQ+To+The+CRUD+CreateTable+Generator+In+F.aspx"&gt;last
post&lt;/a&gt;, 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...
&lt;/p&gt;
&lt;p&gt;
...But... C# still can't do discriminated unions efficiently or effectively ;). 
&lt;/p&gt;
&lt;p&gt;
&lt;hr&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;div style="FONT-SIZE: 11pt; BACKGROUND: white; COLOR: black; FONT-FAMILY: Consolas"&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;1&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: green"&gt;//
crudcreatecompare.cs: Generates LINQ CRUD table fields using the horribly named DatabaseBase
code&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;2&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: green"&gt;//&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;3&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: green"&gt;//
Tables look like: [Table(Name="dbo.Accounts")]&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;4&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: green"&gt;//
Columns look like this:&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;5&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: green"&gt;//&amp;nbsp;
[Column(Storage="_AccountName", DbType="VarChar(128) NOT NULL", CanBeNull=false, IsPrimaryKey=true)]&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;6&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: green"&gt;//&amp;nbsp;
[DataMember(Order=1)] // Exists if serialization is turned on; used to order key parameters&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;7&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: green"&gt;//
Emits:&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;8&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: green"&gt;//&amp;nbsp;
public static readonly TableHelper&amp;lt;Account, String&amp;gt; Accounts =&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;9&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: green"&gt;//&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp; CreateTable(dc =&amp;gt; dc.Accounts, a =&amp;gt; a.AccountName);&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;10&lt;/span&gt;&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;11&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: blue"&gt;using&lt;/span&gt; System;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;12&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: blue"&gt;using&lt;/span&gt; System.Collections.Generic;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;13&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: blue"&gt;using&lt;/span&gt; System.Data.Linq.Mapping;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;14&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: blue"&gt;using&lt;/span&gt; System.IO;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;15&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: blue"&gt;using&lt;/span&gt; System.Linq;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;16&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: blue"&gt;using&lt;/span&gt; System.Reflection;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;17&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: blue"&gt;using&lt;/span&gt; System.Runtime.Serialization;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;18&lt;/span&gt;&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;19&lt;/span&gt;&amp;nbsp;&lt;span style="COLOR: blue"&gt;class&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Program&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;20&lt;/span&gt;&amp;nbsp;{
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;21&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;void&lt;/span&gt; Main()
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;22&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;23&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;24&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Program&lt;/span&gt;().generate(
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;25&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: #a31515"&gt;"C:\\yourlinq.dll"&lt;/span&gt;));
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;26&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;27&lt;/span&gt;&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;28&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;string&lt;/span&gt; generate(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt; asmpath)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;29&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;30&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;var&lt;/span&gt; asm
= &lt;span style="COLOR: #2b91af"&gt;Assembly&lt;/span&gt;.LoadFrom(asmpath);
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;31&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;var&lt;/span&gt; lines
= &lt;span style="COLOR: blue"&gt;from&lt;/span&gt; t &lt;span style="COLOR: blue"&gt;in&lt;/span&gt; asm.GetExportedTypes()
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;32&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; ta
= getAttr&amp;lt;&lt;span style="COLOR: #2b91af"&gt;TableAttribute&lt;/span&gt;&amp;gt;(t)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;33&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;where&lt;/span&gt; ta
!= &lt;span style="COLOR: blue"&gt;null&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;34&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; name
= pluralize(ta.Name.Replace(&lt;span style="COLOR: #a31515"&gt;"dbo."&lt;/span&gt;, &lt;span style="COLOR: #a31515"&gt;""&lt;/span&gt;))
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;35&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;orderby&lt;/span&gt; name
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;36&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;select&lt;/span&gt; genTable(t,
name);
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;37&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;return&lt;/span&gt; joinStrings(&lt;span style="COLOR: #a31515"&gt;""&lt;/span&gt;,
lines);
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;38&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;39&lt;/span&gt;&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;40&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;string&lt;/span&gt; genTable(&lt;span style="COLOR: #2b91af"&gt;Type&lt;/span&gt; t, &lt;span style="COLOR: blue"&gt;string&lt;/span&gt; tableName)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;41&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;42&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;var&lt;/span&gt; keyProps
=
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;43&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;from&lt;/span&gt; p &lt;span style="COLOR: blue"&gt;in&lt;/span&gt; t.GetProperties()
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;44&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; c = getAttr&amp;lt;&lt;span style="COLOR: #2b91af"&gt;ColumnAttribute&lt;/span&gt;&amp;gt;(p)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;45&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;where&lt;/span&gt; c != &lt;span style="COLOR: blue"&gt;null&lt;/span&gt; &amp;amp;&amp;amp;
c.IsPrimaryKey
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;46&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;let&lt;/span&gt; dm = getAttr&amp;lt;&lt;span style="COLOR: #2b91af"&gt;DataMemberAttribute&lt;/span&gt;&amp;gt;(p)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;47&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;orderby&lt;/span&gt; dm == &lt;span style="COLOR: blue"&gt;null&lt;/span&gt; ?
0 : dm.Order
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;48&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;select&lt;/span&gt; p;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;49&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;var&lt;/span&gt; tw
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;StringWriter&lt;/span&gt;();
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;50&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
tw.WriteLine(&lt;span style="COLOR: #a31515"&gt;"public static readonly TableHelper&amp;lt;{0},
{1}&amp;gt; {2} ="&lt;/span&gt;,
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;51&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; t.Name,
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;52&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; joinStrings(&lt;span style="COLOR: #a31515"&gt;", "&lt;/span&gt;, keyProps.Select(p
=&amp;gt; p.PropertyType.Name)),
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;53&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; tableName);
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;54&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
tw.WriteLine(&lt;span style="COLOR: #a31515"&gt;"\tCreateTable(dc =&amp;gt; dc.{0}, {1});"&lt;/span&gt;,
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;55&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; tableName,
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;56&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;&amp;nbsp;&amp;nbsp; joinStrings(&lt;span style="COLOR: #a31515"&gt;", "&lt;/span&gt;, keyProps.Select(p
=&amp;gt; &lt;span style="COLOR: #a31515"&gt;"a =&amp;gt; a."&lt;/span&gt; + p.Name)));
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;57&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;
tw.WriteLine();
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;58&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;return&lt;/span&gt; tw.ToString();
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;59&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;60&lt;/span&gt;&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;61&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;string&lt;/span&gt; joinStrings(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt; sep, &lt;span style="COLOR: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="COLOR: blue"&gt;string&lt;/span&gt;&amp;gt;
items)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;62&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;63&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;return&lt;/span&gt; &lt;span style="COLOR: blue"&gt;string&lt;/span&gt;.Join(sep,
items.ToArray());
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;64&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;65&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;string&lt;/span&gt; pluralize(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt; s)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;66&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;67&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;return&lt;/span&gt; s.EndsWith(&lt;span style="COLOR: #a31515"&gt;"s"&lt;/span&gt;)
? s : s + &lt;span style="COLOR: #a31515"&gt;"s"&lt;/span&gt;;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;68&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;69&lt;/span&gt;&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;70&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; T
getAttr&amp;lt;T&amp;gt;(&lt;span style="COLOR: #2b91af"&gt;ICustomAttributeProvider&lt;/span&gt; icap)
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;71&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;72&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;var&lt;/span&gt; a
= icap.GetCustomAttributes(&lt;span style="COLOR: blue"&gt;typeof&lt;/span&gt;(T), &lt;span style="COLOR: blue"&gt;true&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;73&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;return&lt;/span&gt; a.Length
== 0 ? &lt;span style="COLOR: blue"&gt;default&lt;/span&gt;(T) : (T)a[0];
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;74&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;75&lt;/span&gt;&amp;nbsp;}
&lt;/p&gt;
&lt;/div&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=ae23e7f3-a43e-4bc5-90cc-12b2b74dff99" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,ae23e7f3-a43e-4bc5-90cc-12b2b74dff99.aspx</comments>
      <category>Code</category>
      <category>FSharp</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=1613baf7-ed7e-4ecc-bd10-4106ea3c88bc</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,1613baf7-ed7e-4ecc-bd10-4106ea3c88bc.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,1613baf7-ed7e-4ecc-bd10-4106ea3c88bc.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=1613baf7-ed7e-4ecc-bd10-4106ea3c88bc</wfw:commentRss>
      <slash:comments>8</slash:comments>
      <body 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" />
      </body>
      <title>The reason VB.NET is truly a second class citizen</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,1613baf7-ed7e-4ecc-bd10-4106ea3c88bc.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/03/31/The+Reason+VBNET+Is+Truly+A+Second+Class+Citizen.aspx</link>
      <pubDate>Mon, 31 Mar 2008 21:55:56 GMT</pubDate>
      <description>&lt;p&gt;
No support for anonymous methods/lambda statements.&amp;nbsp;I first realised this when
someone commented on one of my &lt;a href="http://www.atrevido.net/blog/2007/08/26/A+LINQ+To+The+CRUD.aspx"&gt;functional
C#&lt;/a&gt; postings, asking "how can I write this in VB"? Turns out VB has no support
for anonymous methods. &lt;a href="http://www.paulstovell.com/blog/vbnet-wheres-actiont-support"&gt;Ouch.&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
Really, dropping anonymous methods in favour of stuff like XML literals? Maybe that's
why it's listed as &lt;a href="http://msmvps.com/blogs/bill/archive/2008/03/23/first-time-or-casual-programming.aspx"&gt;first
time or casual programming&lt;/a&gt;&amp;nbsp;;). (No, I jest. Scheme is far better for first
time programming.)
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=1613baf7-ed7e-4ecc-bd10-4106ea3c88bc" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,1613baf7-ed7e-4ecc-bd10-4106ea3c88bc.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=ddab93db-ef59-4084-ba60-aa7dba01412e</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,ddab93db-ef59-4084-ba60-aa7dba01412e.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,ddab93db-ef59-4084-ba60-aa7dba01412e.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=ddab93db-ef59-4084-ba60-aa7dba01412e</wfw:commentRss>
      <slash:comments>5</slash:comments>
      <body 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" />
      </body>
      <title>Empty WCF services references - no code generated</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,ddab93db-ef59-4084-ba60-aa7dba01412e.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/03/31/Empty+WCF+Services+References+No+Code+Generated.aspx</link>
      <pubDate>Mon, 31 Mar 2008 09:06:51 GMT</pubDate>
      <description>&lt;p&gt;
Usually I use WCF just by referencing the contracts directly and using my own &lt;a href="http://www.atrevido.net/blog/2007/08/13/Practical+Functional+C+Part+II.aspx"&gt;generic
helper methods&lt;/a&gt;. 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. 
&lt;/p&gt;
&lt;p&gt;
Things were working just fine until I added a reference to a new service. Adding the
service reference didn't&amp;nbsp;work; it failed silently. It added all the schema files&amp;nbsp;to
the project, but the Reference.cs file was empty.&amp;nbsp;If I told it to NOT used&amp;nbsp;referenced
assemblies, then it generated everything just fine.
&lt;/p&gt;
&lt;p&gt;
After switching to the command line and using svcutil, I got these errors:&lt;br&gt;
&lt;font face="Courier New"&gt;Error: Cannot import wsdl:portType&lt;br&gt;
Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter&lt;br&gt;
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']&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
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.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=ddab93db-ef59-4084-ba60-aa7dba01412e" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,ddab93db-ef59-4084-ba60-aa7dba01412e.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=ffa70c25-0c78-474b-8d60-10a693ffc407</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,ffa70c25-0c78-474b-8d60-10a693ffc407.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,ffa70c25-0c78-474b-8d60-10a693ffc407.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=ffa70c25-0c78-474b-8d60-10a693ffc407</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body 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" />
      </body>
      <title>Hacking SOAP Faults into Silverlight 2 Beta 1</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,ffa70c25-0c78-474b-8d60-10a693ffc407.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/03/27/Hacking+SOAP+Faults+Into+Silverlight+2+Beta+1.aspx</link>
      <pubDate>Thu, 27 Mar 2008 07:19:36 GMT</pubDate>
      <description>&lt;p&gt;
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.
&lt;/p&gt;
&lt;p&gt;
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.]
&lt;/p&gt;
&lt;p&gt;
Some progress. Silverlight now gives a more useful exception:
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;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/'&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
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.
&lt;/p&gt;
&lt;p&gt;
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.
&lt;/p&gt;
&lt;p&gt;
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&amp;nbsp;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:
&lt;/p&gt;
&lt;p&gt;
&lt;font size=3&gt;&lt;span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;public&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;void&lt;/span&gt; ProvideFault(Exception
error, MessageVersion version, &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;ref&lt;/span&gt; Message
fault)&lt;br&gt;
{&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;//
HackFaults store the exception in the httpcontext&lt;/span&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; var context &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; System.Web.HttpContext.Current;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;if&lt;/span&gt; (context
!&lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;null&lt;/span&gt;)
{ 
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;//
Only works in AspNetCompat mode&lt;/span&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;if&lt;/span&gt; (!context.Request.Browser.Crawler
&amp;amp;&amp;amp; context.Request.Browser.EcmaScriptVersion.Major &amp;gt; 0) {&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;//
This should rule out non-browsers&lt;/span&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; context.Items.Add(&lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;"HackFault"&lt;/span&gt;,
error);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;
}&lt;br&gt;
&lt;/span&gt;
&lt;/p&gt;
&gt; 
&lt;p&gt;
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:
&lt;/p&gt;
&lt;pre&gt;&lt;span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;protected&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;void&lt;/span&gt; Application_EndRequest(&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;object&lt;/span&gt; sender,
EventArgs e) { &lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;//
In all fairness, I was drinking eiswein at the time&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;if&lt;/span&gt; (Context.Items.Contains(&lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;"HackFault"&lt;/span&gt;))
{ Context.Response.ContentType &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;"text/xml"&lt;/span&gt;;
Context.Response.StatusCode &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; 200;
Context.Response.ClearContent(); var hackEx &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; Context.Items[&lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;"HackFault"&lt;/span&gt;] &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;as&lt;/span&gt; Exception;
var hackFaultXml &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;string&lt;/span&gt;.Format( &lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;"&amp;lt;s:Envelope
xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"&amp;gt;&amp;lt;s:Body&amp;gt;&amp;lt;{0} xmlns=\"{1}\"
/&amp;gt;&amp;lt;/s:Body&amp;gt;&amp;lt;/s:Envelope&amp;gt;"&lt;/span&gt;, hackEx.GetType().ToString(), Context.Server.HtmlEncode(hackEx.Message));
Context.Response.Output.Write(hackFaultXml); } } &lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
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.&amp;nbsp;The&amp;nbsp;SL-side parsing
code is vile but easy:
&lt;/p&gt;
&lt;pre&gt;&lt;span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;public&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;static&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;string&lt;/span&gt; ExtractHackFaultMessage(&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;this&lt;/span&gt; Exception
ex) { &lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;//
HackFaults generate these Exceptions and messages:&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;//Without
debug:&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;//Could
not connect to server: System.Runtime.Serialization.SerializationException: [SFxInvalidMessageBody]&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;//Arguments:FaultException,Something
silly&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;//With
debug:&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;//Could
not connect to server: System.Runtime.Serialization.SerializationException: 
&lt;br&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;&lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;OperationFormatter
encountered an invalid Message body. Expected to find node type 'Element' with 
&lt;br&gt;
name 'SomeOperationResponse' and namespace 'http://schemas.cool.com/yea/v2/00'. 
&lt;br&gt;
Found node type 'Element' with name 'FaultException' and namespace 'Something silly'&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;if&lt;/span&gt; (!(ex &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;is&lt;/span&gt; System.Runtime.Serialization.SerializationException)) &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;null&lt;/span&gt;;
var msg &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; ex.Message; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;string&lt;/span&gt; regexp; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;if&lt;/span&gt; (msg.Contains(&lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;"[SFxInvalidMessageBody]"&lt;/span&gt;))
{ regexp &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;@"Arguments:(.*),(.*)"&lt;/span&gt;;
} &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;else&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;if&lt;/span&gt; (msg.Contains(&lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;"OperationFormatter
encountered an invalid Message body"&lt;/span&gt;)) { regexp &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;@"Found
node type 'Element' with name '(.*)' and namespace '(.*)'"&lt;/span&gt;; } &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;else&lt;/span&gt; { &lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;//
Nope, it's some thing else&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;null&lt;/span&gt;;
} var match &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; System.Text.RegularExpressions.Regex.Match(msg,
regexp); &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;if&lt;/span&gt; (match.Groups.Count
!&lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; 3) &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;null&lt;/span&gt;; &lt;span style="FONT-SIZE: 11px; COLOR: green; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;//
Not expected&lt;/span&gt; var exType &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; match.Groups[1].Value.Trim();
var exMsg &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; match.Groups[2].Value.Trim(); &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;if&lt;/span&gt; (exType
== &lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;"System.ServiceModel.FaultException"&lt;/span&gt;) &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; exMsg; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;else&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;return&lt;/span&gt; exType+ &lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;":
"&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;+&lt;/span&gt; exMsg;
}&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
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&amp;nbsp;like this: "Error: " + (ex.ExtractHackFaultMessage() ?? ex.ToString())
&lt;/p&gt;
&lt;p&gt;
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?).
&lt;/p&gt;
&lt;a href="http://www.atrevido.net/blog/content/binary/HttpErrorHandler.cs.txt"&gt;HttpErrorHandler.cs.txt
(2.49 KB)&lt;/a&gt;&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=ffa70c25-0c78-474b-8d60-10a693ffc407" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,ffa70c25-0c78-474b-8d60-10a693ffc407.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=1b0c68ce-d168-4210-86fb-4f2b2126bfc0</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,1b0c68ce-d168-4210-86fb-4f2b2126bfc0.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,1b0c68ce-d168-4210-86fb-4f2b2126bfc0.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=1b0c68ce-d168-4210-86fb-4f2b2126bfc0</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body 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>
ETW is a real pain to use with .NET. 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" />
      </body>
      <title>Writing events with System.Diagnostics.Eventing </title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,1b0c68ce-d168-4210-86fb-4f2b2126bfc0.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/02/28/Writing+Events+With+SystemDiagnosticsEventing.aspx</link>
      <pubDate>Thu, 28 Feb 2008 21:12:25 GMT</pubDate>
      <description>&lt;p&gt;
... 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.&lt;br&gt;
&lt;br&gt;
&lt;strong&gt;Quick ETW Overview&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Actually, the real ETW overview is here:&amp;nbsp;&lt;a href="http://msdn.microsoft.com/msdnmag/issues/07/04/ETW/"&gt;http://msdn.microsoft.com/msdnmag/issues/07/04/ETW/&lt;/a&gt;&amp;nbsp;&amp;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.
&lt;/p&gt;
&lt;p&gt;
ETW is a real pain to use with .NET.&amp;nbsp;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.&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
It worsens:&amp;nbsp;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. 
&lt;/p&gt;
&lt;p&gt;
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.&amp;nbsp;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&amp;nbsp;just stay in the XML file and be read from there.&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
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.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;ECManGen&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
But wait, how do I actually make that manifest?&amp;nbsp;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. 
&lt;/p&gt;
&lt;p&gt;
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.
&lt;/p&gt;
&lt;p&gt;
*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.
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
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
:).
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Going Managed&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
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). 
&lt;/p&gt;
&lt;p&gt;
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.&amp;nbsp;And also,
the .NET API won't even handle the Boolean-&amp;gt;BOOL (4 byte) silliness for you.&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
In summary, it's a lot of boring, error-prone&amp;nbsp;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.
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Using ecmanaged&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New"&gt;Usage: ecmanaged ecgen &amp;lt;manifest&amp;gt; /out:&amp;lt;target assembly&amp;gt;
/namespace:&amp;lt;target namespace&amp;gt; /class:&amp;lt;target class&amp;gt;&lt;br&gt;
Usage: ecmanaged msglocate &amp;lt;manifest&amp;gt; &amp;lt;messageFileName&amp;gt;&lt;br&gt;
Usage: ecmanaged install &amp;lt;manifest&amp;gt; &amp;lt;targetManifest&amp;gt; &amp;lt;messageFileName&amp;gt;&lt;br&gt;
Usage: ecmanaged uninstall &amp;lt;targetManifest&amp;gt;&lt;/font&gt;
&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
Call msglocate with the manifest and the message binary file, and it'll go fix the
manifest to point to the right place.
&lt;/p&gt;
&lt;p&gt;
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.
&lt;/p&gt;
&lt;p&gt;
Uninstall just calls wevutil uninstall-manifest.
&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;
&lt;font size=3&gt;&lt;font size=2&gt;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.&lt;/font&gt;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;font size=3&gt;&lt;font size=2&gt;I welcome all comments/questions/insults, but please, no&amp;nbsp;death
threats.&amp;nbsp;Download: &lt;a href="http://www.atrevido.net/blog/content/binary/ecmanaged.exe"&gt;ecmanaged.exe
(45 KB)&lt;/a&gt;&lt;/font&gt;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;font size=3&gt;&lt;font size=2&gt;P.S. No, I don't hate Windows or the devs on it, although
I hate unmanaged code (it IS 2008, innit?).&amp;nbsp;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.&lt;/font&gt;&lt;/font&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=1b0c68ce-d168-4210-86fb-4f2b2126bfc0" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,1b0c68ce-d168-4210-86fb-4f2b2126bfc0.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=f9e4d1ef-8fff-4f44-8d9f-248bfc498e60</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,f9e4d1ef-8fff-4f44-8d9f-248bfc498e60.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,f9e4d1ef-8fff-4f44-8d9f-248bfc498e60.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=f9e4d1ef-8fff-4f44-8d9f-248bfc498e60</wfw:commentRss>
      <slash:comments>4</slash:comments>
      <body 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" />
      </body>
      <title>Complicated functions in LINQ to SQL</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,f9e4d1ef-8fff-4f44-8d9f-248bfc498e60.aspx</guid>
      <link>http://www.atrevido.net/blog/2007/09/06/Complicated+Functions+In+LINQ+To+SQL.aspx</link>
      <pubDate>Thu, 06 Sep 2007 13:56:54 GMT</pubDate>
      <description>&lt;p&gt;
Rob Conery talks about geocoding with LINQ &lt;a href="http://blog.wekeroad.com/2007/08/30/linq-and-geocoding/"&gt;here&lt;/a&gt;.
In his post, he provides some code using the &lt;a href="http://en.wikipedia.org/wiki/Haversine_formula"&gt;Haversine
formula&lt;/a&gt; to compute the distance between two points on earth. His function is declared
as: 
&lt;/p&gt;
&lt;p style="BACKGROUND: white"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af; BACKGROUND-COLOR: #eeece1"&gt;Func&lt;/span&gt;&lt;span style="COLOR: black; BACKGROUND-COLOR: #eeece1"&gt;&amp;lt;&lt;/span&gt;&lt;span style="COLOR: blue; BACKGROUND-COLOR: #eeece1"&gt;double&lt;/span&gt;&lt;span style="COLOR: black; BACKGROUND-COLOR: #eeece1"&gt;, &lt;/span&gt;&lt;span style="COLOR: blue; BACKGROUND-COLOR: #eeece1"&gt;double&lt;/span&gt;&lt;span style="COLOR: black; BACKGROUND-COLOR: #eeece1"&gt;, &lt;/span&gt;&lt;span style="COLOR: blue; BACKGROUND-COLOR: #eeece1"&gt;double&lt;/span&gt;&lt;span style="COLOR: black; BACKGROUND-COLOR: #eeece1"&gt;, &lt;/span&gt;&lt;span style="COLOR: blue; BACKGROUND-COLOR: #eeece1"&gt;double&lt;/span&gt;&lt;span style="COLOR: black; BACKGROUND-COLOR: #eeece1"&gt;, &lt;/span&gt;&lt;span style="COLOR: blue; BACKGROUND-COLOR: #eeece1"&gt;double&lt;/span&gt;&lt;span style="COLOR: black"&gt;&lt;span style="BACKGROUND-COLOR: #eeece1"&gt;&amp;gt;
CalcDistance = (lat1, lon1, lat2, lon2) =&amp;gt; …&lt;/span&gt;&lt;span style="FONT-SIZE: 12pt"&gt; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Further, this delegate is wrapped in a normal C# method. Now, read my previous post
about &lt;a href="http://www.atrevido.net/blog/2007/09/05/Calling+Custom+Methods+In+LINQtoSQL.aspx"&gt;&lt;span style="FONT-SIZE: 12pt; FONT-FAMILY: Consolas"&gt;calling
functions in LINQ to SQL&lt;/span&gt;&lt;/a&gt;. 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 &lt;em&gt;data&lt;/em&gt; 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. 
&lt;/p&gt;
&lt;p&gt;
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! &lt;a href="http://tomasp.net/articles/dynamic-linq-queries.aspx"&gt;TomasP's
Expandable stuff looks cool&lt;/a&gt;, but I ran into some bugs on Beta 2. This is really
something the compiler should help out with!). 
&lt;/p&gt;
&lt;p&gt;
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.): 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;const&lt;/span&gt; &lt;span style="COLOR: blue"&gt;double&lt;/span&gt; R
= 6367; 
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;const&lt;/span&gt; &lt;span style="COLOR: blue"&gt;double&lt;/span&gt; RAD
= &lt;span style="COLOR: #2b91af"&gt;Math&lt;/span&gt;.PI / 180; 
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="COLOR: blue"&gt;double&lt;/span&gt;, &lt;span style="COLOR: blue"&gt;double&lt;/span&gt;, &lt;span style="COLOR: blue"&gt;double&lt;/span&gt;, &lt;span style="COLOR: blue"&gt;double&lt;/span&gt;, &lt;span style="COLOR: blue"&gt;double&lt;/span&gt;&amp;gt;&amp;gt;
dist = 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Consolas"&gt;(lat1, lon1, lat2, lon2) =&amp;gt;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;R
* 2 *&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;(&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;Math&lt;/span&gt;.Asin(&lt;span style="COLOR: #2b91af"&gt;Math&lt;/span&gt;.Min(1,&lt;span style="COLOR: #2b91af"&gt;Math&lt;/span&gt;.Sqrt(&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;(&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;Math&lt;/span&gt;.Pow(&lt;span style="COLOR: #2b91af"&gt;Math&lt;/span&gt;.Sin(((lat1
* RAD - lat2 * RAD)) / 2.0), 2.0) +&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;Math&lt;/span&gt;.Cos(lat1
* RAD) * &lt;span style="COLOR: #2b91af"&gt;Math&lt;/span&gt;.Cos(lat2 * RAD) *&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;Math&lt;/span&gt;.Pow(&lt;span style="COLOR: #2b91af"&gt;Math&lt;/span&gt;.Sin(((lon1
* RAD - lon2 * RAD)) / 2.0), 2.0)&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;)&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;)))&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
OK, that was the easy part. We just had to&amp;nbsp;wrap Expression&amp;lt;&amp;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: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;public&lt;/span&gt; &lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;TSource&amp;gt;
Where&amp;lt;TSource&amp;gt;(&lt;span style="COLOR: blue"&gt;this&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;IQueryable&lt;/span&gt;&amp;lt;TSource&amp;gt;
source, &lt;span style="COLOR: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TSource, &lt;span style="COLOR: blue"&gt;bool&lt;/span&gt;&amp;gt;&amp;gt;
predicate); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Hence, we need to provide a predicate of &lt;span style="FONT-FAMILY: Courier New"&gt;Expression&amp;lt;Func&amp;lt;TSource,
bool&amp;gt;&amp;gt;&lt;/span&gt; for it do its magic. To work with expressions, we need to start
using the &lt;span style="FONT-FAMILY: Courier New"&gt;System.Linq.Expressions&lt;/span&gt; namespace.
For more clarity, I aliased &lt;span style="FONT-FAMILY: Courier New"&gt;E&lt;/span&gt; to &lt;span style="FONT-FAMILY: Courier New"&gt;System.Linq.Expressions.Expression&lt;/span&gt;.
Building expressions isn't particularly &lt;em&gt;hard&lt;/em&gt;, 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. 
&lt;/p&gt;
&lt;p&gt;
We start off with some data from elsewhere in our application. In my example, I'm
just going to declare some locals: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;double&lt;/span&gt; coolLat
= 43.641852; 
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;double&lt;/span&gt; coolLong = -79.387298; 
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;double&lt;/span&gt; maxDist = 100; &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
The first &lt;span style="FONT-FAMILY: Courier New"&gt;Expression&lt;/span&gt; we need is a &lt;span style="FONT-FAMILY: Courier New"&gt;ParameterExpression&lt;/span&gt; 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: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; acctParam
= &lt;span style="COLOR: #2b91af"&gt;E&lt;/span&gt;.Parameter(&lt;span style="COLOR: blue"&gt;typeof&lt;/span&gt;(&lt;span style="COLOR: #2b91af"&gt;Account&lt;/span&gt;), &lt;span style="COLOR: #a31515"&gt;"a"&lt;/span&gt;); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
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: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; acctLon = &lt;span style="COLOR: #2b91af"&gt;E&lt;/span&gt;.Property(acctParam, &lt;span style="COLOR: #a31515"&gt;"Longitude"&lt;/span&gt;);&lt;br&gt;
&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; acctLat = &lt;span style="COLOR: #2b91af"&gt;E&lt;/span&gt;.Property(acctParam, &lt;span style="COLOR: #a31515"&gt;"Latitude"&lt;/span&gt;); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
The secret sauce is creating the invoke to our &lt;span style="FONT-FAMILY: Courier New"&gt;dist&lt;/span&gt; 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: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; distCalc
= &lt;span style="COLOR: #2b91af"&gt;E&lt;/span&gt;.Invoke(dist, &lt;span style="COLOR: #2b91af"&gt;E&lt;/span&gt;.Constant(coolLat), &lt;span style="COLOR: #2b91af"&gt;E&lt;/span&gt;.Constant(coolLong),
acctLat, acctLon); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
We have to use &lt;span style="FONT-FAMILY: Courier New"&gt;ConstantExpression&lt;/span&gt;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 &lt;span style="FONT-FAMILY: Courier New"&gt;&amp;lt;TSource, bool&amp;gt; LambdaExpression&lt;/span&gt;: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; maxComp = &lt;span style="COLOR: #2b91af"&gt;E&lt;/span&gt;.LessThan(distCalc, &lt;span style="COLOR: #2b91af"&gt;E&lt;/span&gt;.Constant(maxDist)); 
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; pred = &lt;span style="COLOR: #2b91af"&gt;E&lt;/span&gt;.Lambda&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Account&lt;/span&gt;, &lt;span style="COLOR: blue"&gt;bool&lt;/span&gt;&amp;gt;&amp;gt;(maxComp,
acctParam); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Our query can now look like this: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: #2b91af"&gt;MembersDataContext&lt;/span&gt; dc
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;MembersDataContext&lt;/span&gt;();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; q = dc.Accounts.Where(pred); 
&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(q.ToString()); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
When we run it, we see that LINQ to SQL is quite capable of handling our little bit
of math: 
&lt;/p&gt;
&lt;p&gt;
&lt;span style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;exec&lt;/span&gt; &lt;span style="COLOR: maroon"&gt;sp_executesql&lt;/span&gt; N&lt;span style="COLOR: red"&gt;'SELECT
[t0].[AccountId], [t0].[Latitude], [t0].[Longitude]&lt;br&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; COLOR: red; FONT-FAMILY: Courier New"&gt;FROM
[dbo].[Accounts] AS [t0] 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; COLOR: red; FONT-FAMILY: Courier New"&gt;WHERE (@p0
* ASIN( 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; COLOR: red; FONT-FAMILY: Courier New"&gt;(CASE 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; COLOR: red; FONT-FAMILY: Courier New"&gt;WHEN @p1
&amp;lt; SQRT(POWER(SIN(((@p2 * @p3) - ([t0].[Latitude] * @p4)) / @p5), @p6) + (COS(@p7
* @p8) * COS([t0].[Latitude] * @p9) * 
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; COLOR: red; FONT-FAMILY: Courier New"&gt;POWER(SIN(((@p10
* @p11) - ([t0].[Longitude] * @p12)) / @p13), @p14))) THEN @p1 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; COLOR: red; FONT-FAMILY: Courier New"&gt;ELSE SQRT(POWER(SIN(((@p2
* @p3) - ([t0].[Latitude] * @p4)) / @p5), @p6) + (COS(@p7 * @p8) * COS([t0].[Latitude]
* @p9) * 
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; POWER(SIN(((@p10 * @p11) - ([t0].[Longitude] * @p12)) / @p13),
@p14))) &lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: red"&gt;
&lt;br&gt;
END))) &amp;lt; @p15'&lt;/span&gt;&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;N&lt;span style="COLOR: red"&gt;'@p0
float,@p1 float,@p2 float,@p3 float,@p4 float,@p5 float,@p6 float,@p7 float,@p8 float,@p9
float,&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; @p10 float,@p11 float,@p12 float,@p13 float,@p14 float,@p15 float'&lt;/span&gt;&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p0&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;12742&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p1&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;1&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p2&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;95.412000000000006&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p3&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;0.017453292519943295&lt;span style="COLOR: gray"&gt;,&lt;br&gt;
&lt;/span&gt;@p4&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;0.017453292519943295&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p5&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;2&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p6&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;2&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p7&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;95.412000000000006&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p8&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;0.017453292519943295&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p9&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;0.017453292519943295&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p10&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;102.63200000000001&lt;span style="COLOR: gray"&gt;,&lt;br&gt;
&lt;/span&gt;@p11&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;0.017453292519943295&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p12&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;0.017453292519943295&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p13&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;2&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p14&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;2&lt;span style="COLOR: gray"&gt;,&lt;/span&gt;@p15&lt;span style="COLOR: gray"&gt;=&lt;/span&gt;100 &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
I still think there should be some kind of syntax so we could write it like we want
to: (Where(a=&amp;gt;dist(coolLat, coolLong, a.Latitude, a.Longitude) &amp;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...
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=f9e4d1ef-8fff-4f44-8d9f-248bfc498e60" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,f9e4d1ef-8fff-4f44-8d9f-248bfc498e60.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=f26a9142-88f9-4376-9285-a775227cfde7</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,f26a9142-88f9-4376-9285-a775227cfde7.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,f26a9142-88f9-4376-9285-a775227cfde7.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=f26a9142-88f9-4376-9285-a775227cfde7</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body 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" />
      </body>
      <title>Calling custom methods in LINQ-to-SQL</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,f26a9142-88f9-4376-9285-a775227cfde7.aspx</guid>
      <link>http://www.atrevido.net/blog/2007/09/05/Calling+Custom+Methods+In+LINQtoSQL.aspx</link>
      <pubDate>Wed, 05 Sep 2007 23:58:49 GMT</pubDate>
      <description>&lt;p&gt;
This was sparked by the issues raised by &lt;a href="http://blog.wekeroad.com/2007/08/30/linq-and-geocoding/"&gt;Rob
Conery here&lt;/a&gt;. 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: &lt;a href="http://tomasp.net/articles/dynamic-linq-queries.aspx"&gt;Building
LINQ Queries at Runtime&lt;/a&gt; in C# and Joseph Albahari: &lt;a href="http://www.albahari.com/expressions/"&gt;Dynamically
building LINQ expression predicates&lt;/a&gt;. 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. 
&lt;/p&gt;
&lt;p&gt;
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: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;void&lt;/span&gt; Main(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt;[]
args) { 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
MembersDataContext&lt;/span&gt; dc = &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;MembersDataContext&lt;/span&gt;(); 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
var&lt;/span&gt; q = dc.Accounts.Where(a =&amp;gt; IsRightAccount(a)); 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
Console&lt;/span&gt;.WriteLine(q.ToString()); 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;} 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;bool&lt;/span&gt; IsRightAccount(&lt;span style="COLOR: #2b91af"&gt;Account&lt;/span&gt; a)
{ 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
return&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Math&lt;/span&gt;.Sqrt(a.AccountId) % 2 == 0; 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
This code crashes with: &lt;span style="FONT-FAMILY: Courier New"&gt;Unhandled Exception:
System.NotSupportedException: Method 'Boolean IsRightAccount(ConsoleApplication1.Account)'
has no supported translation to SQL&lt;/span&gt;. Which should be expected, as LINQ to SQL
cannot know what goes on inside that method and thus can't translate it. 
&lt;/p&gt;
&lt;p&gt;
Let's change things to make IsRightAccount be a Func delegate (from a lambda expression): 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Account&lt;/span&gt;, &lt;span style="COLOR: blue"&gt;bool&lt;/span&gt;&amp;gt;
IsRightAccount = a =&amp;gt; &lt;span style="COLOR: #2b91af"&gt;Math&lt;/span&gt;.Sqrt(a.AccountId)
% 2 == 0; &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Now we get: &lt;span style="FONT-FAMILY: Courier New"&gt;Unhandled Exception: System.NotImplementedException:
The method or operation is not implemented. At System.Data.Linq.SqlClient.QueryConverter.VisitInvocation(InvocationExpression
invoke).&lt;/span&gt; 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. 
&lt;/p&gt;
&lt;p&gt;
Enter the magic Tree of Expressions: &lt;span style="FONT-FAMILY: Courier New"&gt;Expression&amp;lt;T&amp;gt;&lt;/span&gt;.
As I mentioned in my &lt;a href="http://www.atrevido.net/blog/2007/09/05/C+30+And+LINQ+Misunderstandings.aspx"&gt;last
post&lt;/a&gt;, Expression Trees provide "introspection" (reflection against code). In the
examples above, the lambda that calls &lt;span style="FONT-FAMILY: Courier New"&gt;IsRightAccount&lt;/span&gt; for
the Where clause actually turned into an &lt;span style="FONT-FAMILY: Courier New"&gt;InvocationExpression&lt;/span&gt; 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 &lt;span style="FONT-FAMILY: Courier New"&gt;IsRightAccount&lt;/span&gt; calculation)
is visible &lt;em&gt;as data&lt;/em&gt;. 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". 
&lt;/p&gt;
&lt;p&gt;
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&amp;lt;MyFunc&amp;gt;: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="COLOR: blue; FONT-FAMILY: Courier New"&gt;static&lt;/span&gt;&lt;span style="FONT-FAMILY: Consolas"&gt; &lt;/span&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Account&lt;/span&gt;, &lt;span style="COLOR: blue"&gt;bool&lt;/span&gt;&amp;gt;&amp;gt;
IsRightAccount = a =&amp;gt; &lt;span style="COLOR: #2b91af"&gt;Math&lt;/span&gt;.Sqrt(a.AccountId)
% 2 == 0;&lt;/span&gt;&lt;span style="FONT-FAMILY: Consolas"&gt; &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
We will also change our Where clause to accommodate the fact that we are not calling
a method: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; q = dc.Accounts.Where(IsRightAccount); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
And presto! Our program now shows a SQL conversion: 
&lt;/p&gt;
&lt;p&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;SELECT [t0].[AccountId], [t0].[Email] 
&lt;br&gt;
FROM [dbo].[Accounts] AS [t0]&lt;br&gt;
WHERE (SQRT(CONVERT(Float,[t0].[AccountId])) % @p0) = @p1 &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
This also applies if you have complex logic that doesn't directly map to a item -&amp;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 &lt;a href="http://www.atrevido.net/blog/2007/08/26/A+LINQ+To+The+CRUD.aspx"&gt;LINQ
to the CRUD&lt;/a&gt; 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. 
&lt;/p&gt;
&lt;p&gt;
If you know of any other links or work done in this area, I'm very interested in seeing
other approaches. Thanks!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=f26a9142-88f9-4376-9285-a775227cfde7" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,f26a9142-88f9-4376-9285-a775227cfde7.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=522978e9-045b-447b-9898-9947467c2fe5</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,522978e9-045b-447b-9898-9947467c2fe5.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,522978e9-045b-447b-9898-9947467c2fe5.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=522978e9-045b-447b-9898-9947467c2fe5</wfw:commentRss>
      <slash:comments>10</slash:comments>
      <body 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" />
      </body>
      <title>C# 3.0 and LINQ Misunderstandings</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,522978e9-045b-447b-9898-9947467c2fe5.aspx</guid>
      <link>http://www.atrevido.net/blog/2007/09/05/C+30+And+LINQ+Misunderstandings.aspx</link>
      <pubDate>Wed, 05 Sep 2007 03:01:18 GMT</pubDate>
      <description>&lt;p&gt;
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 (&lt;a href="http://msdn2.microsoft.com/en-us/library/ms364047(vs.80).aspx"&gt;http://msdn2.microsoft.com/en-us/library/ms364047(vs.80).aspx&lt;/a&gt;)
so you can know I'm being accurate. 
&lt;/p&gt;
&lt;h1&gt;&lt;font size=4&gt;Myth: LINQ is just a data access technology&lt;/font&gt; 
&lt;/h1&gt;
&lt;p&gt;
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 &lt;a href="http://www.atrevido.net/blog/2007/08/29/Practical+Functional+C+Part+IV+Think+In+ResultSets.aspx"&gt;previous
example&lt;/a&gt;: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-SIZE: 9pt; FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;args&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.Select(s
=&amp;gt; &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Thread&lt;/span&gt;(()
=&amp;gt; SomeLongProcess(s)))&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.Process(t
=&amp;gt; t.Start())&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.ToList()&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.ForEach(t
=&amp;gt; t.Join());&lt;/span&gt; 
&lt;/p&gt;
&lt;p&gt;
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?)
&lt;/p&gt;
&lt;h1&gt;&lt;font size=4&gt;Implicitly typed local variables (var keyword)&lt;/font&gt; 
&lt;/h1&gt;
&lt;p&gt;
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: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #dddddd"&gt;
&lt;span style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New"&gt;var i = 5; 
&lt;br&gt;
var s = "Hello"; 
&lt;br&gt;
var d = 1.0; 
&lt;br&gt;
var numbers = new int[] {1, 2, 3}; 
&lt;br&gt;
var orders = new Dictionary&amp;lt;int,Order&amp;gt;(); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;span style="FONT-SIZE: 8pt; FONT-FAMILY: Verdana"&gt;The implicitly typed local variable
declarations above are precisely equivalent to the following explicitly typed declarations: &lt;/span&gt;
&lt;/p&gt;
&lt;p style="BACKGROUND: #dddddd"&gt;
&lt;span style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New"&gt;int i = 5; 
&lt;br&gt;
string s = "Hello"; 
&lt;br&gt;
double d = 1.0; 
&lt;br&gt;
int[] numbers = new int[] {1, 2, 3}; 
&lt;br&gt;
Dictionary&amp;lt;int,Order&amp;gt; orders = new Dictionary&amp;lt;int,Order&amp;gt;(); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
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: 
&lt;/p&gt;
&lt;p&gt;
C# anonymous types allow you to declare a type just by specifying its fields. From
the spec: "&lt;span style="FONT-SIZE: 8pt; FONT-FAMILY: Verdana"&gt;C# 3.0 permits the &lt;strong&gt;new&lt;/strong&gt; operator
to be used with an anonymous object initializer to create an object of an anonymous
type."&lt;/span&gt; For instance, the following code is a valid expression: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;new&lt;/span&gt; { Name = &lt;span style="COLOR: #a31515"&gt;"Michael" &lt;/span&gt;} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
This produces an object of a new, anonymous, type, containing a single string property
called Name. Hence, this code works: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="COLOR: blue"&gt;new&lt;/span&gt; {
Name = &lt;span style="COLOR: #a31515"&gt;"Michael"&lt;/span&gt; }.Name); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
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: 
&lt;/p&gt;
&lt;p&gt;
var topCustomers = MyDatabase.Customers.Where(c =&amp;gt; c.GoldStar == true).Select(c
=&amp;gt; new {c.CustomerId, c.Name}); 
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
What's the takeaway here? &lt;strong&gt;The var keyword simply allows the compiler to infer
the type of the variable so you don't have to specify it.&lt;/strong&gt; 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! 
&lt;/p&gt;
&lt;p&gt;
As a side note (if this wasn't clear), the var keyword is NOT dynamic typing, just
implicit typing (type inference). 
&lt;/p&gt;
&lt;h1&gt;&lt;font size=4&gt;Dynamic C#&lt;/font&gt; 
&lt;/h1&gt;
&lt;p&gt;
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 "&lt;a href="http://poignantguide.net/ruby/chapter-3.html"&gt;why's
(poignant) guide to ruby&lt;/a&gt;", we see this Ruby code: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #339966; BACKGROUND-COLOR: #fffef9"&gt;5&lt;/span&gt;&lt;span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9"&gt;.&lt;/span&gt;&lt;span style="COLOR: #336699; BACKGROUND-COLOR: #fffef9"&gt;times&lt;/span&gt;&lt;span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9"&gt; { &lt;/span&gt;&lt;span style="COLOR: #336699; BACKGROUND-COLOR: #fffef9"&gt;print&lt;/span&gt;&lt;span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9"&gt; "&lt;/span&gt;&lt;span style="COLOR: #339966; BACKGROUND-COLOR: #e9f5f5"&gt;Odelay!&lt;/span&gt;&lt;span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9"&gt;"
} &lt;/span&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
C# allows us to write in a similar style: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;5.Times(() =&amp;gt; &lt;span style="COLOR: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="COLOR: #a31515"&gt;"Odelay!"&lt;/span&gt;)); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
The next Ruby example in that guide goes like this: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #336699; BACKGROUND-COLOR: #fffef9"&gt;exit&lt;/span&gt;&lt;span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9"&gt; &lt;strong&gt;unless&lt;/strong&gt; "&lt;/span&gt;&lt;span style="COLOR: #339966; BACKGROUND-COLOR: #e9f5f5"&gt;restaurant&lt;/span&gt;&lt;span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9"&gt;".&lt;/span&gt;&lt;span style="COLOR: #336699; BACKGROUND-COLOR: #fffef9"&gt;include?&lt;/span&gt;&lt;span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9"&gt; "&lt;/span&gt;&lt;span style="COLOR: #339966; BACKGROUND-COLOR: #e9f5f5"&gt;aura&lt;/span&gt;&lt;span style="COLOR: #993366; BACKGROUND-COLOR: #fffef9"&gt;" &lt;/span&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
In C#, we can write: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;exit.Unless(() =&amp;gt; &lt;span style="COLOR: #a31515"&gt;"restaurant"&lt;/span&gt;.Contains(&lt;span style="COLOR: #a31515"&gt;"aura"&lt;/span&gt;));&lt;/span&gt; 
&lt;/p&gt;
&lt;p&gt;
The &lt;a href="http://en.wikipedia.org/wiki/Dynamic_language"&gt;Wikipedia article on Functional
Programming&lt;/a&gt; lists a few features that dynamic languages usually have: 
&lt;/p&gt;
&lt;h2&gt;&lt;font size=3&gt;Eval &lt;/font&gt;
&lt;/h2&gt;
&lt;p&gt;
Sorta… you can create Expression&amp;lt;T&amp;gt; and execute them. On the other hand, you
can't do anything like eval(myString) (which is just asking for runtime failure). 
&lt;/p&gt;
&lt;h2&gt;&lt;font size=3&gt;Higher-order functions&lt;/font&gt; 
&lt;/h2&gt;
&lt;p&gt;
Definitely in there. 
&lt;/p&gt;
&lt;h2&gt;&lt;font size=3&gt;Runtime alteration of object or type system&lt;/font&gt; 
&lt;/h2&gt;
&lt;p&gt;
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.) 
&lt;/p&gt;
&lt;h2&gt;&lt;font size=3&gt;Functional Programming&lt;/font&gt; 
&lt;/h2&gt;
&lt;p&gt;
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: &lt;a href="http://sneezy.cs.nott.ac.uk/fun/nov-06/FunPm.ppt"&gt;C#
is a functional programming language&lt;/a&gt;.
&lt;/p&gt;
&lt;h2&gt;&lt;font size=3&gt;Closures &lt;/font&gt;
&lt;/h2&gt;
&lt;p&gt;
Yep, since anonymous methods were introduced in C# 2.0. 
&lt;/p&gt;
&lt;h2&gt;&lt;font size=3&gt;Continuations&lt;/font&gt; 
&lt;/h2&gt;
&lt;p&gt;
Extremely limited, in the form of &lt;span style="FONT-FAMILY: Courier New"&gt;yield return&lt;/span&gt;. 
&lt;/p&gt;
&lt;h2&gt;&lt;font size=3&gt;Introspection&lt;/font&gt; 
&lt;/h2&gt;
&lt;p&gt;
Not just reflection, but actually inspecting the actual code. C# 3.0 has this in the
form of Expression&amp;lt;T&amp;gt; (see below). 
&lt;/p&gt;
&lt;h2&gt;&lt;font size=3&gt;Macros&lt;/font&gt; 
&lt;/h2&gt;
&lt;p&gt;
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). 
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;In summary&lt;/strong&gt;, C# lets you gain a lot of benefits usually associated
with dynamic &lt;strong&gt;programming&lt;/strong&gt;, but without the nasty parts of dynamic &lt;strong&gt;typing&lt;/strong&gt;. 
&lt;/p&gt;
&lt;p&gt;
A great paper on this subject is &lt;a href="http://pico.vub.ac.be/~wdmeuter/RDL04/papers/Meijer.pdf"&gt;Static
Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between
Programming Languages&lt;/a&gt;, by Erik Meijer and Peter Drayton of Microsoft. 
&lt;/p&gt;
&lt;h1&gt;&lt;font size=4&gt;Myth: Extension methods add methods to a class&lt;/font&gt; 
&lt;/h1&gt;
&lt;p&gt;
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." 
&lt;/p&gt;
&lt;p&gt;
Essentially, Extension methods allow us to use &lt;a href="http://en.wikipedia.org/wiki/Infix_notation"&gt;&lt;strong&gt;infix&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt; &lt;/strong&gt;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 &lt;em&gt;specially
marked&lt;/em&gt; methods. 
&lt;/p&gt;
&lt;p&gt;
An alternative* would be to define an operator like the F# pipeline operator (|&amp;gt;).
In C#, this would let us write stuff like: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
customers |&amp;gt; Seq.Where(c =&amp;gt; c.Name == "Michael") 
&lt;/p&gt;
&lt;p&gt;
That doesn't look like an improvement. BUT, we no longer need to mark methods in a
special way. We can just use them: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
myArray |&amp;gt; Array.BinarySearch("s") 
&lt;/p&gt;
&lt;p&gt;
Why do we need infix notation anyways? Well, the normal prefix notation can be difficult
to read: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
Select(Where(customers, c =&amp;gt; c.Cool == true), c =&amp;gt; c.Name)&lt;br&gt;
Array.BinarySearch(items, "S") 
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
*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 |&amp;gt; Stuff.SomeMethod("X")" where
SomeMethod returns a function. Or, where you have "item |&amp;gt; Stuff.SomeMethod("X").SomethingElse("y").
I'm still annoyed that I can't use infix semantics where *I* want, but oh well. 
&lt;/p&gt;
&lt;h2&gt;&lt;font size=4&gt;Lambda expressions and Expression&amp;lt;T&amp;gt;&lt;/font&gt; 
&lt;/h2&gt;
&lt;p&gt;
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&amp;lt;D&amp;gt;." 
&lt;/p&gt;
&lt;p&gt;
So, "lambda expressions" can either be just code (i.e., directly executable IL) OR
they can get turned into a data structure, Expression&amp;lt;T&amp;gt;. 
&lt;/p&gt;
&lt;p&gt;
Adding to the confusion, a lambda expression can contain just an expression (i=&amp;gt;
i + 1), or it can be a block of statements ( i =&amp;gt; {Write(i); i++; Write(i); return
i+1;} ). However, a lambda expression with a statement block body &lt;em&gt;cannot &lt;/em&gt;become
an Expression&amp;lt;T&amp;gt;. (As far as I know, VB's lambdas only allow for expression
bodies, not blocks.) 
&lt;/p&gt;
&lt;p&gt;
An example: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;, &lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;
inc = i =&amp;gt; i + 1; &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;font face=Arial&gt;Is equivalent to:&lt;/font&gt; &lt;/span&gt;
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: #2b91af"&gt;ParameterExpression&lt;/span&gt; param_i
= &lt;span style="COLOR: #2b91af"&gt;Expression&lt;/span&gt;.Parameter(&lt;span style="COLOR: blue"&gt;typeof&lt;/span&gt;(&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;), &lt;span style="COLOR: #a31515"&gt;"i"&lt;/span&gt;);&lt;br&gt;
&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; inc2 = &lt;span style="COLOR: #2b91af"&gt;Expression&lt;/span&gt;.Lambda&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;, &lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;(&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Expression&lt;/span&gt;.Add(&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;param_i,&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="COLOR: #2b91af"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;Expression&lt;/span&gt;.Constant(1, &lt;span style="COLOR: blue"&gt;typeof&lt;/span&gt;(&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;))), 
&lt;br&gt;
param_i); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
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&amp;lt;T&amp;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). 
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Are there any other features that you've seen misused or you've had questions
about?&lt;/strong&gt; Let me know! I love comments, insults, and suggestions.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Want to correct me on something?&lt;/strong&gt; Go right ahead! But, if you're going
to say something like "C# doesn't have type inference",&amp;nbsp;please make sure to either
be an expert on the matter or be able to quote an authoritative source or show a proof.
Thanks!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=522978e9-045b-447b-9898-9947467c2fe5" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,522978e9-045b-447b-9898-9947467c2fe5.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=ed630fc6-cafa-450a-a6f2-7a570064f09a</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,ed630fc6-cafa-450a-a6f2-7a570064f09a.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,ed630fc6-cafa-450a-a6f2-7a570064f09a.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=ed630fc6-cafa-450a-a6f2-7a570064f09a</wfw:commentRss>
      <slash:comments>4</slash:comments>
      <body 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" />
      </body>
      <title>Practical Functional C# - Part IV – Think in [Result]Sets</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,ed630fc6-cafa-450a-a6f2-7a570064f09a.aspx</guid>
      <link>http://www.atrevido.net/blog/2007/08/29/Practical+Functional+C+Part+IV+Think+In+ResultSets.aspx</link>
      <pubDate>Wed, 29 Aug 2007 10:45:59 GMT</pubDate>
      <description>&lt;p&gt;
Don't skip parts I&amp;nbsp;to III to get you up to speed.&amp;nbsp;I have $300 up for grabs
if these articles are incorrect in stating that it will greatly improve most C# apps:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;a href="http://www.atrevido.net/blog/2007/08/12/Practical+Functional+C+Part+I.aspx"&gt;Practical
Functional C# - Part I&amp;nbsp;&lt;/a&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;a href="http://www.atrevido.net/blog/2007/08/13/Practical+Functional+C+Part+II.aspx"&gt;Practical
Functional C# - Part II&amp;nbsp;&lt;br&gt;
&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;a href="http://www.atrevido.net/blog/2007/08/16/Practical+Functional+C+Part+III+Loops+Are+Evil.aspx"&gt;Practical
Functional C# - Part III - Loops are Evil&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
Consider the following task: Write a function that checks a username against a few
disallowed characters "!@#$%^&amp;amp;*". The normal C# implementation looks like this
(null checks removed): 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;bool&lt;/span&gt; IsBadUserName(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt; userName)&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;var&lt;/span&gt; badChars = &lt;span style="COLOR: #a31515"&gt;"!@#$%^&amp;amp;*"&lt;/span&gt;;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;foreach&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;char&lt;/span&gt; c &lt;span style="COLOR: blue"&gt;in&lt;/span&gt; badChars)
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;if&lt;/span&gt; (userName.Contains(c)) &lt;span style="COLOR: blue"&gt;return&lt;/span&gt; &lt;span style="COLOR: blue"&gt;true&lt;/span&gt;;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;return&lt;/span&gt; &lt;span style="COLOR: blue"&gt;false&lt;/span&gt;; 
&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
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): 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;bool&lt;/span&gt; IsBadUserName2(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt; userName){&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;var&lt;/span&gt; badChars
= &lt;span style="COLOR: #a31515"&gt;"!@#$%^&amp;amp;*"&lt;/span&gt;;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;return&lt;/span&gt; userName&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;.Intersect(badChars)&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;.Any();&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
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: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; ourInts
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt;[] { 2, 5, 13 };&lt;br&gt;
&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; squares = ourInts.Select(i =&amp;gt; i * i); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
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: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; tempAddresses
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;MailAddress&lt;/span&gt;&amp;gt;();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;foreach&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;string&lt;/span&gt; s &lt;span style="COLOR: blue"&gt;in&lt;/span&gt; semicolonEmails.Split(&lt;span style="COLOR: #a31515"&gt;';'&lt;/span&gt;))
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;var&lt;/span&gt; ts
= s.Trim();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;if&lt;/span&gt; (ts
== &lt;span style="COLOR: #a31515"&gt;""&lt;/span&gt;) &lt;span style="COLOR: blue"&gt;continue&lt;/span&gt;;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;tempAddresses.Add(&lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;MailAddress&lt;/span&gt;(ts));&amp;nbsp;&lt;br&gt;
}&lt;br&gt;
&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; myAddresses = tempAddresses.ToArray(); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
But consider the functional approach: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;var &lt;/span&gt;myAddresses
= semicolonEmails&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.Split(&lt;span style="COLOR: #a31515"&gt;';'&lt;/span&gt;)&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.Select(s =&amp;gt; s.Trim())&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.Where(s =&amp;gt; s !=&lt;span style="COLOR: #a31515"&gt; ""&lt;/span&gt;)&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.Select(s =&amp;gt; &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; MailAddress(s))&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.ToArray(); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
In one statement, we transform the data three times, as well as add filter to remove
empty items. 
&lt;/p&gt;
&lt;p&gt;
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&amp;lt;T&amp;gt; does define these methods.) &lt;span style="FONT-FAMILY: Courier New"&gt;Process&lt;/span&gt; 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: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;
Process&amp;lt;T&amp;gt;(&lt;span style="COLOR: blue"&gt;this&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;
source, &lt;span style="COLOR: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt; f)&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;foreach&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; item &lt;span style="COLOR: blue"&gt;in&lt;/span&gt; source)
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;f(item);&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;yield&lt;/span&gt; &lt;span style="COLOR: blue"&gt;return&lt;/span&gt; item;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
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: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;void&lt;/span&gt; Main(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt;[]
args)&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;var&lt;/span&gt; threads
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Thread&lt;/span&gt;&amp;gt;();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;foreach&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; s &lt;span style="COLOR: blue"&gt;in&lt;/span&gt; args)
{&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;Thread&lt;/span&gt; t
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Thread&lt;/span&gt;(startLongProcess);&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;t.Start(s);&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;threads.Add(t);&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;foreach&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; t &lt;span style="COLOR: blue"&gt;in&lt;/span&gt; threads)
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;t.Join();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
}&lt;br&gt;
&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;void&lt;/span&gt; startLongProcess(&lt;span style="COLOR: blue"&gt;object&lt;/span&gt; data) 
&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;SomeLongProcess((&lt;span style="COLOR: blue"&gt;string&lt;/span&gt;)data); 
&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Yes, we actually&amp;nbsp;must declare a separate function just to invoke &lt;span style="FONT-FAMILY: Courier New"&gt;SomeLongProcess&lt;/span&gt;.
Let's combine and use the functional approach now: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;void&lt;/span&gt; Main(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt;[]
args) 
&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;args&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;.Select(s
=&amp;gt; &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Thread&lt;/span&gt;(()
=&amp;gt; SomeLongProcess(s)))&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.Process(t
=&amp;gt; t.Start())&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;.ToList()&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;.ForEach(t
=&amp;gt; t.Join());&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;p&gt;
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: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;args.Parallel(SomeLongProcess); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
But I'll talk about that another day. 
&lt;/p&gt;
&lt;p&gt;
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. 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=ed630fc6-cafa-450a-a6f2-7a570064f09a" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,ed630fc6-cafa-450a-a6f2-7a570064f09a.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=6f242348-42ca-4934-9c2e-ea2bd1103a02</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,6f242348-42ca-4934-9c2e-ea2bd1103a02.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,6f242348-42ca-4934-9c2e-ea2bd1103a02.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=6f242348-42ca-4934-9c2e-ea2bd1103a02</wfw:commentRss>
      <slash:comments>10</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
A question many people have run into is: How does CRUD fit into LINQ-to-SQL? While
LINQ-to-SQL (I'll abbreviate as DLINQ) provides a very fast and easy way for us to
start querying our data, it doesn't handle updates as beautifully. It is particularly
noticeable when you are doing multi-tier and hence cannot share a <span style="FONT-FAMILY: Courier New">DataContext</span>. 
</p>
        <p>
Let's consider an example database called "<span style="FONT-FAMILY: Courier New">MembersDatabase</span>"
which has a table called "<span style="FONT-FAMILY: Courier New">Accounts</span>". <span style="FONT-FAMILY: Courier New">Accounts</span> has
an <span style="FONT-FAMILY: Courier New">int</span> primary key, and a <span style="FONT-FAMILY: Courier New">varchar</span><span style="FONT-FAMILY: Courier New">Email</span> field.
We use the DLINQ designer and create the dbml that generates a class called <span style="FONT-FAMILY: Courier New">MembersDataContext</span>.
How does our app-tier code look? I'll give you a hint, it starts with "ug" and rhymes
with "nasty": 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: green">// Select<br /></span>
            <span style="COLOR: blue">int</span> someId = 123; <span style="COLOR: green">//
Passed from another tier<br /></span><span style="COLOR: #2b91af">Account</span> someAccount; <span style="COLOR: green">//
Can't use implicit typing -- no anonymous types<br /></span><span style="COLOR: blue">using</span> (<span style="COLOR: blue">var</span> dc
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">MembersDataContext</span>())
{<span style="COLOR: green"><br /></span>    someAccount = dc.Accounts.SingleOrDefault(a =&gt; a.AccountId
== someId);<span style="COLOR: green"><br /></span>}<span style="COLOR: green"><br /><br />
// Insert<br /></span><span style="COLOR: blue">var</span> myAccount = <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">Account</span>();<span style="COLOR: green"><br /></span>myAccount.Email = <span style="COLOR: #a31515">"me@contoso.com"</span>;<span style="COLOR: green"><br /></span><span style="COLOR: blue">using</span> (<span style="COLOR: blue">var</span> dc
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">MembersDataContext</span>())
{<span style="COLOR: green"><br /></span>    dc.Accounts.Add(myAccount);<span style="COLOR: green"> <br /></span>    dc.SubmitChanges();<span style="COLOR: green"><br /></span>}<span style="COLOR: green"><br /><br />
// Update<br /></span><span style="COLOR: blue">int</span> myId = 1; <span style="COLOR: green">//
Id and email passed from another tier<br /></span><span style="COLOR: blue">string</span> newEmail = <span style="COLOR: #a31515">"cool@cool.com"</span>;<span style="COLOR: green"><br /></span><span style="COLOR: blue">var</span> changedAccount = <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">Account</span>();<span style="COLOR: green"><br /></span>changedAccount.AccountId = myId;<span style="COLOR: green"><br /></span>changedAccount.Email = newEmail;<span style="COLOR: green"><br /></span><span style="COLOR: blue">using</span> (<span style="COLOR: blue">var</span> dc
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">MembersDataContext</span>())
{<span style="COLOR: green"><br /></span>    dc.Accounts.Attach(changedAccount, <span style="COLOR: blue">true</span>);<span style="COLOR: green"> <br /></span>    dc.SubmitChanges();<span style="COLOR: green"><br /></span>}<span style="COLOR: green"><br /><br />
// Delete<br /></span><span style="COLOR: blue">int</span> idToKill = 2; <span style="COLOR: green">//
Passed from another tier<br /></span><span style="COLOR: blue">using</span> (<span style="COLOR: blue">var</span> dc
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">MembersDataContext</span>())
{<span style="COLOR: green"><br /></span><span style="COLOR: blue"><font color="#003300">    </font>using</span> (<span style="COLOR: blue">var</span> txScope
= <span style="COLOR: blue">new</span> System.Transactions.<span style="COLOR: #2b91af">TransactionScope</span>())
{<span style="COLOR: green"><br /></span><span style="COLOR: blue"><font color="#003300">        </font>var</span> acc
= dc.Accounts.SingleOrDefault(a =&gt; a.AccountId == idToKill);<span style="COLOR: green"> <br /></span><span style="COLOR: blue"><font color="#003300">        </font>if</span> (acc
== <span style="COLOR: blue">null</span>) <span style="COLOR: blue">throw</span><span style="COLOR: blue">new</span><span style="COLOR: #2b91af">ChangeConflictException</span>(<span style="COLOR: #a31515">"Row
not found."</span>);<span style="COLOR: green"> <br /></span>        dc.Accounts.Remove(acc);<span style="COLOR: green"> <br /></span>        dc.SubmitChanges();<span style="COLOR: green"><br /></span>        txScope.Complete();<span style="COLOR: green"><br /></span>    }<span style="COLOR: green"><br /></span>} </span>
        </p>
        <p>
It's not horrible; it's certainly better than anything before it. But, we can do better.
I created some helper classes to do so (see attached file). 
</p>
        <p>
First, <span style="FONT-FAMILY: Courier New">DatabaseBase&lt;TContext&gt;</span>.
This holds our tables, and provides <span style="FONT-FAMILY: Courier New">DataContext</span> helper
functions <span style="FONT-FAMILY: Courier New">Use</span> and <span style="FONT-FAMILY: Courier New">Query</span>.
Second, <span style="FONT-FAMILY: Courier New">TableBase&lt;TItem, TKey&gt;</span>.
This actually provides our CRUD methods. I don't think anyone is overly interested
in the implementation details (comment if I'm wrong), so here's how you declare your
CRUD types: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">class</span>
            <span style="COLOR: #2b91af">MembersDatabase</span> : <span style="COLOR: #2b91af">DatabaseBase</span>&lt;<span style="COLOR: #2b91af">MembersDataContext</span>&gt;<br />
{<br /><span style="COLOR: blue"><font color="#003300">    </font>public</span><span style="COLOR: blue">static</span><span style="COLOR: blue">readonly</span><span style="COLOR: #2b91af">TableBase</span>&lt;<span style="COLOR: #2b91af">Account</span>, <span style="COLOR: blue">int</span>&gt;
Accounts <br />
        = CreateTable(dc =&gt; dc.Accounts, a =&gt;
a.AccountId); 
<br />
} </span>
        </p>
        <p>
That's it. 
</p>
        <p>
You create a new class to serve as your "database" class. All that's required here
is to inherit from <span style="FONT-FAMILY: Courier New">DatabaseBase</span>. 
</p>
        <p>
Next, for each table, simply create a new field via <span style="FONT-FAMILY: Courier New">CreateTable</span>.
The first parameter is a lambda function that selects the right table off the <span style="FONT-FAMILY: Courier New">DataContext</span>.
The second parameter is a lambda expression that selects the primary key. Not much
too it. 
</p>
        <p>
So, how does our previous chunk of code look with this small helper library? 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: green">// Select<br /></span>
            <span style="COLOR: blue">int</span> someId = 123; <span style="COLOR: green">//
Passed from another tier<br /></span><span style="COLOR: blue">var</span> someAccount = <span style="COLOR: #2b91af">MembersDatabase</span>.Accounts.SelectByKey(someId);<span style="COLOR: green"><br /><br />
// Insert<br /></span><span style="COLOR: blue">var</span> myAccount = <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">Account</span>();<span style="COLOR: green"><br /></span>myAccount.Email = <span style="COLOR: #a31515">"me@contoso.com"</span>;<span style="COLOR: green"><br /></span><span style="COLOR: #2b91af">MembersDatabase</span>.Accounts.Insert(myAccount);<span style="COLOR: green"><br /><br />
// Update<br /></span><span style="COLOR: blue">int</span> myId = 1; <span style="COLOR: green">//
Id and email passed from another tier<br /></span><span style="COLOR: blue">string</span> newEmail = <span style="COLOR: #a31515">"me@me.com"</span>;<span style="COLOR: green"><br /></span><span style="COLOR: blue">var</span> changedAccount = <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">Account</span>();<span style="COLOR: green"><br /></span>changedAccount.AccountId = myId;<span style="COLOR: green"><br /></span>changedAccount.Email = newEmail;<span style="COLOR: green"><br /></span><span style="COLOR: #2b91af">MembersDatabase</span>.Accounts.Update(changedAccount);<span style="COLOR: green"><br /><br />
// Delete<br /></span><span style="COLOR: blue">int</span> idToKill = 2; <span style="COLOR: green">//
Passed from another tier<br /></span><span style="COLOR: #2b91af">MembersDatabase</span>.Accounts.Delete(idToKill); </span>
        </p>
        <p>
That's about 40% less code. It’s far more straightforward, being a single block. 
</p>
        <p>
To start using this code, just drop DatabaseBase.cs into your project. It adds DatabaseBase
to System.Data.Linq. Then subclass as shown above, and you're on your way to LINQ
updating bliss. What do you think?
</p>
        <p>
          <a href="http://www.atrevido.net/blog/content/binary/DatabaseBase.cs.txt">DatabaseBase.cs
(5.65 KB)</a>
          <br />
          <br />
P.S. At any rate, I should get points for the Zelda pun, right? 
</p>
        <p>
          <strong>Update:</strong> I forgot to mention, you'll want to turn UpdateCheck to Never
on your columns in the LINQ-to-SQL designer. 
<br /><strong>Update:</strong> The code (including the Tuple class) for the .NET 3.5 RTM
release is here: <a href="http://www.atrevido.net/blog/2008/06/26/LINQ+To+The+CRUD+RTM.aspx">http://www.atrevido.net/blog/2008/06/26/LINQ+To+The+CRUD+RTM.aspx</a></p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=6f242348-42ca-4934-9c2e-ea2bd1103a02" />
      </body>
      <title>A LINQ to the CRUD</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,6f242348-42ca-4934-9c2e-ea2bd1103a02.aspx</guid>
      <link>http://www.atrevido.net/blog/2007/08/26/A+LINQ+To+The+CRUD.aspx</link>
      <pubDate>Sun, 26 Aug 2007 20:30:32 GMT</pubDate>
      <description>&lt;p&gt;
A question many people have run into is: How does CRUD fit into LINQ-to-SQL? While
LINQ-to-SQL (I'll abbreviate as DLINQ) provides a very fast and easy way for us to
start querying our data, it doesn't handle updates as beautifully. It is particularly
noticeable when you are doing multi-tier and hence cannot share a &lt;span style="FONT-FAMILY: Courier New"&gt;DataContext&lt;/span&gt;. 
&lt;/p&gt;
&lt;p&gt;
Let's consider an example database called "&lt;span style="FONT-FAMILY: Courier New"&gt;MembersDatabase&lt;/span&gt;"
which has a table called "&lt;span style="FONT-FAMILY: Courier New"&gt;Accounts&lt;/span&gt;". &lt;span style="FONT-FAMILY: Courier New"&gt;Accounts&lt;/span&gt; has
an &lt;span style="FONT-FAMILY: Courier New"&gt;int&lt;/span&gt; primary key, and a &lt;span style="FONT-FAMILY: Courier New"&gt;varchar&lt;/span&gt; &lt;span style="FONT-FAMILY: Courier New"&gt;Email&lt;/span&gt; field.
We use the DLINQ designer and create the dbml that generates a class called &lt;span style="FONT-FAMILY: Courier New"&gt;MembersDataContext&lt;/span&gt;.
How does our app-tier code look? I'll give you a hint, it starts with "ug" and rhymes
with "nasty": 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: green"&gt;// Select&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt; someId = 123; &lt;span style="COLOR: green"&gt;//
Passed from another tier&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: #2b91af"&gt;Account&lt;/span&gt; someAccount; &lt;span style="COLOR: green"&gt;//
Can't use implicit typing -- no anonymous types&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;using&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; dc
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;MembersDataContext&lt;/span&gt;())
{&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; someAccount = dc.Accounts.SingleOrDefault(a =&amp;gt; a.AccountId
== someId);&lt;span style="COLOR: green"&gt; 
&lt;br&gt;
&lt;/span&gt;}&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;br&gt;
// Insert&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; myAccount = &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Account&lt;/span&gt;();&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;myAccount.Email = &lt;span style="COLOR: #a31515"&gt;"me@contoso.com"&lt;/span&gt;;&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;using&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; dc
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;MembersDataContext&lt;/span&gt;())
{&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dc.Accounts.Add(myAccount);&lt;span style="COLOR: green"&gt;&amp;nbsp;&lt;br&gt;
&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dc.SubmitChanges();&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;}&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;br&gt;
// Update&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt; myId = 1; &lt;span style="COLOR: green"&gt;//
Id and email passed from another tier&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;string&lt;/span&gt; newEmail = &lt;span style="COLOR: #a31515"&gt;"cool@cool.com"&lt;/span&gt;;&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; changedAccount = &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Account&lt;/span&gt;();&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;changedAccount.AccountId = myId;&lt;span style="COLOR: green"&gt; 
&lt;br&gt;
&lt;/span&gt;changedAccount.Email = newEmail;&lt;span style="COLOR: green"&gt; 
&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;using&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; dc
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;MembersDataContext&lt;/span&gt;())
{&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dc.Accounts.Attach(changedAccount, &lt;span style="COLOR: blue"&gt;true&lt;/span&gt;);&lt;span style="COLOR: green"&gt;&amp;nbsp;&lt;br&gt;
&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dc.SubmitChanges();&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;}&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;br&gt;
// Delete&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt; idToKill = 2; &lt;span style="COLOR: green"&gt;//
Passed from another tier&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;using&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; dc
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;MembersDataContext&lt;/span&gt;())
{&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&lt;font color=#003300&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/font&gt;using&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; txScope
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; System.Transactions.&lt;span style="COLOR: #2b91af"&gt;TransactionScope&lt;/span&gt;())
{&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&lt;font color=#003300&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/font&gt;var&lt;/span&gt; acc
= dc.Accounts.SingleOrDefault(a =&amp;gt; a.AccountId == idToKill);&lt;span style="COLOR: green"&gt;&amp;nbsp;&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&lt;font color=#003300&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/font&gt;if&lt;/span&gt; (acc
== &lt;span style="COLOR: blue"&gt;null&lt;/span&gt;) &lt;span style="COLOR: blue"&gt;throw&lt;/span&gt; &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;ChangeConflictException&lt;/span&gt;(&lt;span style="COLOR: #a31515"&gt;"Row
not found."&lt;/span&gt;);&lt;span style="COLOR: green"&gt;&amp;nbsp;&lt;br&gt;
&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; dc.Accounts.Remove(acc);&lt;span style="COLOR: green"&gt;&amp;nbsp;&lt;br&gt;
&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; dc.SubmitChanges();&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; txScope.Complete();&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
It's not horrible; it's certainly better than anything before it. But, we can do better.
I created some helper classes to do so (see attached file). 
&lt;/p&gt;
&lt;p&gt;
First, &lt;span style="FONT-FAMILY: Courier New"&gt;DatabaseBase&amp;lt;TContext&amp;gt;&lt;/span&gt;.
This holds our tables, and provides &lt;span style="FONT-FAMILY: Courier New"&gt;DataContext&lt;/span&gt; helper
functions &lt;span style="FONT-FAMILY: Courier New"&gt;Use&lt;/span&gt; and &lt;span style="FONT-FAMILY: Courier New"&gt;Query&lt;/span&gt;.
Second, &lt;span style="FONT-FAMILY: Courier New"&gt;TableBase&amp;lt;TItem, TKey&amp;gt;&lt;/span&gt;.
This actually provides our CRUD methods. I don't think anyone is overly interested
in the implementation details (comment if I'm wrong), so here's how you declare your
CRUD types: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;class&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;MembersDatabase&lt;/span&gt; : &lt;span style="COLOR: #2b91af"&gt;DatabaseBase&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;MembersDataContext&lt;/span&gt;&amp;gt;&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;font color=#003300&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/font&gt;public&lt;/span&gt; &lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;readonly&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;TableBase&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Account&lt;/span&gt;, &lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&amp;gt;
Accounts&amp;nbsp;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; = CreateTable(dc =&amp;gt; dc.Accounts, a =&amp;gt;
a.AccountId); 
&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
That's it. 
&lt;/p&gt;
&lt;p&gt;
You create a new class to serve as your "database" class. All that's required here
is to inherit from &lt;span style="FONT-FAMILY: Courier New"&gt;DatabaseBase&lt;/span&gt;. 
&lt;/p&gt;
&lt;p&gt;
Next, for each table, simply create a new field via &lt;span style="FONT-FAMILY: Courier New"&gt;CreateTable&lt;/span&gt;.
The first parameter is a lambda function that selects the right table off the &lt;span style="FONT-FAMILY: Courier New"&gt;DataContext&lt;/span&gt;.
The second parameter is a lambda expression that selects the primary key. Not much
too it. 
&lt;/p&gt;
&lt;p&gt;
So, how does our previous chunk of code look with this small helper library? 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: green"&gt;// Select&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt; someId = 123; &lt;span style="COLOR: green"&gt;//
Passed from another tier&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; someAccount = &lt;span style="COLOR: #2b91af"&gt;MembersDatabase&lt;/span&gt;.Accounts.SelectByKey(someId);&lt;span style="COLOR: green"&gt; 
&lt;br&gt;
&lt;br&gt;
// Insert&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; myAccount = &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Account&lt;/span&gt;();&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;myAccount.Email = &lt;span style="COLOR: #a31515"&gt;"me@contoso.com"&lt;/span&gt;;&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: #2b91af"&gt;MembersDatabase&lt;/span&gt;.Accounts.Insert(myAccount);&lt;span style="COLOR: green"&gt; 
&lt;br&gt;
&lt;br&gt;
// Update&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt; myId = 1; &lt;span style="COLOR: green"&gt;//
Id and email passed from another tier&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;string&lt;/span&gt; newEmail = &lt;span style="COLOR: #a31515"&gt;"me@me.com"&lt;/span&gt;;&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; changedAccount = &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Account&lt;/span&gt;();&lt;span style="COLOR: green"&gt;
&lt;br&gt;
&lt;/span&gt;changedAccount.AccountId = myId;&lt;span style="COLOR: green"&gt; 
&lt;br&gt;
&lt;/span&gt;changedAccount.Email = newEmail;&lt;span style="COLOR: green"&gt; 
&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: #2b91af"&gt;MembersDatabase&lt;/span&gt;.Accounts.Update(changedAccount);&lt;span style="COLOR: green"&gt; 
&lt;br&gt;
&lt;br&gt;
// Delete&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt; idToKill = 2; &lt;span style="COLOR: green"&gt;//
Passed from another tier&lt;br&gt;
&lt;/span&gt;&lt;span style="COLOR: #2b91af"&gt;MembersDatabase&lt;/span&gt;.Accounts.Delete(idToKill); &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
That's about 40% less code. It’s far more straightforward, being a single block. 
&lt;/p&gt;
&lt;p&gt;
To start using this code, just drop DatabaseBase.cs into your project. It adds DatabaseBase
to System.Data.Linq. Then subclass as shown above, and you're on your way to LINQ
updating bliss. What do you think?
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.atrevido.net/blog/content/binary/DatabaseBase.cs.txt"&gt;DatabaseBase.cs
(5.65 KB)&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
P.S. At any rate, I should get points for the Zelda pun, right? 
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Update:&lt;/strong&gt; I forgot to mention, you'll want to turn UpdateCheck to Never
on your columns in the LINQ-to-SQL designer. 
&lt;br&gt;
&lt;strong&gt;Update:&lt;/strong&gt; The code (including the Tuple class) for the .NET 3.5 RTM
release is here: &lt;a href="http://www.atrevido.net/blog/2008/06/26/LINQ+To+The+CRUD+RTM.aspx"&gt;http://www.atrevido.net/blog/2008/06/26/LINQ+To+The+CRUD+RTM.aspx&lt;/a&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=6f242348-42ca-4934-9c2e-ea2bd1103a02" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,6f242348-42ca-4934-9c2e-ea2bd1103a02.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=8cbb0fb7-d2ec-4efd-8cbe-033d516b49e7</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,8cbb0fb7-d2ec-4efd-8cbe-033d516b49e7.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,8cbb0fb7-d2ec-4efd-8cbe-033d516b49e7.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=8cbb0fb7-d2ec-4efd-8cbe-033d516b49e7</wfw:commentRss>
      <slash:comments>5</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
What people do in their own time in the privacy of their homes is none of my business.
However, when they mess with reading documentation, then it crosses the line and becomes
annoying. How many times do VB developers need to be told that a null is "Nothing"?
Consider this snippet from <a href="http://msdn2.microsoft.com/en-us/library/ms152012.aspx">MSDN</a>:
</p>
        <p>
-------<br />
The <b>CreateUser</b> method will return a null reference (<b>Nothing</b> in Visual
Basic) if <span class="parameter">password</span> is an empty string or a null reference
(<b>Nothing</b> in Visual Basic), <span class="parameter">username</span> is an empty
string or a null reference (<b>Nothing</b> in Visual Basic) or contains a comma (,), <span class="parameter">passwordQuestion</span> is
not a null reference (<b>Nothing</b> in Visual Basic) and contains an empty string,
or <span class="parameter">passwordAnswer</span> is not a null reference (<b>Nothing</b> in
Visual Basic) and contains an empty string.<br />
-------
</p>
        <p>
Five times in one paragraph! I know null type systems are annoying and lead to errors,
but that seems a bit excessive. Seriously though, it'd make more sense to make
VB developers learn a few words once, rather than having to mess up documentation
just in case they get confused. 
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=8cbb0fb7-d2ec-4efd-8cbe-033d516b49e7" />
      </body>
      <title>Reason #52 against Visual Basic (Nothing in Visual Basic)</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,8cbb0fb7-d2ec-4efd-8cbe-033d516b49e7.aspx</guid>
      <link>http://www.atrevido.net/blog/2007/08/22/Reason+52+Against+Visual+Basic+Nothing+In+Visual+Basic.aspx</link>
      <pubDate>Wed, 22 Aug 2007 14:49:34 GMT</pubDate>
      <description>&lt;p&gt;
What people do in their own time in the privacy of their homes is none of my business.
However, when they mess with reading documentation, then it crosses the line and becomes
annoying. How many times do VB developers need to be told that a null is "Nothing"?
Consider this snippet from &lt;a href="http://msdn2.microsoft.com/en-us/library/ms152012.aspx"&gt;MSDN&lt;/a&gt;:
&lt;/p&gt;
&lt;p&gt;
-------&lt;br&gt;
The &lt;b&gt;CreateUser&lt;/b&gt; method will return a null reference (&lt;b&gt;Nothing&lt;/b&gt; in Visual
Basic) if &lt;span class=parameter&gt;password&lt;/span&gt; is an empty string or a null reference
(&lt;b&gt;Nothing&lt;/b&gt; in Visual Basic), &lt;span class=parameter&gt;username&lt;/span&gt; is an empty
string or a null reference (&lt;b&gt;Nothing&lt;/b&gt; in Visual Basic) or contains a comma (,), &lt;span class=parameter&gt;passwordQuestion&lt;/span&gt; is
not a null reference (&lt;b&gt;Nothing&lt;/b&gt; in Visual Basic) and contains an empty string,
or &lt;span class=parameter&gt;passwordAnswer&lt;/span&gt; is not a null reference (&lt;b&gt;Nothing&lt;/b&gt; in
Visual Basic) and contains an empty string.&lt;br&gt;
-------
&lt;/p&gt;
&lt;p&gt;
Five times in one paragraph! I know null type systems are annoying and lead to errors,
but that seems a bit excessive.&amp;nbsp;Seriously though, it'd make more sense to make
VB developers learn a few words once, rather than having to mess up documentation
just in case they get confused. 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=8cbb0fb7-d2ec-4efd-8cbe-033d516b49e7" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,8cbb0fb7-d2ec-4efd-8cbe-033d516b49e7.aspx</comments>
      <category>Code</category>
      <category>Humour</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=5f132cb3-cb04-47ea-9ddb-5cd85e4b3b52</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,5f132cb3-cb04-47ea-9ddb-5cd85e4b3b52.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,5f132cb3-cb04-47ea-9ddb-5cd85e4b3b52.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=5f132cb3-cb04-47ea-9ddb-5cd85e4b3b52</wfw:commentRss>
      <slash:comments>21</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Be sure to read these first two articles: 
</p>
        <p>
    <a href="http://www.atrevido.net/blog/2007/08/12/Practical+Functional+C+Part+I.aspx">Practical
Functional C# - Part I</a></p>
        <p>
    <a href="http://www.atrevido.net/blog/2007/08/13/Practical+Functional+C+Part+II.aspx">Practical
Functional C# - Part II</a></p>
        <p>
OK let's start with a quick challenge. Write an accurate description of the following
program, in English: 
</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>
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">   
string</span> output = <span style="COLOR: #a31515">""</span>;<br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>if</span> (args.Length
&gt; 0) output = args[0]; <br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>if</span> (args.Length
&gt; 1) {<br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>    </span></span>for</span> (<span style="COLOR: blue">int</span> i
= 1; i &lt; args.Length; i++) {<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span>output
+= <span style="COLOR: #a31515">", "</span> + args[i]; <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>    </span></span>}<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>}<br /><span style="COLOR: #2b91af"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>Console</span>.WriteLine(output); 
<br />
} </span>
        </p>
        <p>
Well? The specification might be something like "a program that writes its arguments
separated by a comma and space". But how quickly could you determine that from the
code? How much additional time does it take to determine there aren't any bugs? Every
time a maintenance developer comes across this code, they have to analyze this code,
determine the boundary conditions correctly, verify the indexing, and so on. Every
time someone reads this code, she must pay a high tax. The saddest part is that this
is an extremely common pattern. 
</p>
        <p>
Edit: As Chad Hower pointed out in the comments that you can remove the two if statements
by performing a check inside the loop. That shortens it considerably and reduces some
of the "tax" that has to be paid when you read it.
</p>
        <p>
"Take this set of values and aggregate them into a single value". How many pieces
of code do exactly this, but obscure it behind a <span style="FONT-FAMILY: Courier New">for</span> loop?
Functional languages realize this and provide functions called "<span style="FONT-FAMILY: Courier New">Fold</span>"
or "<span style="FONT-FAMILY: Courier New">Reduce</span>". Such functions take an
accumulator function, apply it to every element in the list, then return the accumulator
value when finished. C# 3.0, courtesy of LINQ, provides an equivalent function, called
"Aggregate": 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">
            <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="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>string</span> output
= args.DefaultIfEmpty(<font color="#a31515">""</font>).Aggregate(<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span>(accum,
item) =&gt; accum += <span style="COLOR: #a31515">", "</span> + item); <br /><span style="COLOR: #2b91af"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>Console</span>.WriteLine(output); 
<br />
} </span>
        </p>
        <p>
Here we are saying that we are going to aggregate <span style="FONT-FAMILY: Courier New">args</span> into
a single string value. The lambda on the second line takes two arguments. The first
is the accumulator and <span style="FONT-FAMILY: Courier New">Aggregate</span> passes
it to each element ("threads" it through). The second parameter is the current item
we are working with. The return value of our lambda is simply the concatenation of
the current accumulated value, comma and space, and the current item. This return
value becomes the accumulator for the next item. On the first execution, since we
did not give it an explicit seed value, it just uses the first item. The final return
value becomes the value that <span style="FONT-FAMILY: Courier New">Aggregate</span> returns
to <span style="FONT-FAMILY: Courier New">output</span>. (Edited: Added DefaultIfEmpty
-- this overload of Aggregate doesn't work on empty sequences.) Using the lambda
provides nicer syntax than this equivalent code: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Consolas">
            <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: Consolas">{ <br /></span>
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: blue">
              <span style="FONT-FAMILY: Courier New">
                <span style="COLOR: blue">    </span>
              </span>string</span> output
= args.DefaultIfEmpty(<font color="#a31515">""</font>).Aggregate(joinCommaSpace); <br /></span>
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: #2b91af">
              <span style="FONT-FAMILY: Courier New">
                <span style="COLOR: blue">    </span>
              </span>Console</span>.WriteLine(output); 
<br /></span>
          <span style="FONT-FAMILY: Consolas">} 
<br /></span>
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: blue">static</span>
            <span style="COLOR: blue">string</span> joinCommaSpace(<span style="COLOR: blue">string</span> a, <span style="COLOR: blue">string</span> b) 
<br /></span>
          <span style="FONT-FAMILY: Consolas">{ <br /></span>
          <span style="FONT-FAMILY: Consolas">
            <span style="COLOR: blue">
              <span style="FONT-FAMILY: Courier New">
                <span style="COLOR: blue">    </span>
              </span>return</span> a
+ <span style="COLOR: #a31515">", "</span> + b; 
<br /></span>
          <span style="FONT-FAMILY: Consolas">} </span>
        </p>
        <p>
So why is this a good thing? Well, it goes back to the questions about the first set
of code: how much effort is required to determine intent and correctness of a particular
piece of code? In the imperative way, we need eight lines of code, with three distinct
paths. Using a functional approach, we have three lines of code and only one code
path. The only serious objection that I've heard is that this code is "unfamiliar".
Well, sure, anything new might be unfamiliar, but that does not make it bad. 
</p>
        <p>
You wouldn't write your SQL code to make someone only familiar with C "comfortable"
or "familiar", would you? You wouldn't write in C# the same way you'd write in C or
BASIC. So why stick with outdated programming practices just because some "new" developer
might get confused? Functional code is more concise, less error prone, and much more
readable. Learning this style might take a couple of days, but it's an invaluable
skill. At any rate, LINQ is built upon these concepts, so it will do people good to
learn anyways. 
</p>
        <p>
Now, let's examine how to create our own functions to hide loops. This time, we're
going to look at data access. A very common pattern in data access is creating a <span style="FONT-FAMILY: Courier New">SqlDataReader</span>,
going through it, adding elements to a list. Like other patterns, overhead obscures
the intent: 
</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">List</span>&lt;<span style="COLOR: #2b91af">Person</span>&gt;
GetAllPeople()<br />
{<br /><span style="COLOR: green"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>//
Setup command</span><br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>var</span> comm
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">SqlCommand</span>(<span style="COLOR: #a31515">"GetAllPeople"</span>);<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>comm.CommandType
= <span style="COLOR: #2b91af">CommandType</span>.StoredProcedure;<br /><br /><span style="COLOR: green"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>//
Setup connection</span><br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>using</span> (<span style="COLOR: blue">var</span> conn
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">SqlConnection</span>(<span style="COLOR: #2b91af">Settings</span>.ConnectionString))
{<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span>comm.Connection
= conn; <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>    </span></span>conn.Open();<br /><br /><span style="COLOR: green"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>    </span></span>//
Loop and add people to our list</span><br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>    </span></span>using</span> (<span style="COLOR: blue">var</span> reader
= comm.ExecuteReader()) {<br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>    </span></span>    </span></span>var</span> people
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">List</span>&lt;<span style="COLOR: #2b91af">Person</span>&gt;();<br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span>while</span> (reader.Read())
{<br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span></span></span>var</span> p
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">Person</span>();<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span></span></span>p.Name
= reader.GetString(0); <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span></span></span>p.Age
= reader.GetInt32(1); <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span></span></span>people.Add(p); <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span>}<br /><span style="COLOR: green"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span>//
Done</span><br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span>return</span> people; <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span>}<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>}<br />
} </span>
        </p>
        <p>
Yes, something as simple as reading a list of two-field type can take 14 lines of
code. Let's do something about that. The only unique part is where we create a <span style="FONT-FAMILY: Courier New">Person</span> from
the <span style="FONT-FAMILY: Courier New">SqlDataReader</span>. Outside of that,
it's a very straightforward, but large, pattern. Refactoring the pattern, we get this: 
</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">List</span>&lt;T&gt;
ListFromReader&lt;T&gt;(<span style="COLOR: blue">string</span> connectionString, 
<br /><span style="COLOR: #2b91af">SqlCommand</span> command, <span style="COLOR: #2b91af">Func</span>&lt;<span style="COLOR: #2b91af">SqlDataReader</span>,
T&gt; code) 
<br />
{<br /><span style="COLOR: green"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>//
Setup connection</span><br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>using</span> (<span style="COLOR: blue">var</span> conn
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">SqlConnection</span>(connectionString))
{<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span>command.Connection
= conn; <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>    </span></span>conn.Open();<br /><br /><span style="COLOR: green"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span>//
Loop into list</span><br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span>using</span> (<span style="COLOR: blue">var</span> reader
= command.ExecuteReader()) {<br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span>var</span> list
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">List</span>&lt;T&gt;();<br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span>while</span> (reader.Read())
{<br /><span style="COLOR: green"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span></span></span>//
Here we call the supplied code to add the right item</span><br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span></span></span>T
item = code(reader); <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span></span></span>list.Add(item); <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span>}<br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span>return</span> list; <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>    </span></span>}<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>}<br />
} </span>
        </p>
        <p>
Now our code to <span style="FONT-FAMILY: Courier New">GetAllPeople</span> is very
simple: 
</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">List</span>&lt;<span style="COLOR: #2b91af">Person</span>&gt;
GetAllPeople2()<br />
{<br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>var</span> comm
= <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">SqlCommand</span>(<span style="COLOR: #a31515">"GetAllPeople"</span>);<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>comm.CommandType
= <span style="COLOR: #2b91af">CommandType</span>.StoredProcedure;<br /><br /><span style="COLOR: blue"><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span>return</span> ListFromReader(<span style="COLOR: #2b91af">Settings</span>.ConnectionString,
comm, <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span>reader
=&gt; <span style="COLOR: blue">new</span><span style="COLOR: #2b91af">Person</span> {<br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span>Name
= reader.GetString(0), <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span></span></span>Age
= reader.GetInt32(1) <br /><span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    <span style="FONT-FAMILY: Courier New"><span style="COLOR: blue">    </span></span></span></span>});<br />
} </span>
        </p>
        <p>
Just be looking at this code, we know all the data-API stuff is handled correctly.
This approach is vastly superior to other common SQL "helpers", for example, an <span style="FONT-FAMILY: Courier New">ExecuteReader</span> method
that gives us a <span style="FONT-FAMILY: Courier New">SqlDataReader</span>. First,
we have no locals that need disposing or other cleanup: this function scopes the variables
to our lambda. Second, we can focus on our actual logic (creating a <span style="FONT-FAMILY: Courier New">Person</span>)
rather than dealing with loop conditions. 
</p>
        <p>
Edit: This is not specific to C# 3.0! You can definately achieve a lot of the same
benefits in 2.0, except you need to replace the simple lambda syntax ( <font face="Courier New">=&gt; </font>)
with the much more verbose <font face="Courier New">delegate (ArgType arg) { }</font> (anonymous
method) syntax. C# 3.0 just makes it much easier to write. 
</p>
        <p>
What other common loops do you encounter? I have a few more we'll cover in the next
article. As always, comments, insults and suggestions are welcome.
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=5f132cb3-cb04-47ea-9ddb-5cd85e4b3b52" />
      </body>
      <title>Practical Functional C# - Part III – Loops are Evil</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,5f132cb3-cb04-47ea-9ddb-5cd85e4b3b52.aspx</guid>
      <link>http://www.atrevido.net/blog/2007/08/16/Practical+Functional+C+Part+III+Loops+Are+Evil.aspx</link>
      <pubDate>Thu, 16 Aug 2007 16:36:01 GMT</pubDate>
      <description>&lt;p&gt;
Be sure to read these first two articles: 
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://www.atrevido.net/blog/2007/08/12/Practical+Functional+C+Part+I.aspx"&gt;Practical
Functional C# - Part I&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://www.atrevido.net/blog/2007/08/13/Practical+Functional+C+Part+II.aspx"&gt;Practical
Functional C# - Part II&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
OK let's start with a quick challenge. Write an accurate description of the following
program, in English: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;void&lt;/span&gt; Main(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt;[]
args)&lt;br&gt;
{ 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
string&lt;/span&gt; output = &lt;span style="COLOR: #a31515"&gt;""&lt;/span&gt;;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;if&lt;/span&gt; (args.Length
&amp;gt; 0) output = args[0];&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;if&lt;/span&gt; (args.Length
&amp;gt; 1) {&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;for&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;int&lt;/span&gt; i
= 1; i &amp;lt; args.Length; i++) {&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;output
+= &lt;span style="COLOR: #a31515"&gt;", "&lt;/span&gt; + args[i];&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;}&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;}&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;Console&lt;/span&gt;.WriteLine(output); 
&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Well? The specification might be something like "a program that writes its arguments
separated by a comma and space". But how quickly could you determine that from the
code? How much additional time does it take to determine there aren't any bugs? Every
time a maintenance developer comes across this code, they have to analyze this code,
determine the boundary conditions correctly, verify the indexing, and so on. Every
time someone reads this code, she must pay a high tax. The saddest part is that this
is an extremely common pattern. 
&lt;/p&gt;
&lt;p&gt;
Edit: As Chad Hower pointed out in the comments that you can remove the two if statements
by performing a check inside the loop. That shortens it considerably and reduces some
of the "tax" that has to be paid when you read it.
&lt;/p&gt;
&lt;p&gt;
"Take this set of values and aggregate them into a single value". How many pieces
of code do exactly this, but obscure it behind a &lt;span style="FONT-FAMILY: Courier New"&gt;for&lt;/span&gt; loop?
Functional languages realize this and provide functions called "&lt;span style="FONT-FAMILY: Courier New"&gt;Fold&lt;/span&gt;"
or "&lt;span style="FONT-FAMILY: Courier New"&gt;Reduce&lt;/span&gt;". Such functions take an
accumulator function, apply it to every element in the list, then return the accumulator
value when finished. C# 3.0, courtesy of LINQ, provides an equivalent function, called
"Aggregate": 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;void&lt;/span&gt; Main(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt;[]
args)&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;string&lt;/span&gt; output
= args.DefaultIfEmpty(&lt;font color=#a31515&gt;""&lt;/font&gt;).Aggregate(&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;(accum,
item) =&amp;gt; accum += &lt;span style="COLOR: #a31515"&gt;", "&lt;/span&gt; + item);&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;Console&lt;/span&gt;.WriteLine(output); 
&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Here we are saying that we are going to aggregate &lt;span style="FONT-FAMILY: Courier New"&gt;args&lt;/span&gt; into
a single string value. The lambda on the second line takes two arguments. The first
is the accumulator and &lt;span style="FONT-FAMILY: Courier New"&gt;Aggregate&lt;/span&gt; passes
it to each element ("threads" it through). The second parameter is the current item
we are working with. The return value of our lambda is simply the concatenation of
the current accumulated value, comma and space, and the current item. This return
value becomes the accumulator for the next item. On the first execution, since we
did not give it an explicit seed value, it just uses the first item. The final return
value becomes the value that &lt;span style="FONT-FAMILY: Courier New"&gt;Aggregate&lt;/span&gt; returns
to &lt;span style="FONT-FAMILY: Courier New"&gt;output&lt;/span&gt;. (Edited: Added DefaultIfEmpty
-- this overload of Aggregate&amp;nbsp;doesn't work on empty sequences.) Using the lambda
provides nicer syntax than this equivalent code: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;void&lt;/span&gt; Main(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt;[]
args) 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Consolas"&gt;{&amp;nbsp;&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;string&lt;/span&gt; output
= args.DefaultIfEmpty(&lt;font color=#a31515&gt;""&lt;/font&gt;).Aggregate(joinCommaSpace);&amp;nbsp;&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: #2b91af"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;Console&lt;/span&gt;.WriteLine(output); 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Consolas"&gt;} 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: blue"&gt;string&lt;/span&gt; joinCommaSpace(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt; a, &lt;span style="COLOR: blue"&gt;string&lt;/span&gt; b) 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Consolas"&gt;{&amp;nbsp;&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;return&lt;/span&gt; a
+ &lt;span style="COLOR: #a31515"&gt;", "&lt;/span&gt; + b; 
&lt;br&gt;
&lt;/span&gt;&lt;span style="FONT-FAMILY: Consolas"&gt;} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
So why is this a good thing? Well, it goes back to the questions about the first set
of code: how much effort is required to determine intent and correctness of a particular
piece of code? In the imperative way, we need eight lines of code, with three distinct
paths. Using a functional approach, we have three lines of code and only one code
path. The only serious objection that I've heard is that this code is "unfamiliar".
Well, sure, anything new might be unfamiliar, but that does not make it bad. 
&lt;/p&gt;
&lt;p&gt;
You wouldn't write your SQL code to make someone only familiar with C "comfortable"
or "familiar", would you? You wouldn't write in C# the same way you'd write in C or
BASIC. So why stick with outdated programming practices just because some "new" developer
might get confused? Functional code is more concise, less error prone, and much more
readable. Learning this style might take a couple of days, but it's an invaluable
skill. At any rate, LINQ is built upon these concepts, so it will do people good to
learn anyways. 
&lt;/p&gt;
&lt;p&gt;
Now, let's examine how to create our own functions to hide loops. This time, we're
going to look at data access. A very common pattern in data access is creating a &lt;span style="FONT-FAMILY: Courier New"&gt;SqlDataReader&lt;/span&gt;,
going through it, adding elements to a list. Like other patterns, overhead obscures
the intent: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;public&lt;/span&gt; &lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Person&lt;/span&gt;&amp;gt;
GetAllPeople()&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: green"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;//
Setup command&lt;/span&gt;
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;var&lt;/span&gt; comm
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;SqlCommand&lt;/span&gt;(&lt;span style="COLOR: #a31515"&gt;"GetAllPeople"&lt;/span&gt;);&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;comm.CommandType
= &lt;span style="COLOR: #2b91af"&gt;CommandType&lt;/span&gt;.StoredProcedure;&lt;br&gt;
&lt;br&gt;
&lt;span style="COLOR: green"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;//
Setup connection&lt;/span&gt;
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;using&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; conn
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;SqlConnection&lt;/span&gt;(&lt;span style="COLOR: #2b91af"&gt;Settings&lt;/span&gt;.ConnectionString))
{&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;comm.Connection
= conn;&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;conn.Open();&lt;br&gt;
&lt;br&gt;
&lt;span style="COLOR: green"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;//
Loop and add people to our list&lt;/span&gt;
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;using&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; reader
= comm.ExecuteReader()) {&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;var&lt;/span&gt; people
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Person&lt;/span&gt;&amp;gt;();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;while&lt;/span&gt; (reader.Read())
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;var&lt;/span&gt; p
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Person&lt;/span&gt;();&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;p.Name
= reader.GetString(0);&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;p.Age
= reader.GetInt32(1);&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;people.Add(p);&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;}&lt;br&gt;
&lt;span style="COLOR: green"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;//
Done&lt;/span&gt;
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;return&lt;/span&gt; people;&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;}&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;}&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Yes, something as simple as reading a list of two-field type can take 14 lines of
code. Let's do something about that. The only unique part is where we create a &lt;span style="FONT-FAMILY: Courier New"&gt;Person&lt;/span&gt; from
the &lt;span style="FONT-FAMILY: Courier New"&gt;SqlDataReader&lt;/span&gt;. Outside of that,
it's a very straightforward, but large, pattern. Refactoring the pattern, we get this: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;public&lt;/span&gt; &lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt;
ListFromReader&amp;lt;T&amp;gt;(&lt;span style="COLOR: blue"&gt;string&lt;/span&gt; connectionString, 
&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;SqlCommand&lt;/span&gt; command, &lt;span style="COLOR: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;SqlDataReader&lt;/span&gt;,
T&amp;gt; code) 
&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: green"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;//
Setup connection&lt;/span&gt;
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;using&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; conn
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;SqlConnection&lt;/span&gt;(connectionString))
{&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;command.Connection
= conn;&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;conn.Open();&lt;br&gt;
&lt;br&gt;
&lt;span style="COLOR: green"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;//
Loop into list&lt;/span&gt;
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;using&lt;/span&gt; (&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; reader
= command.ExecuteReader()) {&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;var&lt;/span&gt; list
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt;();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;while&lt;/span&gt; (reader.Read())
{&lt;br&gt;
&lt;span style="COLOR: green"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;//
Here we call the supplied code to add the right item&lt;/span&gt;
&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;T
item = code(reader);&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;list.Add(item);&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;}&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;return&lt;/span&gt; list;&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;}&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;}&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Now our code to &lt;span style="FONT-FAMILY: Courier New"&gt;GetAllPeople&lt;/span&gt; is very
simple: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Consolas"&gt;&lt;span style="COLOR: blue"&gt;public&lt;/span&gt; &lt;span style="COLOR: blue"&gt;static&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="COLOR: #2b91af"&gt;Person&lt;/span&gt;&amp;gt;
GetAllPeople2()&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;var&lt;/span&gt; comm
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;SqlCommand&lt;/span&gt;(&lt;span style="COLOR: #a31515"&gt;"GetAllPeople"&lt;/span&gt;);&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;comm.CommandType
= &lt;span style="COLOR: #2b91af"&gt;CommandType&lt;/span&gt;.StoredProcedure;&lt;br&gt;
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;return&lt;/span&gt; ListFromReader(&lt;span style="COLOR: #2b91af"&gt;Settings&lt;/span&gt;.ConnectionString,
comm,&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;reader
=&amp;gt; &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;Person&lt;/span&gt; {&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;Name
= reader.GetString(0),&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;Age
= reader.GetInt32(1)&amp;nbsp;&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;});&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Just be looking at this code, we know all the data-API stuff is handled correctly.
This approach is vastly superior to other common SQL "helpers", for example, an &lt;span style="FONT-FAMILY: Courier New"&gt;ExecuteReader&lt;/span&gt; method
that gives us a &lt;span style="FONT-FAMILY: Courier New"&gt;SqlDataReader&lt;/span&gt;. First,
we have no locals that need disposing or other cleanup: this function scopes the variables
to our lambda. Second, we can focus on our actual logic (creating a &lt;span style="FONT-FAMILY: Courier New"&gt;Person&lt;/span&gt;)
rather than dealing with loop conditions. 
&lt;/p&gt;
&lt;p&gt;
Edit: This is not specific to C# 3.0! You can definately achieve a lot of the same
benefits in 2.0, except you need to replace the simple lambda&amp;nbsp;syntax ( &lt;font face="Courier New"&gt;=&amp;gt; &lt;/font&gt;)
with the much more verbose &lt;font face="Courier New"&gt;delegate (ArgType arg) { }&lt;/font&gt; (anonymous
method) syntax. C# 3.0 just makes it much easier to write. 
&lt;/p&gt;
&lt;p&gt;
What other common loops do you encounter? I have a few more we'll cover in the next
article. As always, comments, insults and suggestions are welcome.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=5f132cb3-cb04-47ea-9ddb-5cd85e4b3b52" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,5f132cb3-cb04-47ea-9ddb-5cd85e4b3b52.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=77e5ea50-b8d6-4a21-b5a2-a0d814a86c4f</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,77e5ea50-b8d6-4a21-b5a2-a0d814a86c4f.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,77e5ea50-b8d6-4a21-b5a2-a0d814a86c4f.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=77e5ea50-b8d6-4a21-b5a2-a0d814a86c4f</wfw:commentRss>
      <slash:comments>8</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Previous article: <a href="http://www.atrevido.net/blog/2007/08/12/Practical+Functional+C+Part+I.aspx">Practical
Functional C# - Part I</a></p>
        <p>
Last time I demonstrated how to replicate the using keyword as a function that takes
a function. In this article, I'm going to show some real-world cases where you'll
see a major improvement by taking a more functional approach. I'm going to use WCF
as an example space. 
</p>
        <p>
WCF allows us to define services as normal C# interfaces. We then use a factory to
create a proxy for an interface, specifying the URI, binding types (HTTP, binary,
message queue), and other options. However, our interest is how this actually looks
from the client side; how we actually make calls. 
</p>
        <p>
Since a WCF call is actually invoking code on another machine, any number of bad things
can happen to our client channel, resulting in exceptions. When this happens, we have
to <span style="FONT-FAMILY: Courier New">Abort</span> the channel. But if things
complete successfully, we just need to <span style="FONT-FAMILY: Courier New">Close</span> the
channel. Of course, that's not easy enough: if the <span style="FONT-FAMILY: Courier New">Close</span> fails,
we then need to <span style="FONT-FAMILY: Courier New">Abort</span> the channel anyways.
Confused? Well, check out this code snippet that uses an interface called <span style="FONT-FAMILY: Courier New">ICalculator</span> to
add two numbers: 
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">void</span> WcfExample()<br />
{<br /><span style="COLOR: blue">    int</span> a = 1; <br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>int</span> b
= 2; <br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>int</span> sum; <br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>var</span> chanFactory
= GetCachedFactory&lt;<span style="COLOR: #2b91af">ICalculator</span>&gt;();<br /><span style="COLOR: #2b91af"><span style="COLOR: blue">    </span>ICalculator</span> calc
= chanFactory.CreateChannel();<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>bool</span> error
= <span style="COLOR: blue">true</span>; <br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>try</span> {<br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>sum
= calc.Add(a, b); <br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>((<span style="COLOR: #2b91af">IClientChannel</span>)calc).Close();<br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>error
= <span style="COLOR: blue">false</span>; <br /><span style="COLOR: blue">    </span>}<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>finally</span> {<br /><span style="COLOR: blue"><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>if</span> (error)
{<br /><span style="COLOR: blue">    <span style="COLOR: blue">    <span style="COLOR: blue">    </span></span></span>((<span style="COLOR: #2b91af">IClientChannel</span>)calc).Abort();<br /><span style="COLOR: blue">    </span><span style="COLOR: blue">    </span>}<br /><span style="COLOR: blue">    </span>}<br /><span style="COLOR: #2b91af"><span style="COLOR: blue">    </span>Console</span>.WriteLine(sum); 
<br />
} </span>
        </p>
        <p>
Ouch! Out of 17 lines of code, only five relate to our problem. The rest (70%) is
pure, ugly overhead. This is a much more complicated pattern than the <span style="FONT-FAMILY: Courier New">using</span> pattern,
and from experience, I can tell you it is error-prone. Fortunately, this pattern decomposes
nicely. The only two unique things are the name of the interface and the statement
that acts on the interface. Here is one way you might go about writing this generically:
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">TReturn UseService&lt;TChannel, TReturn&gt;(<span style="COLOR: #2b91af">Func</span>&lt;TChannel,
TReturn&gt; code)<br />
{<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>var</span> chanFactory
= GetCachedFactory&lt;TChannel&gt;();<br /><span style="COLOR: blue">    </span>TChannel channel = chanFactory.CreateChannel();<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>bool</span> error
= <span style="COLOR: blue">true</span>; <br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>try</span> {<br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>TReturn
result = code(channel); <br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>((<span style="COLOR: #2b91af">IClientChannel</span>)channel).Close();<br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>error
= <span style="COLOR: blue">false</span>; <br /><span style="COLOR: blue"><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>return</span> result; <br /><span style="COLOR: blue">    </span>}<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>finally</span> {<br /><span style="COLOR: blue"><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>if</span> (error)
{<br /><span style="COLOR: blue">    <span style="COLOR: blue">    <span style="COLOR: blue">    </span></span></span>((<span style="COLOR: #2b91af">IClientChannel</span>)channel).Abort();<br /><span style="COLOR: blue">    </span><span style="COLOR: blue">    </span>}<br /><span style="COLOR: blue">    </span>}<br />
} </span>
        </p>
        <p>
This is exactly like the previous code, but we've substituted <span style="FONT-FAMILY: Courier New">TChannel</span> and
a function parameter named <span style="FONT-FAMILY: Courier New">code</span> instead
of our actual types. The type of function we want is <span style="FONT-FAMILY: Courier New">Func&lt;TChannel,
TReturn&gt;</span>. You can think of this as saying: "transforms a <span style="FONT-FAMILY: Courier New">TChannel</span> into
a <span style="FONT-FAMILY: Courier New">TReturn</span>". Now, look at the beauty
this allows on the client side:
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">void</span> WcfExample2()<br />
{<br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>int</span> a
= 1; <br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>int</span> b
= 2; <br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>int</span> sum
= UseService((<span style="COLOR: #2b91af">ICalculator</span> calc) =&gt; <br /><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>calc.Add(a,
b)); <br /><span style="COLOR: #2b91af"><span style="COLOR: blue">    </span>Console</span>.WriteLine(sum); 
<br />
} </span>
        </p>
        <p>
Presto! Our overhead went from 12 lines to zero. If that didn't sell you on the power
of functions, I suggest finding another career. Now, there is a lambda there, but
all it is saying is "Here is a function that takes one parameter of type <span style="FONT-FAMILY: Courier New">ICalculator</span> and
returns the value of <span style="FONT-FAMILY: Courier New">Add(a, b)</span>." The
C# compiler automatically infers the return type (<span style="FONT-FAMILY: Courier New">int</span>). 
</p>
        <p>
Some of you mentioned still using C# 2.0. Two things: First, you can use the 3.0 compiler
and run on 2.0 because these examples don't reference any new assemblies. Second,
you can achieve the same thing using anonymous methods, but they just look a bit uglier:
</p>
        <p style="BACKGROUND: #eeece1">
          <span style="FONT-FAMILY: Courier New">
            <span style="COLOR: blue">void</span> WcfExample3()<br />
{<br /><span style="COLOR: green"><span style="COLOR: blue">    </span>//
C# 2.0 example with anonymous methods</span><br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>int</span> a
= 1; <br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>int</span> b
= 2; <br /><span style="COLOR: blue"><span style="COLOR: blue">    </span>int</span> sum
= UseService&lt;<span style="COLOR: #2b91af">ICalculator<font color="#000000">,</font><font color="#0000ff">int&gt;</font></span>(<span style="COLOR: blue">delegate</span>(<span style="COLOR: #2b91af">ICalculator</span> calc)
{<br /><span style="COLOR: blue"><span style="COLOR: blue">    <span style="COLOR: blue">    </span></span>return</span> calc.Add(a,
b); <br /><span style="COLOR: blue">    </span>});<br /><span style="COLOR: #2b91af"><span style="COLOR: blue">    </span>Console</span>.WriteLine(sum);<br />
} </span>
        </p>
        <p>
By this time, I hope you are thinking about places in your code where you can extract
a larger pattern and use functions instead. The key concept to understand here is
that your source code should reflect your solution. You should not have extra code
sitting around just for the sake of appeasing the platform or meeting some "design
pattern". Let the platform and libraries take care of the details, and let your code
focus on actually solving problems. As always, I welcome your comments, suggestions,
and insults, so please let me know what you think! 
</p>
        <p>
Next up, we'll take a look at loops, see why they are harmful, and then go about fixing
them. 
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=77e5ea50-b8d6-4a21-b5a2-a0d814a86c4f" />
      </body>
      <title>Practical Functional C# - Part II</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,77e5ea50-b8d6-4a21-b5a2-a0d814a86c4f.aspx</guid>
      <link>http://www.atrevido.net/blog/2007/08/13/Practical+Functional+C+Part+II.aspx</link>
      <pubDate>Mon, 13 Aug 2007 23:07:26 GMT</pubDate>
      <description>&lt;p&gt;
Previous article: &lt;a href="http://www.atrevido.net/blog/2007/08/12/Practical+Functional+C+Part+I.aspx"&gt;Practical
Functional C# - Part I&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Last time I demonstrated how to replicate the using keyword as a function that takes
a function. In this article, I'm going to show some real-world cases where you'll
see a major improvement by taking a more functional approach. I'm going to use WCF
as an example space. 
&lt;/p&gt;
&lt;p&gt;
WCF allows us to define services as normal C# interfaces. We then use a factory to
create a proxy for an interface, specifying the URI, binding types (HTTP, binary,
message queue), and other options. However, our interest is how this actually looks
from the client side; how we actually make calls. 
&lt;/p&gt;
&lt;p&gt;
Since a WCF call is actually invoking code on another machine, any number of bad things
can happen to our client channel, resulting in exceptions. When this happens, we have
to &lt;span style="FONT-FAMILY: Courier New"&gt;Abort&lt;/span&gt; the channel. But if things
complete successfully, we just need to &lt;span style="FONT-FAMILY: Courier New"&gt;Close&lt;/span&gt; the
channel. Of course, that's not easy enough: if the &lt;span style="FONT-FAMILY: Courier New"&gt;Close&lt;/span&gt; fails,
we then need to &lt;span style="FONT-FAMILY: Courier New"&gt;Abort&lt;/span&gt; the channel anyways.
Confused? Well, check out this code snippet that uses an interface called &lt;span style="FONT-FAMILY: Courier New"&gt;ICalculator&lt;/span&gt; to
add two numbers: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;void&lt;/span&gt; WcfExample()&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; int&lt;/span&gt; a = 1;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;int&lt;/span&gt; b
= 2;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;int&lt;/span&gt; sum;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;var&lt;/span&gt; chanFactory
= GetCachedFactory&amp;lt;&lt;span style="COLOR: #2b91af"&gt;ICalculator&lt;/span&gt;&amp;gt;();&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;ICalculator&lt;/span&gt; calc
= chanFactory.CreateChannel();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;bool&lt;/span&gt; error
= &lt;span style="COLOR: blue"&gt;true&lt;/span&gt;;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;try&lt;/span&gt; {&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;sum
= calc.Add(a, b);&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;((&lt;span style="COLOR: #2b91af"&gt;IClientChannel&lt;/span&gt;)calc).Close();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;error
= &lt;span style="COLOR: blue"&gt;false&lt;/span&gt;;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;finally&lt;/span&gt; {&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;if&lt;/span&gt; (error)
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;((&lt;span style="COLOR: #2b91af"&gt;IClientChannel&lt;/span&gt;)calc).Abort();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;Console&lt;/span&gt;.WriteLine(sum); 
&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Ouch! Out of 17 lines of code, only five relate to our problem. The rest (70%) is
pure, ugly overhead. This is a much more complicated pattern than the &lt;span style="FONT-FAMILY: Courier New"&gt;using&lt;/span&gt; pattern,
and from experience, I can tell you it is error-prone. Fortunately, this pattern decomposes
nicely. The only two unique things are the name of the interface and the statement
that acts on the interface. Here is one way you might go about writing this generically:
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;TReturn UseService&amp;lt;TChannel, TReturn&amp;gt;(&lt;span style="COLOR: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TChannel,
TReturn&amp;gt; code)&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;var&lt;/span&gt; chanFactory
= GetCachedFactory&amp;lt;TChannel&amp;gt;();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;TChannel channel = chanFactory.CreateChannel();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;bool&lt;/span&gt; error
= &lt;span style="COLOR: blue"&gt;true&lt;/span&gt;;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;try&lt;/span&gt; {&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;TReturn
result = code(channel);&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;((&lt;span style="COLOR: #2b91af"&gt;IClientChannel&lt;/span&gt;)channel).Close();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;error
= &lt;span style="COLOR: blue"&gt;false&lt;/span&gt;;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;return&lt;/span&gt; result;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;finally&lt;/span&gt; {&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;if&lt;/span&gt; (error)
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;&lt;/span&gt;((&lt;span style="COLOR: #2b91af"&gt;IClientChannel&lt;/span&gt;)channel).Abort();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
This is exactly like the previous code, but we've substituted &lt;span style="FONT-FAMILY: Courier New"&gt;TChannel&lt;/span&gt; and
a function parameter named &lt;span style="FONT-FAMILY: Courier New"&gt;code&lt;/span&gt; instead
of our actual types. The type of function we want is &lt;span style="FONT-FAMILY: Courier New"&gt;Func&amp;lt;TChannel,
TReturn&amp;gt;&lt;/span&gt;. You can think of this as saying: "transforms a &lt;span style="FONT-FAMILY: Courier New"&gt;TChannel&lt;/span&gt; into
a &lt;span style="FONT-FAMILY: Courier New"&gt;TReturn&lt;/span&gt;". Now, look at the beauty
this allows on the client side:
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;void&lt;/span&gt; WcfExample2()&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;int&lt;/span&gt; a
= 1;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;int&lt;/span&gt; b
= 2;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;int&lt;/span&gt; sum
= UseService((&lt;span style="COLOR: #2b91af"&gt;ICalculator&lt;/span&gt; calc) =&amp;gt;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;calc.Add(a,
b));&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;Console&lt;/span&gt;.WriteLine(sum); 
&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Presto! Our overhead went from 12 lines to zero. If that didn't sell you on the power
of functions, I suggest finding another career. Now, there is a lambda there, but
all it is saying is "Here is a function that takes one parameter of type &lt;span style="FONT-FAMILY: Courier New"&gt;ICalculator&lt;/span&gt; and
returns the value of &lt;span style="FONT-FAMILY: Courier New"&gt;Add(a, b)&lt;/span&gt;." The
C# compiler automatically infers the return type (&lt;span style="FONT-FAMILY: Courier New"&gt;int&lt;/span&gt;). 
&lt;/p&gt;
&lt;p&gt;
Some of you mentioned still using C# 2.0. Two things: First, you can use the 3.0 compiler
and run on 2.0 because these examples don't reference any new assemblies. Second,
you can achieve the same thing using anonymous methods, but they just look a bit uglier:
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;void&lt;/span&gt; WcfExample3()&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: green"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;//
C# 2.0 example with anonymous methods&lt;/span&gt;
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;int&lt;/span&gt; a
= 1;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;int&lt;/span&gt; b
= 2;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;int&lt;/span&gt; sum
= UseService&amp;lt;&lt;span style="COLOR: #2b91af"&gt;ICalculator&lt;font color=#000000&gt;,&lt;/font&gt; &lt;font color=#0000ff&gt;int&amp;gt;&lt;/font&gt;&lt;/span&gt;(&lt;span style="COLOR: blue"&gt;delegate&lt;/span&gt;(&lt;span style="COLOR: #2b91af"&gt;ICalculator&lt;/span&gt; calc)
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;return&lt;/span&gt; calc.Add(a,
b);&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;});&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;Console&lt;/span&gt;.WriteLine(sum);&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
By this time, I hope you are thinking about places in your code where you can extract
a larger pattern and use functions instead. The key concept to understand here is
that your source code should reflect your solution. You should not have extra code
sitting around just for the sake of appeasing the platform or meeting some "design
pattern". Let the platform and libraries take care of the details, and let your code
focus on actually solving problems. As always, I welcome your comments, suggestions,
and insults, so please let me know what you think! 
&lt;/p&gt;
&lt;p&gt;
Next up, we'll take a look at loops, see why they are harmful, and then go about fixing
them. 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=77e5ea50-b8d6-4a21-b5a2-a0d814a86c4f" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,77e5ea50-b8d6-4a21-b5a2-a0d814a86c4f.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=d0dafcc7-5ed9-4ff8-8a48-b39a909af34a</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,d0dafcc7-5ed9-4ff8-8a48-b39a909af34a.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,d0dafcc7-5ed9-4ff8-8a48-b39a909af34a.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=d0dafcc7-5ed9-4ff8-8a48-b39a909af34a</wfw:commentRss>
      <slash:comments>5</slash:comments>
      <title>Practical Functional C# - Part I</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,d0dafcc7-5ed9-4ff8-8a48-b39a909af34a.aspx</guid>
      <link>http://www.atrevido.net/blog/2007/08/12/Practical+Functional+C+Part+I.aspx</link>
      <pubDate>Sun, 12 Aug 2007 23:21:32 GMT</pubDate>
      <description>&lt;p&gt;
Edit: This first article might be a bit dense&amp;nbsp;at times. However, I promise, if
you stick through and read at least until &lt;a href="http://www.atrevido.net/blog/2007/08/13/Practical+Functional+C+Part+II.aspx"&gt;Parts
II&lt;/a&gt; and &lt;a href="http://www.atrevido.net/blog/2007/08/16/Practical+Functional+C+Part+III+Loops+Are+Evil.aspx"&gt;III
(Loops are Evil)&lt;/a&gt; you will see major benefits that will totally transform your
code (even C# 2.0 code!). In fact, to the first&amp;nbsp;3 people that can show me that
these practices will NOT result in better code in many enterprise apps, I'll give
$100 each. Post a blog comment or email me (mgg AT telefinity dot com).&lt;br&gt;
&lt;br&gt;
Redundancy in source code is a common degeneration. But for the C# programmer, her
weapons to eliminate it have been unwieldy at best. She has been able to eliminate
simple, blocky, patterns, but truly writing reusable code at a fine level has not
been easy. 
&lt;/p&gt;
&lt;p&gt;
This series will demonstrate how you can take advantage of functional programming
(FP) in your work, today. The first task is to dispense with the notion that functional
programming is difficult and strange. Most FP articles start with a recursive definition
of the Fibonacci sequence and then talk about currying functions. Here, we're going
to start off with something that every C# programmer has used many times. I can guarantee
that after you absorb this series of articles, you'll be writing more concise, less
buggy, more powerful software. I've seen many C# modules get cut down drastically
in size. I've seen new C# code written that does multithreading and it was written
correctly on the first go. I want you to see these things too. 
&lt;/p&gt;
&lt;p&gt;
Refactoring out common blocks of code is familiar. Probably every developer has written
a helper method to initialize a database command or prepare a commonly used object.
Unfortunately, refactoring only tends to happen to &lt;em&gt;contiguous blocks&lt;/em&gt;. We
do not see refactoring of complex patterns that do not fit into neat blocks. Consider
the following visualizations of a program. The red blocks are the unique parts of
the program, and the grey ones represent common statements. 
&lt;/p&gt;
&lt;p&gt;
&lt;img alt="" src="http://www.atrevido.net/blog/content/binary/080307_1151_PracticalFu1.png"&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
becomes&lt;br&gt;
&lt;img alt="" src="http://www.atrevido.net/blog/content/binary/080307_1151_PracticalFu2.png"&gt; 
&lt;/p&gt;
&lt;p&gt;
It is easy to refactor the first sequence: move the common parts into another function
and call it. However, the second pattern poses quite a problem. The individual "common"
blocks are too simple to move into another method. The call to the refactor method
would be the same as the method itself! How can we refactor it correctly?&lt;br&gt;
&lt;br&gt;
Well, C# itself contains keywords that refactor some of these patterns. Consider the &lt;span style="FONT-FAMILY: Courier New"&gt;using&lt;/span&gt; keyword.
The following two methods are nearly equivalent: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;void&lt;/span&gt; usingPatternExample()&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; string&lt;/span&gt; result;&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;StreamReader&lt;/span&gt; sr
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;StreamReader&lt;/span&gt;(filename);&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;try&lt;/span&gt; {&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;result
= sr.ReadToEnd();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;finally&lt;/span&gt; {&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;if&lt;/span&gt; (sr
!= &lt;span style="COLOR: blue"&gt;null&lt;/span&gt;) sr.Dispose();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
}&lt;br&gt;
&lt;span style="COLOR: blue"&gt;
&lt;br&gt;
void&lt;/span&gt; usingKeywordExample()&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;string&lt;/span&gt; result;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;using&lt;/span&gt; (&lt;span style="COLOR: #2b91af"&gt;StreamReader&lt;/span&gt; sr
= &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;StreamReader&lt;/span&gt;(filename))
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;result
= sr.ReadToEnd();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;}&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
I think it is obvious why everyone uses the &lt;span style="FONT-FAMILY: Courier New"&gt;using&lt;/span&gt; keyword
over writing out this long init-try-something-finally-dispose pattern repeatedly.
When we read code that uses the &lt;span style="FONT-FAMILY: Courier New"&gt;using&lt;/span&gt; keyword,
the intent is instantly clear. We don't need to go validate the pattern to make sure
it does what we think it does, we can just see "&lt;span style="FONT-FAMILY: Courier New"&gt;using&lt;/span&gt;"
and know that it is correct. As an extra benefit, we can declare our disposable variable
inside the using scope, so that we don't accidentally use it after it is disposed. 
&lt;/p&gt;
&lt;p&gt;
This is all good and dandy, until we realize that we are stuck with the handful of
patterns defined as C# keywords! If I wanted to declare the variable result as an
output of the using statement, I'm out of luck. If I want to initialize multiple objects
in one using block, then that is just too bad. Part of the reason for this is that
it was extremely ugly to do this in C# before version 3.0. Consider this C# 1.0 example
to recreate the &lt;span style="FONT-FAMILY: Courier New"&gt;using&lt;/span&gt; keyword as a user-defined
function: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;delegate&lt;/span&gt; &lt;span style="COLOR: blue"&gt;void&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;UsingAction&lt;/span&gt;(&lt;span style="COLOR: #2b91af"&gt;IDisposable&lt;/span&gt; obj); 
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;void&lt;/span&gt; Using(&lt;span style="COLOR: #2b91af"&gt;IDisposable&lt;/span&gt; obj, &lt;span style="COLOR: #2b91af"&gt;UsingAction&lt;/span&gt; action) 
&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;try&lt;/span&gt; {
action(obj); }&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;finally&lt;/span&gt; { &lt;span style="COLOR: blue"&gt;if&lt;/span&gt; (obj
!= &lt;span style="COLOR: blue"&gt;null&lt;/span&gt;) obj.Dispose(); }&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
So far, so good – nothing ugly yet. The usage of this user-defined &lt;span style="FONT-FAMILY: Courier New"&gt;Using&lt;/span&gt; function
on the other hand: 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;string&lt;/span&gt; result; 
&lt;br&gt;
&lt;span style="COLOR: blue"&gt;void&lt;/span&gt; UsingExample1()&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/font&gt;&lt;/span&gt;Using(&lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;StreamReader&lt;/span&gt;(filename), &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;UsingAction&lt;/span&gt;(readIntoResult)); 
&lt;br&gt;
}&lt;br&gt;
&lt;span style="COLOR: blue"&gt;void&lt;/span&gt; readIntoResult(&lt;span style="COLOR: #2b91af"&gt;IDisposable&lt;/span&gt; obj) 
&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: #2b91af"&gt;&lt;span style="COLOR: blue"&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/font&gt;&lt;/span&gt;StreamReader&lt;/span&gt; sr
= (&lt;span style="COLOR: #2b91af"&gt;StreamReader&lt;/span&gt;)obj;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/font&gt;&lt;/span&gt;result
= sr.ReadToEnd();&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Atrocious! The pattern of the code is shattered and complicated to follow. The main
part of the code (getting the result) is forced to sit in a separate method many lines
away. We're required to use fields to pass data in or out. And just to top it off,
lack of generics forces a cast – we had to write &lt;span style="FONT-FAMILY: Courier New"&gt;StreamReader&lt;/span&gt; three
times. The utter syntax hides our intention. In short, it is completely unusable. 
&lt;/p&gt;
&lt;p&gt;
C# 2.0 makes some progress. First, we can change &lt;span style="FONT-FAMILY: Courier New"&gt;UsingAction&lt;/span&gt; to &lt;span style="FONT-FAMILY: Courier New"&gt;Action&amp;lt;T&amp;gt;&lt;/span&gt; and
allow the caller to specify the type. All that is needed&amp;nbsp;is a constraint on the
type to &lt;span style="FONT-FAMILY: Courier New"&gt;IDisposable&lt;/span&gt;. The new declaration
of &lt;span style="FONT-FAMILY: Courier New"&gt;Using&lt;/span&gt; looks like this:&lt;br&gt;
&lt;br&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue; BACKGROUND-COLOR: #eeece1"&gt;void&lt;/span&gt;&lt;span style="BACKGROUND-COLOR: #eeece1"&gt; Using&amp;lt;T&amp;gt;(T
obj, &lt;span style="COLOR: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt; action) &lt;span style="COLOR: blue"&gt;where&lt;/span&gt; T
: &lt;span style="COLOR: #2b91af"&gt;IDisposable&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; 
&lt;/p&gt;
&lt;p&gt;
This says that we need something of type "&lt;span style="FONT-FAMILY: Courier New"&gt;T&lt;/span&gt;",
and the only restriction is that &lt;span style="FONT-FAMILY: Courier New"&gt;T&lt;/span&gt; must
be a type that implements &lt;span style="FONT-FAMILY: Courier New"&gt;IDisposable&lt;/span&gt;.
Then, we want an &lt;span style="FONT-FAMILY: Courier New"&gt;Action&lt;/span&gt; that works on
that same type &lt;span style="FONT-FAMILY: Courier New"&gt;T&lt;/span&gt;, whatever it is. By
using &lt;span style="FONT-FAMILY: Courier New"&gt;T &lt;/span&gt;instead of a specific type,
we are essentially saying "we don't care about what type your object is; our function
works with all sorts of types". This is the source of the name "generics". Our code
is more generic; it's not tied to a specific type. Generics are an extremely important
tool for refactoring patterns because patterns occur across different types. 
&lt;/p&gt;
&lt;p&gt;
To clean up the calling code, C# 2.0 has a feature called anonymous methods. They
are exactly as they sound: methods without names. They can be declared inline, right
along with the rest of the code. Additionally, they "capture" local variables, making
it unnecessary to declare fields to pass data in and out. 
&lt;/p&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;span style="COLOR: blue"&gt;void&lt;/span&gt; UsingExample2()&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;string&lt;/span&gt; result;&amp;nbsp;&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;Using(&lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;StreamReader&lt;/span&gt;(filename), &lt;span style="COLOR: blue"&gt;delegate&lt;/span&gt;(&lt;span style="COLOR: #2b91af"&gt;StreamReader&lt;/span&gt; sr)
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;/span&gt;result
= sr.ReadToEnd();&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;});&lt;br&gt;
} &lt;/span&gt;
&lt;/p&gt;
&lt;p class=MsoNormal style="MARGIN: 0in 0in 10pt"&gt;
&lt;span style="FONT-SIZE: 10pt; COLOR: #003300; LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'"&gt;&lt;font face=Verdana&gt;What
a major improvement! C# 2 can &lt;em&gt;&lt;span style="FONT-FAMILY: 'Arial','sans-serif'"&gt;infer&lt;/span&gt;&lt;/em&gt;&lt;?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /&gt; the
type of T for Using, avoiding having to write Using&amp;lt;StreamReader&amp;gt;. Apart from
having to type StreamReader twice, this code is starting to approach the level of
clarity that the using keyword provides.&lt;o:p&gt;&lt;/o:p&gt;
&lt;/font&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p class=MsoNormal style="MARGIN: 0in 0in 10pt"&gt;
&lt;span style="FONT-SIZE: 10pt; COLOR: #003300; LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'"&gt;&lt;font face=Verdana&gt;C#
3.0 introduces &lt;em&gt;&lt;span style="FONT-FAMILY: 'Arial','sans-serif'"&gt;lambdas&lt;/span&gt;&lt;/em&gt;.
Now, that's usually a scary word from functional programming, but it's actually very
simple. For C#, it's just an easier way of writing anonymous methods. Instead of having
to write "&lt;font face="Courier New"&gt;delegate(ParamType paramName) { }&lt;/font&gt;", we can
just do "&lt;font face="Courier New"&gt;paramName =&amp;gt;&lt;/font&gt;". That's all there is to
it! Nothing scary at all. For example, if I want to write a lambda to add two numbers,
I’d write it like this:&lt;o:p&gt;&lt;/o:p&gt;
&lt;/font&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p class=MsoNormal style="BACKGROUND: #eeece1; MARGIN: 0in 0in 10pt; mso-background-themecolor: background2"&gt;
&lt;span style="FONT-SIZE: 10pt; COLOR: #2b91af; LINE-HEIGHT: 115%; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"&gt;Func&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"&gt;&lt;font color=#000000&gt;&amp;lt;&lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt;, &lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt;, &lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt;&amp;gt;
add = (&lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt; a, &lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt; b)
=&amp;gt; a + b;&lt;/font&gt;&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; COLOR: #003300; LINE-HEIGHT: 115%; FONT-FAMILY: 'Courier New'"&gt;
&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class=MsoNormal style="MARGIN: 0in 0in 10pt"&gt;
&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'; mso-no-proof: yes"&gt;&lt;font color=#000000&gt;The
part &lt;/font&gt;&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; COLOR: #2b91af; LINE-HEIGHT: 115%; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"&gt;Func&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"&gt;&lt;font color=#000000&gt;&amp;lt;&lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt;, &lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt;, &lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt;&amp;gt;&lt;/font&gt;&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'; mso-no-proof: yes"&gt;&lt;font color=#000000&gt; says
we have a function that takes two ints and returns an int. Next, we declare our two
integer parameters: &lt;/font&gt;&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"&gt;&lt;font color=#000000&gt;(&lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt; a, &lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt; b)&lt;/font&gt;&lt;/span&gt;&lt;font color=#000000&gt;&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'; mso-no-proof: yes"&gt;.
Then, we define the lambda body by using the &lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"&gt;=&amp;gt;&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'; mso-no-proof: yes"&gt; operator.
Our body consists only of “&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"&gt;a
+ b&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'; mso-no-proof: yes"&gt;”.
With lambdas, if we only have one statement, we don’t need to explicitly use braces
or the &lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"&gt;return&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'; mso-no-proof: yes"&gt; keyword.
Alternatively, we could have written it as: &lt;span style="mso-spacerun: yes"&gt;&amp;nbsp;&lt;/span&gt;
&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;&lt;/font&gt;
&lt;/p&gt;
&lt;p class=MsoNormal style="BACKGROUND: #eeece1; MARGIN: 0in 0in 10pt; mso-background-themecolor: background2"&gt;
&lt;font face="Courier New"&gt;&lt;span style="FONT-SIZE: 10pt; COLOR: #2b91af; LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'; mso-no-proof: yes"&gt;Func&lt;/span&gt;&lt;span style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'; mso-no-proof: yes"&gt;&lt;font color=#000000&gt;&amp;lt;&lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt;, &lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt;, &lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt;&amp;gt;
add = (&lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt; a, &lt;/font&gt;&lt;span style="COLOR: blue"&gt;int&lt;/span&gt;&lt;font color=#000000&gt; b)
=&amp;gt; { &lt;/font&gt;&lt;span style="COLOR: blue"&gt;return&lt;/span&gt;&lt;font color=#000000&gt; a + b;
};&lt;/font&gt;&lt;/span&gt;&lt;/font&gt;&lt;span style="FONT-SIZE: 10pt; COLOR: #003300; LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'"&gt;
&lt;o:p&gt;&lt;/o:p&gt;
&lt;/span&gt;
&lt;/p&gt;
&lt;p class=MsoNormal style="MARGIN: 0in 0in 10pt"&gt;
&lt;span style="FONT-SIZE: 10pt; COLOR: #003300; LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'"&gt;&lt;font face=Verdana&gt;Behind
the scenes, the compiler goes and creates a method and creates the Func delegate on
top of it. So, armed with this new syntax and power, let’s take another look at our
Using method:&lt;o:p&gt;&lt;/o:p&gt;
&lt;/font&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;div&gt;
&lt;table style="BACKGROUND: #eeece1; BORDER-COLLAPSE: collapse" border=0&gt;
&lt;colgroup&gt;
&lt;col style="WIDTH: 320px"&gt;
&lt;col style="WIDTH: 350px"&gt;
&lt;/colgroup&gt;
&lt;tbody valign=top&gt;
&lt;tr&gt;
&lt;td style="BORDER-RIGHT: black 0.5pt solid; PADDING-RIGHT: 7px; BORDER-TOP: black 0.5pt solid; PADDING-LEFT: 7px; BORDER-LEFT: black 0.5pt solid; BORDER-BOTTOM: black 0.5pt solid"&gt;
&lt;p style="BACKGROUND: #eeece1"&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;font size=2&gt;&lt;span style="COLOR: blue"&gt;void&lt;/span&gt; UsingExample3()&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp; string&lt;/span&gt; result;&lt;br&gt;
&amp;nbsp; Using(&lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;StreamReader&lt;/span&gt;(file),
sr =&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; result = sr.ReadToEnd()&lt;br&gt;
&amp;nbsp; );&lt;br&gt;
}&lt;/font&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;/td&gt;
&lt;td style="BORDER-RIGHT: black 0.5pt solid; PADDING-RIGHT: 7px; BORDER-TOP: black 0.5pt solid; PADDING-LEFT: 7px; BORDER-LEFT: medium none; BORDER-BOTTOM: black 0.5pt solid"&gt;
&lt;p&gt;
&lt;span style="FONT-FAMILY: Courier New"&gt;&lt;font size=2&gt;&lt;span style="COLOR: blue"&gt;void&lt;/span&gt; usingKeywordExample()&lt;br&gt;
{&lt;br&gt;
&lt;span style="COLOR: blue"&gt;&amp;nbsp; string&lt;/span&gt; result;&lt;br&gt;
&amp;nbsp; using(&lt;span style="COLOR: blue"&gt;var&lt;/span&gt; sr = &lt;span style="COLOR: blue"&gt;new&lt;/span&gt; &lt;span style="COLOR: #2b91af"&gt;StreamReader&lt;/span&gt;(file))
{&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; result = sr.ReadToEnd();&lt;br&gt;
&amp;nbsp; }&lt;br&gt;
}&lt;/font&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;
This shows there is nothing that special about the built-in keywords. It is also the
first step in demonstrating that some parts of functional programming are not very
foreign to the C# programmer. The next articles in this series will provide some real-world
application of these ideas and show how you can reduce the amount of code you have
to write (and reduce the number of bugs at the same time!).
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=d0dafcc7-5ed9-4ff8-8a48-b39a909af34a" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,d0dafcc7-5ed9-4ff8-8a48-b39a909af34a.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=6b5585c5-576b-4542-9ed8-181e53776f6a</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,6b5585c5-576b-4542-9ed8-181e53776f6a.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,6b5585c5-576b-4542-9ed8-181e53776f6a.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=6b5585c5-576b-4542-9ed8-181e53776f6a</wfw:commentRss>
      <slash:comments>7</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
C# with lambda syntax and extension methods (in lieu of compositional operators) gets
us so far, but the syntax and compiler could use a bit of polish. I'll show some exact
examples later, but meanwhile this picture sums up my feelings at the moment:
</p>
        <p>
          <img title="No type inference for you!" height="666" alt="Notype1.png" src="http://www.atrevido.net/Blog/content/binary/Notype1.png" width="682" border="1" />
          <br />
          <br />
Edited to add: Inspired by <a href="http://xkcd.com/297/">http://xkcd.com/297/</a><br /><br />
Edited to add: Just to be clear, this isn't a compiler or IDE issue: it's a spec issue
(AFAIK). The C# spec simply doesn't allow certain things (like type inference from
a method group).
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=6b5585c5-576b-4542-9ed8-181e53776f6a" />
      </body>
      <title>C# Frustration</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,6b5585c5-576b-4542-9ed8-181e53776f6a.aspx</guid>
      <link>http://www.atrevido.net/blog/2007/08/02/C+Frustration.aspx</link>
      <pubDate>Thu, 02 Aug 2007 19:39:10 GMT</pubDate>
      <description>&lt;p&gt;
C# with lambda syntax and extension methods (in lieu of compositional operators)&amp;nbsp;gets
us so far, but the syntax and compiler could use a bit of polish. I'll show some exact
examples later, but meanwhile this picture sums up my feelings at the moment:
&lt;/p&gt;
&lt;p&gt;
&lt;img title="No type inference for you!" height=666 alt=Notype1.png src="http://www.atrevido.net/Blog/content/binary/Notype1.png" width=682 border=1&gt;
&lt;br&gt;
&lt;br&gt;
Edited to add: Inspired by &lt;a href="http://xkcd.com/297/"&gt;http://xkcd.com/297/&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
Edited to add: Just to be clear, this isn't a compiler or IDE issue: it's a spec issue
(AFAIK). The C# spec simply doesn't allow certain things (like type inference from
a method group).
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=6b5585c5-576b-4542-9ed8-181e53776f6a" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,6b5585c5-576b-4542-9ed8-181e53776f6a.aspx</comments>
      <category>Code</category>
      <category>Humour</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=62fb6984-6e5e-4e95-9f75-72e49d792c46</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,62fb6984-6e5e-4e95-9f75-72e49d792c46.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,62fb6984-6e5e-4e95-9f75-72e49d792c46.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=62fb6984-6e5e-4e95-9f75-72e49d792c46</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
My friend just dealt with an oursourced project. Yes, outsourced as in sending it
to a place that charges a lot less money than, say, developers who actually know
what they're doing.<br /><br />
One of their deliverables was a program that compressed an XML string into a gzip
file. Should be a minor thing, right? The C#/.NET 2 code is less than 10 lines. Well,
their first delivery produced files that contained the text "System.Byte[]". This
was not accepted and they vowed to look into it in more as they were sure the code
was correct.<br /><br />
Their next files were a bit larger and supposedly were really correct this time. But
still, no zip program could read the data. Well, a quick look at the beginning of
the file shows the bytes EF BB BF -- the UTF-8 BOM. The rest of the file was ASCII
digits. Yes, they wrote the bytestream out as a UTF-8 interpretation. 
<br /><br />
If we define evolution as "the non-random survival of randomly mutating replicators",
we can define their approach as "the non-random acceptance of randomly mutating programs."<br /></p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=62fb6984-6e5e-4e95-9f75-72e49d792c46" />
      </body>
      <title>Outsourced Evolutionary Programming</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,62fb6984-6e5e-4e95-9f75-72e49d792c46.aspx</guid>
      <link>http://www.atrevido.net/blog/2007/03/13/Outsourced+Evolutionary+Programming.aspx</link>
      <pubDate>Tue, 13 Mar 2007 17:51:08 GMT</pubDate>
      <description>&lt;p&gt;
My friend just dealt with an oursourced project. Yes, outsourced as in sending it
to a&amp;nbsp;place that charges a lot less money than, say, developers who actually know
what they're doing.&lt;br&gt;
&lt;br&gt;
One of their deliverables was a program that compressed an XML string into a gzip
file. Should be a minor thing, right? The C#/.NET 2 code is less than 10 lines. Well,
their first delivery produced files that contained the text "System.Byte[]". This
was not accepted and they vowed to look into it in more as they were sure the code
was correct.&lt;br&gt;
&lt;br&gt;
Their next files were a bit larger and supposedly were really correct this time. But
still, no zip program could read the data. Well, a quick look at the beginning of
the file shows the bytes EF BB BF -- the UTF-8 BOM. The rest of the file was ASCII
digits. Yes, they wrote the bytestream out as a UTF-8 interpretation. 
&lt;br&gt;
&lt;br&gt;
If we define evolution as "the non-random survival of randomly mutating replicators",
we can define their approach as "the non-random acceptance of randomly mutating programs."&lt;br&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=62fb6984-6e5e-4e95-9f75-72e49d792c46" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,62fb6984-6e5e-4e95-9f75-72e49d792c46.aspx</comments>
      <category>Code</category>
      <category>Humour</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=3f1a7332-e4e1-4dda-be02-527bfe07e98c</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,3f1a7332-e4e1-4dda-be02-527bfe07e98c.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,3f1a7332-e4e1-4dda-be02-527bfe07e98c.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=3f1a7332-e4e1-4dda-be02-527bfe07e98c</wfw:commentRss>
      <slash:comments>8</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Well, after almost exactly 6 hours, I've succeeded at installing SQL Server 2005 Reporting
Services on a server with more than one website.<br /><br />
We're running Reporting Services on separate web servers. So, after the install of
reporting services, you run their little configuration tool. This of course, accomplishes
very little :). See, apparently Reporting Services wasn't designed to work on
a server running, *gasp*, more than one application.<br /><br />
If you have a decent IIS install, the default website isn't there and thus
requests to <a href="http://localhost/">http://localhost/</a> aren't gonna work.
Reporting Services doesn't take this into consideration, and happily tries to request <a href="http://localhost/ReportServer/">http://localhost/ReportServer/</a> even after
you've specified this in the config tool. If this is your issue, you'll
get a “HTTP Error 400: Bad Request“ when trying to access the ReportManager
(/Reports/) website.<br /><br />
You'll need to edit the config files in Program Files\.....\ReportManager and ReportServer.
rsreportserver.config needs to point to <a href="http://the.reporting.host.name/ReportServer">http://the.reporting.host.name/ReportServer</a> in
the UrlRoot element. In RSWebApplication.config, ReportServerUrl will need to have
the same value. The ReportServerVirtualDirectory element must be deleted. You will
get a “The configuration file contains an element that is not valid. The ReportServerUrl
element is not a configuration file element. “ message. This is because the
config reading code apparently doesn't fail gracefully. What it's trying to say is
“the ReportServerUrl and ReportServerVirtualDirectory elements are mutually
exclusive”. I'm still unsure why there should be anything besides a URL...<br /><br />
Around here, you might notice a bunch of DCOM errors in your Event Log (or before
this point). To fix these, you'll need to go into dcomcnfg and edit the COM security
for My Computer. Give the account you're using (like Network Service or “MyReportingServicesAccount“)
permissions for local activation and local launch. You need to reboot for these changes
to take effect (I think). But don't reboot just yet...<br /><br />
Finally, you end up with a 401 Unauthorized when accessing the Reports site. You might
have also noticed you are also unable to authenticate when browsing the Reports or
ReportServer sites from your the local server. Why? 
<br />
“Windows XP SP2 and Windows Server 2003 SP1 include a loopback check security
feature that is designed to help prevent reflection attacks on your computer. Therefore,
authentication fails if the FQDN or the custom host header that you use does not match
the local computer name.” So I'm guessing NTLM susceptible to this type of attack,
and Microsoft is saving us from it. Well, it also hoses us in this case because from
what I can tell, ReportManager (the thing in the Reports vdir -- why it wasn't called
ReportManager by default...) needs to connect to ReportServer. It sends a request,
which is denied because of the loopback protection above. A quick registry edit fixes
this: <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;896861">http://support.microsoft.com/default.aspx?scid=kb;en-us;896861</a><br /><br />
After that... you might have a working SQL Reporting Services 2005 install! (Next
up: Getting it to work with SSL...)<br /><br />
Really, apart from the horrible setup/configuration, it's a very very fine product.
I'm actually pretty impressed. The report I wanted to setup (and the subscription
so it's mailed out) only took about 10 minutes (first time I've ever used RS)! I'm
just at a loss why Microsoft makes it so hard to setup. This configuration can't be
that unusual. And, even stranger, most (if not all) of this configuration issues could
take care of these problems. In other words, their little configuration app should
automatically fix this stuff (or at least give explicit instructions on how to do
so). Or maybe I just didn't RTFM that well... but this is a Microsoft product... you're
supposed to just shove the DVD in the drive and click next, right? &lt;g&gt;<br /><br />
P.S., if you're getting a “Object Reference not set to an Instance of an Object“
when you add a new subscription, ensuring everything else is 100% working should make
it go away...<br /></p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=3f1a7332-e4e1-4dda-be02-527bfe07e98c" />
      </body>
      <title>SQL Server 2005 Reporting Services Configuration Madness</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,3f1a7332-e4e1-4dda-be02-527bfe07e98c.aspx</guid>
      <link>http://www.atrevido.net/blog/2006/05/05/SQL+Server+2005+Reporting+Services+Configuration+Madness.aspx</link>
      <pubDate>Fri, 05 May 2006 06:02:44 GMT</pubDate>
      <description>&lt;p&gt;
Well, after almost exactly 6 hours, I've succeeded at installing SQL Server 2005 Reporting
Services on a server with more than one website.&lt;br&gt;
&lt;br&gt;
We're running Reporting Services on separate web servers. So, after the install of
reporting services, you run their little configuration tool. This of course, accomplishes
very little :). See, apparently Reporting Services wasn't designed to work&amp;nbsp;on
a server running, *gasp*, more than one application.&lt;br&gt;
&lt;br&gt;
If you have a decent IIS install, the default website&amp;nbsp;isn't there and&amp;nbsp;thus
requests to &lt;a href="http://localhost/"&gt;http://localhost/&lt;/a&gt;&amp;nbsp;aren't gonna work.
Reporting Services doesn't take this into consideration, and happily tries to request &lt;a href="http://localhost/ReportServer/"&gt;http://localhost/ReportServer/&lt;/a&gt; even&amp;nbsp;after
you've specified this in the config tool. If&amp;nbsp;this is&amp;nbsp;your issue, you'll
get a &amp;#8220;HTTP&amp;nbsp;Error 400: Bad Request&amp;#8220; when trying to access the ReportManager
(/Reports/) website.&lt;br&gt;
&lt;br&gt;
You'll need to edit the config files in Program Files\.....\ReportManager and ReportServer.
rsreportserver.config needs to point to &lt;a href="http://the.reporting.host.name/ReportServer"&gt;http://the.reporting.host.name/ReportServer&lt;/a&gt; in
the UrlRoot element. In RSWebApplication.config, ReportServerUrl will need to have
the same value. The ReportServerVirtualDirectory element must be deleted. You will
get a &amp;#8220;The configuration file contains an element that is not valid. The ReportServerUrl
element is not a configuration file element. &amp;#8220; message. This is because the
config reading code apparently doesn't fail gracefully. What it's trying to say is
&amp;#8220;the ReportServerUrl and ReportServerVirtualDirectory elements are mutually
exclusive&amp;#8221;. I'm still unsure why there should be anything besides a URL...&lt;br&gt;
&lt;br&gt;
Around here, you might notice a bunch of DCOM errors in your Event Log (or before
this point). To fix these, you'll need to go into dcomcnfg and edit the COM security
for My Computer. Give the account you're using (like Network Service or &amp;#8220;MyReportingServicesAccount&amp;#8220;)
permissions for local activation and local launch. You need to reboot for these changes
to take effect (I think). But don't reboot just yet...&lt;br&gt;
&lt;br&gt;
Finally, you end up with a 401 Unauthorized when accessing the Reports site. You might
have also noticed you are also unable to authenticate when browsing the Reports or
ReportServer sites from your the local server. Why? 
&lt;br&gt;
&amp;#8220;Windows XP SP2 and Windows Server 2003 SP1 include a loopback check security
feature that is designed to help prevent reflection attacks on your computer. Therefore,
authentication fails if the FQDN or the custom host header that you use does not match
the local computer name.&amp;#8221; So I'm guessing NTLM susceptible to this type of attack,
and Microsoft is saving us from it. Well, it also hoses us in this case because from
what I can tell, ReportManager (the thing in the Reports vdir -- why it wasn't called
ReportManager by default...) needs to connect to ReportServer. It sends a request,
which is denied because of the loopback protection above. A quick registry edit fixes
this: &lt;a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;896861"&gt;http://support.microsoft.com/default.aspx?scid=kb;en-us;896861&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
After that... you might have a working SQL Reporting Services 2005 install! (Next
up: Getting it to work with SSL...)&lt;br&gt;
&lt;br&gt;
Really, apart from the horrible setup/configuration, it's a very very fine product.
I'm actually pretty impressed. The report I wanted to setup (and the subscription
so it's mailed out) only took about 10 minutes (first time I've ever used RS)!&amp;nbsp;I'm
just at a loss why Microsoft makes it so hard to setup. This configuration can't be
that unusual. And, even stranger, most (if not all) of this configuration issues could
take care of these problems. In other words, their little configuration app should
automatically fix this stuff (or at least give explicit instructions on how to do
so). Or maybe I just didn't RTFM that well... but this is a Microsoft product... you're
supposed to just shove the DVD in the drive and click next, right? &amp;lt;g&amp;gt;&lt;br&gt;
&lt;br&gt;
P.S., if you're getting a &amp;#8220;Object Reference not set to an Instance of an Object&amp;#8220;
when you add a new subscription, ensuring everything else is 100% working should make
it go away...&lt;br&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=3f1a7332-e4e1-4dda-be02-527bfe07e98c" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,3f1a7332-e4e1-4dda-be02-527bfe07e98c.aspx</comments>
      <category>Code</category>
      <category>Misc. Technology</category>
      <category>Security</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=6eeec281-970e-4f84-b990-9b2e454b092b</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,6eeec281-970e-4f84-b990-9b2e454b092b.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,6eeec281-970e-4f84-b990-9b2e454b092b.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=6eeec281-970e-4f84-b990-9b2e454b092b</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://webproject.scottgu.com/Default.aspx">http://webproject.scottgu.com/Default.aspx</a>
          <br />
          <br />
YEY!!! Finally, after 2 years, we get VS2003 functionality back in VS2005. The biggest
pain point I have, every single day, is dealing with the vile VS2005 web sites. Microsoft
has finally realised that this monstrosity spawned to soothe the demented minds of
webmonkies who think HTML is a programming language is actually bad for real developers.
Really, how does catering to the people who think “build“  refers
to writing code help them? (Oh wait, I know. It allows them to gain access to “web
developers“ while knowing that people who know what they are doing still won't
defect.)<br /><br />
This is exactly like I predicted -- Microsoft will have to back down. I guess it took
the final RTM launch for everyone to try to upgrade their apps and then find out that
the new model is unusable. I wonder how many PSS cases/pieces of feedback they
got.<br /><br />
Well, I can't wait to change our projects to this format. I was planning on restructuring
our solution (22 projects in VS is unwieldly) anyways, and this will go great with
it. I know a few developers who are gonna be real happy when they come back after
the holidays! Maybe this means that doing a public refactoring in our solution won't
take 45 seconds anymore? Maybe these apps will build in less than a minute (like every
other C# app)?<br /><br />
Oh, BTW, I'm far from ungrateful, even though I might sound like that. I'm actually
very happy that the ASP.NET team is doing this, despite the fact that I might roll
my eyes and say “yea, about time!” :). But after going through all the
pain I have... perhaps its understandable.
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=6eeec281-970e-4f84-b990-9b2e454b092b" />
      </body>
      <title>Microsoft finally realises VS2005 web site apps suck</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,6eeec281-970e-4f84-b990-9b2e454b092b.aspx</guid>
      <link>http://www.atrevido.net/blog/2005/12/27/Microsoft+Finally+Realises+VS2005+Web+Site+Apps+Suck.aspx</link>
      <pubDate>Tue, 27 Dec 2005 02:25:54 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://webproject.scottgu.com/Default.aspx"&gt;http://webproject.scottgu.com/Default.aspx&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
YEY!!! Finally, after 2 years, we get VS2003 functionality back in VS2005. The biggest
pain point I have, every single day, is dealing with the vile VS2005 web sites. Microsoft
has finally realised that this monstrosity spawned to soothe the demented minds of
webmonkies who think HTML is a programming language is actually bad for real developers.
Really, how does catering to the people who think &amp;#8220;build&amp;#8220;&amp;nbsp; refers
to writing code help them? (Oh wait, I know. It allows them to gain access to &amp;#8220;web
developers&amp;#8220; while knowing that people who know what they are doing still won't
defect.)&lt;br&gt;
&lt;br&gt;
This is exactly like I predicted -- Microsoft will have to back down. I guess it took
the final RTM launch for everyone to try to upgrade their apps and then find out that
the new model is unusable.&amp;nbsp;I wonder how many PSS cases/pieces of feedback they
got.&lt;br&gt;
&lt;br&gt;
Well, I can't wait to change our projects to this format. I was planning on restructuring
our solution (22 projects in VS is unwieldly) anyways, and this will go great with
it. I know a few developers who are gonna be real happy when they come back after
the holidays! Maybe this means that doing a public refactoring in our solution won't
take 45 seconds anymore? Maybe these apps will build in less than a minute (like every
other C# app)?&lt;br&gt;
&lt;br&gt;
Oh, BTW, I'm far from ungrateful, even though I might sound like that. I'm actually
very happy that the ASP.NET team is doing this, despite the fact that I might roll
my eyes and say &amp;#8220;yea, about time!&amp;#8221; :). But after going through all the
pain I have... perhaps its understandable.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=6eeec281-970e-4f84-b990-9b2e454b092b" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,6eeec281-970e-4f84-b990-9b2e454b092b.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=c792adbf-ce0a-4bf9-a61c-ca1a4296d0ea</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,c792adbf-ce0a-4bf9-a61c-ca1a4296d0ea.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,c792adbf-ce0a-4bf9-a61c-ca1a4296d0ea.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=c792adbf-ce0a-4bf9-a61c-ca1a4296d0ea</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I was working on an application today, and I needed to add some data to every HyperLink
on the ASP.NET page (for a custom authorization string). I thought it might be a common
thing: needing to go through all the controls on a page, but apparently not. I didn't
find any framework functionality, and the only code samples (just to see if I have
the “best” way of doing things) led to some not-so-nice code (arraylists
and recursion!). So, here's the best I've come up with (criticism, please): 
</p>
        <p>
          <span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">        <font color="#008080">Stack</font>&lt;<font color="#008080">Control</font>&gt;
remainingControls <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">new</span><font color="#008080">Stack</font>&lt;<font color="#008080">Control</font>&gt;();<br />
        remainingControls.Push(<span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">this</span>);<br />
        <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">do</span><br />
        {<br />
            <font color="#008080">Control</font> currentControl <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> remainingControls.Pop();<br />
            <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">foreach</span> (Control
item <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">in</span> currentControl.Controls)<br />
            {<br />
                <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">if</span> (item <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">is</span><font color="#008080">HyperLink</font>)<br />
                {<br />
                    <font color="#008080">HyperLink</font> hl <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> (<font color="#008080">HyperLink</font>)item;<br />
                    hl.NavigateUrl <span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> AddAuthToUrl(hl.NavigateUrl);<br />
                }<br />
                <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> (item.Controls.Count
&gt; 0)<br />
                {<br />
                    remainingControls.Push(item);<br />
                }<br />
            }<br />
        } <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">while</span> (remainingControls.Count
!<span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">=</span> 0);</span>
        </p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=c792adbf-ce0a-4bf9-a61c-ca1a4296d0ea" />
      </body>
      <title>Best way to traverse all controls on an ASP.NET page?</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,c792adbf-ce0a-4bf9-a61c-ca1a4296d0ea.aspx</guid>
      <link>http://www.atrevido.net/blog/2005/08/02/Best+Way+To+Traverse+All+Controls+On+An+ASPNET+Page.aspx</link>
      <pubDate>Tue, 02 Aug 2005 21:52:15 GMT</pubDate>
      <description>&lt;p&gt;
I was working on an application today, and I needed to add some data to every HyperLink
on the ASP.NET page (for a custom authorization string). I thought it might be a common
thing: needing to go through all the controls on a page, but apparently not. I didn't
find any framework functionality, and the only code samples (just to see if I have
the &amp;#8220;best&amp;#8221; way of doing things) led to some not-so-nice code (arraylists
and recursion!). So, here's the best I've come up with (criticism, please): 
&lt;p&gt;
&lt;span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;font color=#008080&gt;Stack&lt;/font&gt;&amp;lt;&lt;font color=#008080&gt;Control&lt;/font&gt;&amp;gt;
remainingControls &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;new&lt;/span&gt; &lt;font color=#008080&gt;Stack&lt;/font&gt;&amp;lt;&lt;font color=#008080&gt;Control&lt;/font&gt;&amp;gt;();&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;remainingControls.Push(&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;this&lt;/span&gt;);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;do&lt;/span&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;font color=#008080&gt;Control&lt;/font&gt; currentControl &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; remainingControls.Pop();&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;foreach&lt;/span&gt; (Control
item &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;in&lt;/span&gt; currentControl.Controls)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;if&lt;/span&gt; (item &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;is&lt;/span&gt; &lt;font color=#008080&gt;HyperLink&lt;/font&gt;)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;font color=#008080&gt;HyperLink&lt;/font&gt; hl &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; (&lt;font color=#008080&gt;HyperLink&lt;/font&gt;)item;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;hl.NavigateUrl &lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; AddAuthToUrl(hl.NavigateUrl);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;else&lt;/span&gt; &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;if&lt;/span&gt; (item.Controls.Count
&amp;gt; 0)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;remainingControls.Push(item);&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;} &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;while&lt;/span&gt; (remainingControls.Count
!&lt;span style="FONT-SIZE: 11px; COLOR: red; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;=&lt;/span&gt; 0);&lt;/span&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=c792adbf-ce0a-4bf9-a61c-ca1a4296d0ea" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,c792adbf-ce0a-4bf9-a61c-ca1a4296d0ea.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=6ce2f2fe-6e8e-46a3-92a2-85e262e46a17</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,6ce2f2fe-6e8e-46a3-92a2-85e262e46a17.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,6ce2f2fe-6e8e-46a3-92a2-85e262e46a17.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=6ce2f2fe-6e8e-46a3-92a2-85e262e46a17</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I've spent a few hours trying to get the secure TCP (based on NegotiateStream) integrated
security in .NET 2.0 working. While there is a page on this (<a href="http://winfx.msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_fxremoting/html/555f3337-73db-46c6-8f62-96af99e5f445.asp">Authentication
with the TCP Channel</a>), it fails to mention that you need one more property in
addition to encrypt, impersonationLevel and authenticationMode. It's called “secure”,
and it must be “true”. I didn't see it mentioned anywhere, except when
I happened to browse the MSDN Forums: <a href="http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=55225">http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=55225</a><br /><br />
I looked at his config, and realised I didn't have this “secure” property.
Problem solved. Also, I recommend checking out <a href="http://pluralsight.com/wiki/default.aspx/Keith.GuideBook/HowToAddCIAToDotNETRemoting.html">http://pluralsight.com/wiki/default.aspx/Keith.GuideBook/HowToAddCIAToDotNETRemoting.html</a>,
which has a lot of information about Windows security in general, apart from some
specifics of remoting and Kerberos. And, finally, yes, there's one more page where
the secure attribute is listed (with some other docs) <a href="http://blogs.msdn.com/manishg/archive/2005/04/22/410879.aspx">http://blogs.msdn.com/manishg/archive/2005/04/22/410879.aspx</a><br /><br />
OK, so perhaps there was some error between the user and the keyboard... but I'm very
very excited to see this feature running.
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=6ce2f2fe-6e8e-46a3-92a2-85e262e46a17" />
      </body>
      <title>Secure TCP Remoting in Whidbey</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,6ce2f2fe-6e8e-46a3-92a2-85e262e46a17.aspx</guid>
      <link>http://www.atrevido.net/blog/2005/07/27/Secure+TCP+Remoting+In+Whidbey.aspx</link>
      <pubDate>Wed, 27 Jul 2005 02:25:15 GMT</pubDate>
      <description>&lt;p&gt;
I've spent a few hours trying to get the secure TCP (based on NegotiateStream) integrated
security in .NET 2.0 working. While there is a page on this (&lt;a href="http://winfx.msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_fxremoting/html/555f3337-73db-46c6-8f62-96af99e5f445.asp"&gt;Authentication
with the TCP Channel&lt;/a&gt;), it fails to mention that you need one more property in
addition to encrypt, impersonationLevel and authenticationMode. It's called &amp;#8220;secure&amp;#8221;,
and it must be &amp;#8220;true&amp;#8221;. I didn't see it mentioned anywhere, except when
I happened to browse the MSDN Forums: &lt;a href="http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=55225"&gt;http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=55225&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
I looked at his config, and realised I didn't have this &amp;#8220;secure&amp;#8221; property.
Problem solved. Also, I recommend checking out &lt;a href="http://pluralsight.com/wiki/default.aspx/Keith.GuideBook/HowToAddCIAToDotNETRemoting.html"&gt;http://pluralsight.com/wiki/default.aspx/Keith.GuideBook/HowToAddCIAToDotNETRemoting.html&lt;/a&gt;,
which has a lot of information about Windows security in general, apart from some
specifics of remoting and Kerberos. And, finally, yes, there's one more page where
the secure attribute is listed (with some other docs) &lt;a href="http://blogs.msdn.com/manishg/archive/2005/04/22/410879.aspx"&gt;http://blogs.msdn.com/manishg/archive/2005/04/22/410879.aspx&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
OK, so perhaps there was some error between the user and the keyboard... but I'm very
very excited to see this feature running.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=6ce2f2fe-6e8e-46a3-92a2-85e262e46a17" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,6ce2f2fe-6e8e-46a3-92a2-85e262e46a17.aspx</comments>
      <category>Code</category>
      <category>Security</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=f136fa5b-e61f-433e-acf4-28141c547ab8</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,f136fa5b-e61f-433e-acf4-28141c547ab8.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,f136fa5b-e61f-433e-acf4-28141c547ab8.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=f136fa5b-e61f-433e-acf4-28141c547ab8</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I found a cool C# library for use with Asterisk (AGI) and .NET: <a href="http://gundy.org/asterisk/">MONO-TONE</a>.
It looks promising as an easy way to deal with AGI from C#. I think that I'll be extending
it to support FastAGI as well, and contributing the changes back. Nice work <a href="http://gundy.org/">Gabriel</a>!
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=f136fa5b-e61f-433e-acf4-28141c547ab8" />
      </body>
      <title>Using Asterisk from C#: MONO-TONE</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,f136fa5b-e61f-433e-acf4-28141c547ab8.aspx</guid>
      <link>http://www.atrevido.net/blog/2005/07/08/Using+Asterisk+From+C+MONOTONE.aspx</link>
      <pubDate>Fri, 08 Jul 2005 16:06:36 GMT</pubDate>
      <description>&lt;p&gt;
I found a cool C# library for use with Asterisk (AGI) and .NET: &lt;a href="http://gundy.org/asterisk/"&gt;MONO-TONE&lt;/a&gt;.
It looks promising as an easy way to deal with AGI from C#. I think that I'll be extending
it to support FastAGI as well, and contributing the changes back. Nice work &lt;a href="http://gundy.org/"&gt;Gabriel&lt;/a&gt;!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=f136fa5b-e61f-433e-acf4-28141c547ab8" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,f136fa5b-e61f-433e-acf4-28141c547ab8.aspx</comments>
      <category>Asterisk</category>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=cc31a472-3152-4e2d-8dc7-1d0723f278e4</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,cc31a472-3152-4e2d-8dc7-1d0723f278e4.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,cc31a472-3152-4e2d-8dc7-1d0723f278e4.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=cc31a472-3152-4e2d-8dc7-1d0723f278e4</wfw:commentRss>
      <slash:comments>5</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I just used the coolest feature in a while: VS2005's Call Browser.<br /><br />
I'm currently working on some firmware for IP phones and adapters. The chip is the
Intel 8051, as used by Centrality Communications in the PA168. It's actually quite
fun, programming for an 8-bit system. Apart from writing in C (instead of such high-level
things like C#), writing for embedded systems like this adds its own interesting things,
like having to decide where a variable will be stored (I think there is 3 different
storage locations a variable can have with the 8051). Oh yea, and having to keep things
really small, and really fast.<br /><br />
At any rate, I am not that familiar with the entire design of the system, and I just
want to focus on adding features to the <a href="http://www.voip-info.org/wiki-IAX">IAX2</a> implementation
(cause SIP sucks!). A large part of my work is to figure out how things work. Having
the Goto Definition (F12) is great for finding specific symbols, but doesn't help
with the flow. Up until now, I've been Finding in Files for a specific method, then
chasing things down by recursively Finding in Files until I figured out how things
are called. This happens a lot, since these devices support 5 protocols and use #ifdefs
and generic calls to interface with the different protocols. Add to that 8MB of source,
and it's no small task.<br /><br />
This morning, I remembered I had seen a “Call Browser” window in Visual
Studio 2005 a while ago. Edit: Apparently this isn't a new feature and has been around
since VC6 (at least). Well, it's new to ME, and it's still very cool.<br /><br />
Here's an example. Let's say I want to add attended transfer (where you have a call,
press transfer, dial a number, talk to the new call, then hangup to connect the two).
I'm looking in the source I'm familar with (the IAX protocol area), and see iax2_hangup().
That's a packet-level call, so when someone physically hangs up, that, somehow, gets
called. Where? Well... right click the function, Call Browser -&gt; Show Calls To:<br /><img src="http://www.atrevido.net/blog/content/binary/CallBrowseIax1.PNG" border="0" /><br /><br />
Click... click... click... bingo. Now I've got a complete grasp on the call flow that
would send a IAX_COMMAND_HANGUP. My old way (which makes me feel stupid now) of browsing
source doesn't even come close. A lot of programming these days is managing complexity.
It's all about making the best use of our limited brainspace (some more limited than
others). 17 lines/1 small diagram. That's all it takes for me to see this complete
flow. How much mental capacity does that require versus browsing multiple locations
in 4 different source code files?
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=cc31a472-3152-4e2d-8dc7-1d0723f278e4" />
      </body>
      <title>Visual Studio 2005 Call Browser</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,cc31a472-3152-4e2d-8dc7-1d0723f278e4.aspx</guid>
      <link>http://www.atrevido.net/blog/2005/04/05/Visual+Studio+2005+Call+Browser.aspx</link>
      <pubDate>Tue, 05 Apr 2005 17:08:28 GMT</pubDate>
      <description>&lt;p&gt;
I just used the coolest feature in a while: VS2005's Call Browser.&lt;br&gt;
&lt;br&gt;
I'm currently working on some firmware for IP phones and adapters. The chip is the
Intel 8051, as used by Centrality Communications in the PA168. It's actually quite
fun, programming for an 8-bit system. Apart from writing in C (instead of such high-level
things like C#), writing for embedded systems like this adds its own interesting things,
like having to decide where a variable will be stored (I think there is 3 different
storage locations a variable can have with the 8051). Oh yea, and having to keep things
really small, and really fast.&lt;br&gt;
&lt;br&gt;
At any rate, I am not that familiar with the entire design of the system, and I just
want to focus on adding features to the &lt;a href="http://www.voip-info.org/wiki-IAX"&gt;IAX2&lt;/a&gt; implementation
(cause SIP sucks!). A large part of my work is to figure out how things work. Having
the Goto Definition (F12) is great for finding specific symbols, but doesn't help
with the flow. Up until now, I've been Finding in Files for a specific method, then
chasing things down by recursively Finding in Files until I figured out how things
are called. This happens a lot, since these devices support 5 protocols and use #ifdefs
and generic calls to interface with the different protocols. Add to that 8MB of source,
and it's no small task.&lt;br&gt;
&lt;br&gt;
This morning, I remembered I had seen a &amp;#8220;Call Browser&amp;#8221; window in Visual
Studio 2005 a while ago. Edit: Apparently this isn't a new feature and has been around
since VC6 (at least). Well, it's new to ME, and it's still very cool.&lt;br&gt;
&lt;br&gt;
Here's an example. Let's say I want to add attended transfer (where you have a call,
press transfer, dial a number, talk to the new call, then hangup to connect the two).
I'm looking in the source I'm familar with (the IAX protocol area), and see iax2_hangup().
That's a packet-level call, so when someone physically hangs up, that, somehow, gets
called. Where? Well... right click the function, Call Browser -&amp;gt; Show Calls To:&lt;br&gt;
&lt;img src="http://www.atrevido.net/blog/content/binary/CallBrowseIax1.PNG" border=0&gt;
&lt;br&gt;
&lt;br&gt;
Click... click... click... bingo. Now I've got a complete grasp on the call flow that
would send a IAX_COMMAND_HANGUP. My old way (which makes me feel stupid now) of browsing
source doesn't even come close. A lot of programming these days is managing complexity.
It's all about making the best use of our limited brainspace (some more limited than
others). 17 lines/1 small diagram.&amp;nbsp;That's all it takes for me to see this complete
flow. How much mental capacity does that require versus browsing multiple locations
in 4 different source code files?
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=cc31a472-3152-4e2d-8dc7-1d0723f278e4" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,cc31a472-3152-4e2d-8dc7-1d0723f278e4.aspx</comments>
      <category>Code</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=92b5d25e-e53a-459c-b2c1-77aa26544880</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,92b5d25e-e53a-459c-b2c1-77aa26544880.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,92b5d25e-e53a-459c-b2c1-77aa26544880.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=92b5d25e-e53a-459c-b2c1-77aa26544880</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <title>Cracking code 5.1: Increasing your configuration</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,92b5d25e-e53a-459c-b2c1-77aa26544880.aspx</guid>
      <link>http://www.atrevido.net/blog/2005/03/31/Cracking+Code+51+Increasing+Your+Configuration.aspx</link>
      <pubDate>Thu, 31 Mar 2005 04:26:10 GMT</pubDate>
      <description>Yet another super-easy tutorial... (Revision 2 for legal reasons)&lt;br&gt;
&lt;br&gt;
When attacking code, always look for the smallest, least intrusive change. The more
you change, the more you have to worry about A: screwing something up and B: not being
able to move your changes forward when the emitted code changes. Sometimes copy protection
authors use encryption and likewise. Sometimes they even do it correctly. But many
times, the critical path of code comes down to a single bit or couple of bytes. 
&lt;br&gt;
&lt;br&gt;
I've talked about flipping branches (jumps) before. Some programs all boil down to
an "if(boolean)...", in which case flipping a bit of a jmp will reverse the condition
(jump if equal to jump if not equal). This results in the code always working when
you enter invalid input, and not accepting valid input. But more complex code might
actually depend on a bit more code, say, a variable being set to a certain number.
For instance, maybe it has an "activation level", and the higher it is, the more features
are enabled. In such cases, it's not feasible to go around flipping a bunch of branches.&lt;br&gt;
&lt;br&gt;
Today's tutorial will use IDA Pro (&lt;a href="http://www.atrevido.net/blog/ct.ashx?id=17b48c2e-55c1-4183-af09-9ec1380d5541&amp;amp;url=http%3a%2f%2fwww.datarescue.com%2f" ?&gt;www.datarescue.com&lt;/a&gt;).
You can get a free demo to try out. However, if you're gonna do a lot of work with
IDA Pro, it's only $439 for the full version. It even now supports cross-platform
debugging (i.e., debug your Linux app on Windows), and supports .NET executables.
I have to try it, but it sounds like this could be my solution to developing (debugging)
on Windows for Linux. Very, very cool.&lt;br&gt;
&lt;br&gt;
No sample program this time, since it is really easy to grasp. Lets take a theoretical
program: MagicLineConverter. MagicLineConverter converts input data to output data
and does some magical transformation on it. The program is configured for a set number
of lines. So you can buy a 1000 line program, a 2000 line program, etc. They have
some genius crypto people on staff, so trying to generate fake config files for it
just isn't possible. You need to try it with a million lines, just to make sure it
works, so you can get a purchase order to buy the program. So, you download the demo
program, but it expires before you get a change to examine it. Now, you have zero
lines configured for use.&lt;br&gt;
&lt;br&gt;
Thus, we load the program in IDA Pro. After loading the program, you'll get a large
disassembly view. Poke around, and you'll see names like &amp;#8220;sub_8048400&amp;#8221;
and &amp;#8220;dword_804967C&amp;#8221;. As with any attack, you've got to start off by finding
the real method and variable names. IDA Pro makes this not too hard, and offers a
renaming function that allows you to rename functions as you go along. Thus, if you
think a variable holds a value representing if there is network access, you can rename
it to say "IsNetworkAvail" instead of remembering a memory location. If you work around
for a while, you can probably reconstruct a lot of the program logic. The more you
understand, the better your patch can be.&lt;br&gt;
&lt;br&gt;
Well, when you run the program, output like this is probably sent:&lt;font face="Courier New"&gt;
&lt;br&gt;
Configured for 1000 lines.&lt;br&gt;
&lt;/font&gt;
&lt;br&gt;
Back in IDA Pro, goto the strings window. Search for that string. Double click it
and you'll see something like this in the dissembler: ".data:001234 'aConfigured_for',
0Ah, 0. On the next lines, you'll have information like "; DATA XREF: sub_001400+E".
IDA is telling us where this string is referenced. If we go there, we'll probably
see something like this:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;push ds:dword_0A240200&lt;br&gt;
push offset aConfigured_for ; "Configured for %d lines.\n"&lt;br&gt;
call printf&lt;br&gt;
&lt;/font&gt;
&lt;br&gt;
By now, we're probably almost done. We've found where some code is that reports the
total lines the program is configured for. Somehow, this routine knows where to get
the data, or the data is passed in. Since there's a dword being pushed and printed,
it's safe to assume the count is stored there. Click that dword, and press 'n' to
rename it. Enter a good name, such as 'possibleCount' or 'printedCount'. When the
copy protection is good, there could be multiple levels of indirection leading up
to printing something critical like that. Thus, using tentative names that reflect
what you are certain of helps if things get more complex down the road. You can also
rename the routine to something useful like "printCount".&lt;br&gt;
&lt;br&gt;
Now, we want to see whereelse this variable is used. IDA Pro has a feature that lets
us see all references an item. In the disassembly, right click our renamed variable,
and select &amp;#8220;Jump to xref to operand&amp;#8221; (or just press x). A dialog is shown
that has different instructions using this memory. Look for ones that look like initialization.
Here's two common examples:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;mov ds:printedCount, 0&lt;br&gt;
mov ds:printedCount, ecx&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
The first one first. Highlight that entire line (mov ds:&lt;font face="Courier New"&gt;printedCount&lt;/font&gt;,
0). Then switch to Hex view. You'll see something like this highlighted: &lt;font face="Courier New"&gt;C7
05 34 12 00 00 00 00 00 00&lt;/font&gt;. Since it's a dword, there is 4 bytes to represent
zero. Modify any of them to a value of your choosing. (thus changing mov ds:printedCount,0
to ,1000000). This patch can be as small as a single bit if your choose! 
&lt;br&gt;
&lt;br&gt;
But wait... sometimes GCC won't generate a &amp;#8220;mov something,0&amp;#8221; to initialize
it. In some cases, for some processors, and certain optimizations, it'll use a register
for initialization. In such case, the disassembly might look something like the second
case:&lt;br&gt;
&lt;font face="Courier New"&gt;
&lt;br&gt;
; Somewhere deep in the program&lt;br&gt;
mov ds:printedCount, ecx ; After critical processing&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
Now we have to find out where ecx is initialized. It probably won't be too far away.
If we're lucky, there will be a mov ecx, 0. However, optimized code probably won't
emit that. Instead, it might have:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;xor ecx, ecx&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
xor'ing a value against itself will always produce zero, and &amp;#8220;xor ecx, ecx&amp;#8220;
takes up 3 less bytes than&amp;nbsp;&amp;#8220;mov ecx, 0&amp;#8220;. The xor is only two bytes
(0x31c9).&amp;nbsp;Two ideas: First, fill it with nops. Depending on the value in edx,
this might work and give us some amount of licenses. However, that might not work:
ecx could be zero already.&amp;nbsp;Fortunately, we can address a single byte of ecx with
this: mov ch,0xff. This moves ff into the high part of CX, which is the low part of
ECX. That instruction generates only two bytes (0xb5ff), so it's a great replacement
for the xor opcode on the same register.&amp;nbsp;Assuming ECX is zero, that one byte
will now make it have the value 65,280. 
&lt;br&gt;
&lt;br&gt;
In both cases, it's only a two byte patch. You can distribute the patch with a simple
offset:value -- 9 bytes of ASCII text. Sorta hard to stop that, and anyone could patch
just from their own memory.&lt;br&gt;
&lt;br&gt;
Moral of the story: Write obfuscated code or use a post-compile processors that will
mixup your code for you. If your code is cracked by changing a single bit... that
means it's just protecting the honest :). While 100% protection is never possible,
it should be&amp;nbsp;a lot harder than allowing a stray gamma ray to crack your code!&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=92b5d25e-e53a-459c-b2c1-77aa26544880" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,92b5d25e-e53a-459c-b2c1-77aa26544880.aspx</comments>
      <category>Code</category>
      <category>Security</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=65e1bf80-d2a7-42e8-904c-9e758ded0afa</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,65e1bf80-d2a7-42e8-904c-9e758ded0afa.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,65e1bf80-d2a7-42e8-904c-9e758ded0afa.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=65e1bf80-d2a7-42e8-904c-9e758ded0afa</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I'm doing my own realtime support for Asterisk, in an attempt to make it scale. Asterisk
is nice software, but straight out-of-CVS, the performance for high volume (say, over
20,000 clients) sucks. There are also other inconviences with using a file-based store
to determine how to route calls. Mainly, it's inflexible and hard to achieve high-perf
when everything is based on a large .conf file. Not to mention that Asterisk uses
linked lists for everything so looking up any user is an O(N) op (and parsing the
users file is O(N*N) by default!). So, I'm going to put my own logic as a replacement
for some of the critical parts. 
<br /><br />
One of my concerns was performance. Since I'll have multiple Asterisk clusters banging
on my .NET code (via SOAP), I wanted to ensure the whole end-to-end process was fast
enough. 
<br /><br />
I used <a href="http://www.cs.fsu.edu/~engelen/soap.html">gSOAP</a> to create the
C code on Linux. gSOAP is seriously nice. At least an order of magnitude easier to
use than I expected any SOAP library that works on Linux would be.<br /><br />
I created a simple test. I made a database with phone numbers and codecs. The
idea is that when an incoming call comes in, Asterisk will use my code to SOAP over
to my Windows machines, get the data, and then go on its merry way.<br /><br />
My Asterisk machine is a P4 2.4GHz, 512MB RAM (but, I have a Gnome session running
on it). My Windows XP machine (I tested against my desktop) is a P4 3GHz HT, 1.5GB
RAM. I'm running ASP.NET 2 Beta 1 and SQL Server 2000.<br /><br />
The test program consists of a loop (count 5000) that generates a random number, then
uses gSOAP to ask for the codec for that number. Simple, tight.<br /><br />
The results on Linux are particularly impressive. Each instance of the test app
only used a max of 4% processor, and under 1MB of RAM. The bottleneck was definately
inside ASP.NET. To simulate more load from other machines in a cluster, I ran 1, 2,
and 4 instances of the test program. Also note that background tasks on the XP machine
used up about 10% of the CPU.<br /><br />
Results:<br />
 Single process (5000 total requests): <br />
  Total time:                  
18 seconds (0.0036s/request)<br />
  Requests per second:   277<br />
  ASP.NET/IIS CPU:          30%<br />
  SQL Server CPU:           
4%<br /><br />
 Dual process (10,000 total requests):<br />
  Total time:                 
 23 seconds (0.0048s/request)<br />
  Requests per second:   384<br />
  ASP.NET/IIS CPU:          60%<br />
  SQL Server CPU:           
7%<br /><br />
 Quad process (20,000 total requests):<br />
  Total time:                 
 42 seconds (0.0052s/request)<br />
  Requests per second:   476<br />
  ASP.NET/IIS CPU:          80%<br />
  SQL Server CPU:           10%<br /><br />
These results are encouraging enough that I'm not worried of the performance impact
of using SOAP with Asterisk. My target was to have a response in less than 0.1 seconds.
Although, anything under 0.5s would be quite unnoticable to a client. Even in tests
with more threads, my single request response time was always way under 0.1 seconds.<br /><br />
Also, as far as I know, Whidbey Beta 2 (the version I'll go live with) makes
some performance improvements. And also, IIS6 on Windows 2003 is much faster than
IIS5.1 on XP. At any rate, a single proc desktop machine serving 476 RPS? That's pretty
damn good perf if you ask me!
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=65e1bf80-d2a7-42e8-904c-9e758ded0afa" />
      </body>
      <title>SOAP Performance (gSOAP / ASP.NET)</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,65e1bf80-d2a7-42e8-904c-9e758ded0afa.aspx</guid>
      <link>http://www.atrevido.net/blog/2005/03/16/SOAP+Performance+GSOAP+ASPNET.aspx</link>
      <pubDate>Wed, 16 Mar 2005 17:06:55 GMT</pubDate>
      <description>&lt;p&gt;
I'm doing my own realtime support for Asterisk, in an attempt to make it scale. Asterisk
is nice software, but straight out-of-CVS, the performance for high volume (say, over
20,000 clients) sucks. There are also other inconviences with using a file-based store
to determine how to route calls. Mainly, it's inflexible and hard to achieve high-perf
when everything is based on a large .conf file. Not to mention that Asterisk uses
linked lists for everything so looking up any user is an O(N) op (and parsing the
users file is O(N*N) by default!). So, I'm going to put my own logic as a replacement
for some of the critical parts. 
&lt;br&gt;
&lt;br&gt;
One of my concerns was performance. Since I'll have multiple Asterisk clusters banging
on my .NET code (via SOAP), I wanted to ensure the whole end-to-end process was fast
enough. 
&lt;br&gt;
&lt;br&gt;
I used &lt;a href="http://www.cs.fsu.edu/~engelen/soap.html"&gt;gSOAP&lt;/a&gt; to create the
C code on Linux. gSOAP is seriously nice. At least an order of magnitude easier to
use than I expected any SOAP library that works on Linux would be.&lt;br&gt;
&lt;br&gt;
I created a simple test. I made a database with phone numbers&amp;nbsp;and codecs. The
idea is that when an incoming call comes in, Asterisk will use my code to SOAP over
to my Windows machines, get the data, and then go on its merry way.&lt;br&gt;
&lt;br&gt;
My Asterisk machine is a P4 2.4GHz, 512MB RAM (but, I have a Gnome session running
on it). My Windows XP machine (I tested against my desktop) is a P4 3GHz HT, 1.5GB
RAM. I'm running ASP.NET 2 Beta 1 and SQL Server 2000.&lt;br&gt;
&lt;br&gt;
The test program consists of a loop (count 5000) that generates a random number, then
uses gSOAP to ask for the codec for that number. Simple, tight.&lt;br&gt;
&lt;br&gt;
The results on Linux are particularly impressive. Each instance of&amp;nbsp;the test app
only used a max of 4% processor, and under 1MB of RAM. The bottleneck was definately
inside ASP.NET. To simulate more load from other machines in a cluster, I ran 1, 2,
and 4 instances of the test program. Also note that background tasks on the XP machine
used up about 10% of the CPU.&lt;br&gt;
&lt;br&gt;
Results:&lt;br&gt;
&amp;nbsp;Single process (5000 total requests):&amp;nbsp;&lt;br&gt;
&amp;nbsp; Total time:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
18 seconds (0.0036s/request)&lt;br&gt;
&amp;nbsp; Requests per second:&amp;nbsp;&amp;nbsp;&amp;nbsp;277&lt;br&gt;
&amp;nbsp; ASP.NET/IIS CPU:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;30%&lt;br&gt;
&amp;nbsp; SQL Server CPU:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;
4%&lt;br&gt;
&lt;br&gt;
&amp;nbsp;Dual process (10,000 total requests):&lt;br&gt;
&amp;nbsp; Total time:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;23 seconds (0.0048s/request)&lt;br&gt;
&amp;nbsp;&amp;nbsp;Requests per second:&amp;nbsp;&amp;nbsp; 384&lt;br&gt;
&amp;nbsp; ASP.NET/IIS CPU:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; 60%&lt;br&gt;
&amp;nbsp; SQL Server CPU:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;
7%&lt;br&gt;
&lt;br&gt;
&amp;nbsp;Quad process (20,000 total requests):&lt;br&gt;
&amp;nbsp; Total time:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;nbsp;42 seconds (0.0052s/request)&lt;br&gt;
&amp;nbsp; Requests per second:&amp;nbsp;&amp;nbsp; 476&lt;br&gt;
&amp;nbsp; ASP.NET/IIS CPU:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; 80%&lt;br&gt;
&amp;nbsp; SQL Server CPU:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;10%&lt;br&gt;
&lt;br&gt;
These results are encouraging enough that I'm not worried of the performance impact
of using SOAP with Asterisk. My target was to have a response in less than 0.1 seconds.
Although, anything under 0.5s would be quite unnoticable to a client. Even in tests
with more threads, my single request response time was always way under 0.1 seconds.&lt;br&gt;
&lt;br&gt;
Also, as far as I know, Whidbey&amp;nbsp;Beta 2&amp;nbsp;(the version I'll go live with)&amp;nbsp;makes
some performance improvements. And also, IIS6 on Windows 2003 is much faster than
IIS5.1 on XP. At any rate, a single proc desktop machine serving 476 RPS? That's pretty
damn good perf if you ask me!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=65e1bf80-d2a7-42e8-904c-9e758ded0afa" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,65e1bf80-d2a7-42e8-904c-9e758ded0afa.aspx</comments>
      <category>ast_mono</category>
      <category>Asterisk</category>
      <category>Code</category>
    </item>
  </channel>
</rss>