<?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:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>[Giagnocavo]Michael::Write()</title>
    <link>http://www.atrevido.net/blog/</link>
    <description>Something about .NET.</description>
    <copyright>Michael Giagnocavo</copyright>
    <lastBuildDate>Fri, 15 May 2009 20:46:39 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 1.9.7174.0</generator>
    <managingEditor>mggUNSPAM@telefinity.com</managingEditor>
    <webMaster>mggUNSPAM@telefinity.com</webMaster>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=cc0a8d5c-102f-452b-927c-59b2ca2017ca</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,cc0a8d5c-102f-452b-927c-59b2ca2017ca.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,cc0a8d5c-102f-452b-927c-59b2ca2017ca.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=cc0a8d5c-102f-452b-927c-59b2ca2017ca</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
If you use ASP.NET MVC with F# CTP (Monday brings Beta 1 and probably many changes),
you might run into an issue of how to scope certain things. For example, an IDisposable
is used to create blocks, for things like an HTML form. Example in C#:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 14pt">
          <p style="MARGIN: 0px">
    <span style="BACKGROUND: #ffee62">&lt;%</span><span style="COLOR: blue">using</span> (Html.BeginForm())
{<span style="BACKGROUND: #ffee62">%&gt;</span></p>
          <p style="MARGIN: 0px">
 
</p>
          <p style="MARGIN: 0px">
        <span style="COLOR: blue">&lt;</span><span style="COLOR: #a31515">fieldset</span><span style="COLOR: blue">&gt;</span><span style="COLOR: blue">&lt;</span><span style="COLOR: #a31515">legend</span><span style="COLOR: blue">&gt;</span>Fields<span style="COLOR: blue">&lt;/</span><span style="COLOR: #a31515">legend</span><span style="COLOR: blue">&gt;...</span><span style="COLOR: blue">&lt;/</span><span style="COLOR: #a31515">fieldset</span><span style="COLOR: blue">&gt;</span></p>
          <p style="MARGIN: 0px">
 
</p>
          <p style="MARGIN: 0px">
    <span style="BACKGROUND: #ffee62">&lt;%</span> } <span style="BACKGROUND: #ffee62">%&gt;</span></p>
          <p style="MARGIN: 0px">
            <span style="BACKGROUND: #ffee62">
            </span> 
</p>
        </div>
        <p>
          <!--EndFragment-->This is needed because VB and C# didn't have any easy function/block
syntax (VB 10 should fix this), and many C# developers are still wary of higher order
functions. How does this play out in F#? First off, whitespace is important. This
can get really messy with the current F# ASP.NET integration. Basically, always open
the script blocks on a separate line, and indent from the first column. Example:
</p>
        <blockquote style="MARGIN-RIGHT: 0px" dir="ltr">
          <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 14pt">
            <p style="MARGIN: 0px">
              <span style="BACKGROUND: #ffee62">&lt;%</span> let i = 0
</p>
            <p style="MARGIN: 0px">
   this.Response.Write(sprintf "i = %d" i) <span style="BACKGROUND: #ffee62">%&gt;</span></p>
          </div>
        </blockquote>
        <!--EndFragment-->
        <p>
(Note that the 'this' variable is bound to the current page.) This fails:
</p>
        <p>
          <strong>Compiler Error Message: </strong>
          <font face="Arial">FS0010: Unexpected keyword
'let' or 'use' in expression. Expected incomplete structured construct at or before
this point or other token<br /><br /></font>
          <b>Source Error:</b>
          <br />
          <br />
          <table width="100%" bgcolor="#ffffcc">
            <tbody>
              <tr>
                <td>
                </td>
              </tr>
              <tr>
                <td>
                  <code>
                    <pre>Line 111:                let mutable parameterContainer = parameterContainer
Line 112:                __w.Write("\r\n") |&gt; ignore
<font color="red">Line
113: let i = 0 </font>Line 114: this.Response.Write(sprintf "i = %d" i) Line 115:
__w.Write("\r\n &lt;h2&gt;Create&lt;/h2&gt;\r\n\r\n ") |&gt; ignore</pre>
                  </code>
                </td>
              </tr>
            </tbody>
          </table>
        </p>
        <p>
Note how the &lt;% is counted as space, so the let starts off indented 3 spaces. Instead,
we need to write it so:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 14pt">
          <p style="MARGIN: 0px">
            <span style="BACKGROUND: #ffee62">&lt;%</span>
          </p>
          <p style="MARGIN: 0px">
let i = 0
</p>
          <p style="MARGIN: 0px">
this.Response.Write(sprintf "i = %d" i) <span style="BACKGROUND: #ffee62">%&gt;</span></p>
        </div>
        <!--EndFragment-->
        <p>
This works fine. You can also put the <span style="BACKGROUND: #ffee62">%&gt;</span> on
the next line if you like. Now, on to ASP.NET MVC's IDisposable usage. A straightforward
use of the F# using function won't work:
</p>
        <blockquote style="MARGIN-RIGHT: 0px" dir="ltr">
          <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 14pt">
            <p style="MARGIN: 0px">
              <span style="COLOR: blue">&lt;</span>
              <span style="COLOR: #a31515">b</span>
              <span style="COLOR: blue">&gt;</span>Demo<span style="COLOR: blue">&lt;/</span><span style="COLOR: #a31515">b</span><span style="COLOR: blue">&gt;</span></p>
            <p style="MARGIN: 0px">
 
</p>
            <p style="MARGIN: 0px">
              <span style="BACKGROUND: #ffee62">&lt;%</span>
            </p>
            <p style="MARGIN: 0px">
using (Mvc.Html.FormExtensions.BeginForm this.Html) (fun _ -&gt; <span style="BACKGROUND: #ffee62">%&gt;</span></p>
            <p style="MARGIN: 0px">
 
</p>
            <p style="MARGIN: 0px">
    <span style="COLOR: blue">&lt;</span><span style="COLOR: #a31515">p</span><span style="COLOR: blue">&gt;</span>Inside
a form<span style="COLOR: blue">&lt;/</span><span style="COLOR: #a31515">p</span><span style="COLOR: blue">&gt;</span></p>
            <p style="MARGIN: 0px">
 
</p>
            <p style="MARGIN: 0px">
              <span style="BACKGROUND: #ffee62">&lt;%</span> ) <span style="BACKGROUND: #ffee62">%&gt;</span></p>
          </div>
        </blockquote>
        <!--EndFragment-->
        <p>
          <strong>Compiler Error Message: </strong>
          <font face="Arial">FS0191: The mutable variable
'__w' is used in an invalid way. Mutable variables may not be captured by closures.
Consider eliminating this use of mutation or using a heap-allocated mutable reference
cell via 'ref' and '!'.<br /><br /></font>
          <b>Source Error:</b>
          <br />
          <br />
        </p>
        <p>
          <table width="100%" bgcolor="#ffffcc">
            <tbody>
              <tr>
                <td>
                </td>
              </tr>
              <tr>
                <td>
                  <code>
                    <pre>Line 114:                __w.Write("\r\n\r\n&lt;b&gt;Demo&lt;/b&gt;\r\n\r\n") |&gt; ignore
Line 115:                  
<font color="red">Line
116: using (Mvc.Html.FormExtensions.BeginForm this.Html) (fun _ -&gt; </font>Line
117: __w.Write("\r\n\r\n &lt;p&gt;Inside a form&lt;/p&gt;\r\n\r\n") |&gt; ignore Line
118: ) </pre>
                  </code>
                </td>
              </tr>
            </tbody>
          </table>
        </p>
        <p>
As the error says, this is because the __w variable is mutable, so we can't play with
it inside a lambda. I'm not sure if this will be worked around -- they'd have to change
the codegen quite a bit, I'd think. As a side note, the F# CTP does not support C#
extension methods (hence the verbose calling of BeginForm), but F# will eventually
-- maybe in the Beta.
</p>
        <p>
The way we must scope is with a use binding. There's no way I see to accomplish this
with whitespace alone. Due to the ASPX translation process, this would probably be
very error prone. Instead, we can simply put the use binding inside a do expression:
</p>
        <blockquote style="MARGIN-RIGHT: 0px" dir="ltr">
          <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 14pt">
            <p style="MARGIN: 0px">
              <span style="COLOR: blue">&lt;</span>
              <span style="COLOR: #a31515">b</span>
              <span style="COLOR: blue">&gt;</span>Demo<span style="COLOR: blue">&lt;/</span><span style="COLOR: #a31515">b</span><span style="COLOR: blue">&gt;</span></p>
            <p style="MARGIN: 0px">
 
</p>
            <p style="MARGIN: 0px">
              <span style="BACKGROUND: #ffee62">&lt;%</span>
            </p>
            <p style="MARGIN: 0px">
do (use form = Mvc.Html.FormExtensions.BeginForm this.Html <span style="BACKGROUND: #ffee62">%&gt;</span></p>
            <p style="MARGIN: 0px">
 
</p>
            <p style="MARGIN: 0px">
              <span style="COLOR: blue">&lt;</span>
              <span style="COLOR: #a31515">b</span>
              <span style="COLOR: blue">&gt;</span>Inside
the form<span style="COLOR: blue">&lt;/</span><span style="COLOR: #a31515">b</span><span style="COLOR: blue">&gt;</span></p>
            <p style="MARGIN: 0px">
 
</p>
            <p style="MARGIN: 0px">
              <span style="BACKGROUND: #ffee62">&lt;%</span> ) <span style="BACKGROUND: #ffee62">%&gt;</span></p>
            <p style="MARGIN: 0px">
 
</p>
            <p style="MARGIN: 0px">
              <span style="COLOR: blue">&lt;</span>
              <span style="COLOR: #a31515">b</span>
              <span style="COLOR: blue">&gt;</span>Outside
of the form<span style="COLOR: blue">&lt;/</span><span style="COLOR: #a31515">b</span><span style="COLOR: blue">&gt;</span></p>
          </div>
        </blockquote>
        <!--EndFragment-->
        <p>
The parentheses setup the scope exactly how we want it.
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=cc0a8d5c-102f-452b-927c-59b2ca2017ca" />
      </body>
      <title>F# CTP and ASP.NET MVC ASPX: Scoping disposables</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,cc0a8d5c-102f-452b-927c-59b2ca2017ca.aspx</guid>
      <link>http://www.atrevido.net/blog/2009/05/15/F+CTP+And+ASPNET+MVC+ASPX+Scoping+Disposables.aspx</link>
      <pubDate>Fri, 15 May 2009 20:46:39 GMT</pubDate>
      <description>&lt;p&gt;
If you use ASP.NET MVC with F# CTP (Monday brings Beta 1 and probably many changes),
you might run into an issue of how to scope certain things. For example, an IDisposable
is used to create blocks, for things like an HTML form. Example in C#:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 14pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="BACKGROUND: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="COLOR: blue"&gt;using&lt;/span&gt; (Html.BeginForm())
{&lt;span style="BACKGROUND: #ffee62"&gt;%&amp;gt;&lt;/span&gt;
&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; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="COLOR: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;fieldset&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;legend&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;Fields&lt;span style="COLOR: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;legend&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;...&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;fieldset&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;
&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="BACKGROUND: #ffee62"&gt;&amp;lt;%&lt;/span&gt; } &lt;span style="BACKGROUND: #ffee62"&gt;%&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="BACKGROUND: #ffee62"&gt;&lt;/span&gt;&amp;nbsp;
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
&lt;!--EndFragment--&gt;This is needed because VB and C# didn't have any easy function/block
syntax (VB 10 should fix this), and many C# developers are still wary of higher order
functions. How does this play out in F#? First off, whitespace is important. This
can get really messy with the current F# ASP.NET integration. Basically, always open
the script blocks on a separate line, and indent from the first column. Example:
&lt;/p&gt;
&lt;blockquote style="MARGIN-RIGHT: 0px" dir=ltr&gt; 
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 14pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="BACKGROUND: #ffee62"&gt;&amp;lt;%&lt;/span&gt; let i = 0
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;&amp;nbsp; this.Response.Write(sprintf "i = %d" i) &lt;span style="BACKGROUND: #ffee62"&gt;%&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;/blockquote&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
(Note that the 'this' variable is bound to the current page.)&amp;nbsp;This fails:
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Compiler Error Message: &lt;/strong&gt;&lt;font face=Arial&gt;FS0010: Unexpected keyword
'let' or 'use' in expression. Expected incomplete structured construct at or before
this point or other token&lt;br&gt;
&lt;br&gt;
&lt;/font&gt;&lt;b&gt;Source Error:&lt;/b&gt;
&lt;br&gt;
&lt;br&gt;
&lt;table width="100%" bgcolor=#ffffcc&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;code&gt;&lt;pre&gt;Line 111:                let mutable parameterContainer = parameterContainer
Line 112:                __w.Write("\r\n") |&amp;gt; ignore
&lt;font color=red&gt;Line
113: let i = 0 &lt;/font&gt;Line 114: this.Response.Write(sprintf "i = %d" i) Line 115:
__w.Write("\r\n &amp;lt;h2&amp;gt;Create&amp;lt;/h2&amp;gt;\r\n\r\n ") |&amp;gt; ignore&lt;/pre&gt;
&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/p&gt;
&lt;p&gt;
Note how the &amp;lt;% is counted as space, so the let starts off indented&amp;nbsp;3 spaces.&amp;nbsp;Instead,
we need to write it so:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 14pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="BACKGROUND: #ffee62"&gt;&amp;lt;%&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
let i = 0
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
this.Response.Write(sprintf "i = %d" i) &lt;span style="BACKGROUND: #ffee62"&gt;%&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
This works fine. You can also put the &lt;span style="BACKGROUND: #ffee62"&gt;%&amp;gt;&lt;/span&gt; on
the next line if you like.&amp;nbsp;Now, on to ASP.NET MVC's IDisposable usage. A straightforward
use of the F# using function won't work:
&lt;/p&gt;
&lt;blockquote style="MARGIN-RIGHT: 0px" dir=ltr&gt; 
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 14pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;b&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;Demo&lt;span style="COLOR: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;b&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="BACKGROUND: #ffee62"&gt;&amp;lt;%&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
using (Mvc.Html.FormExtensions.BeginForm this.Html) (fun _ -&amp;gt; &lt;span style="BACKGROUND: #ffee62"&gt;%&amp;gt;&lt;/span&gt;
&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;&amp;lt;&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;p&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;Inside
a form&lt;span style="COLOR: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;p&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="BACKGROUND: #ffee62"&gt;&amp;lt;%&lt;/span&gt; ) &lt;span style="BACKGROUND: #ffee62"&gt;%&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;/blockquote&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
&lt;strong&gt;Compiler Error Message: &lt;/strong&gt;&lt;font face=Arial&gt;FS0191: The mutable variable
'__w' is used in an invalid way. Mutable variables may not be captured by closures.
Consider eliminating this use of mutation or using a heap-allocated mutable reference
cell via 'ref' and '!'.&lt;br&gt;
&lt;br&gt;
&lt;/font&gt;&lt;b&gt;Source Error:&lt;/b&gt;
&lt;br&gt;
&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;table width="100%" bgcolor=#ffffcc&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;code&gt;&lt;pre&gt;Line 114:                __w.Write("\r\n\r\n&amp;lt;b&amp;gt;Demo&amp;lt;/b&amp;gt;\r\n\r\n") |&amp;gt; ignore
Line 115:                  
&lt;font color=red&gt;Line
116: using (Mvc.Html.FormExtensions.BeginForm this.Html) (fun _ -&amp;gt; &lt;/font&gt;Line
117: __w.Write("\r\n\r\n &amp;lt;p&amp;gt;Inside a form&amp;lt;/p&amp;gt;\r\n\r\n") |&amp;gt; ignore Line
118: ) &lt;/pre&gt;
&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/p&gt;
&lt;p&gt;
As the error says, this is because the __w variable is mutable, so we can't play with
it inside a lambda. I'm not sure if this will be worked around -- they'd have to change
the codegen quite a bit, I'd think. As a side note, the F# CTP does not support C#
extension methods (hence the verbose calling of BeginForm), but F# will eventually
-- maybe in the Beta.
&lt;/p&gt;
&lt;p&gt;
The way we must scope is with a use binding. There's no way I see to accomplish this
with whitespace alone. Due to the ASPX translation process, this would probably be
very error prone. Instead, we can simply put the use binding inside a do expression:
&lt;/p&gt;
&lt;blockquote style="MARGIN-RIGHT: 0px" dir=ltr&gt; 
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 14pt"&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="COLOR: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;b&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;Demo&lt;span style="COLOR: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;b&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="BACKGROUND: #ffee62"&gt;&amp;lt;%&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
do (use form = Mvc.Html.FormExtensions.BeginForm this.Html &lt;span style="BACKGROUND: #ffee62"&gt;%&amp;gt;&lt;/span&gt;
&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;&amp;lt;&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;b&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;Inside
the form&lt;span style="COLOR: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;b&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="MARGIN: 0px"&gt;
&lt;span style="BACKGROUND: #ffee62"&gt;&amp;lt;%&lt;/span&gt; ) &lt;span style="BACKGROUND: #ffee62"&gt;%&amp;gt;&lt;/span&gt;
&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;&amp;lt;&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;b&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;Outside
of the form&lt;span style="COLOR: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="COLOR: #a31515"&gt;b&lt;/span&gt;&lt;span style="COLOR: blue"&gt;&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;/blockquote&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
The parentheses setup the scope exactly how we want it.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=cc0a8d5c-102f-452b-927c-59b2ca2017ca" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,cc0a8d5c-102f-452b-927c-59b2ca2017ca.aspx</comments>
      <category>ASP.NET</category>
      <category>FSharp</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=7583965b-185a-4677-ad9e-96c1d6e8abaa</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,7583965b-185a-4677-ad9e-96c1d6e8abaa.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,7583965b-185a-4677-ad9e-96c1d6e8abaa.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=7583965b-185a-4677-ad9e-96c1d6e8abaa</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://www.atrevido.net/blog/2009/04/01/Using+Fluent+NHibernate+With+F.aspx">Last
time</a>, I hacked up some rudimentary support for F# and Fluent NHibernate. It really
looked ugly. I looked into what I could do to make it not look as sucky. 
</p>
        <p>
First off, having to write a full lambda for each mapping was annoying. F# quotations
don't have to be lambdas, unlike C#'s expressions. So, instead of having to write,
say, "fun x -&gt; x.Foo", we can write "x.Foo", assuming there's a local variable
x with the right type. The ClassMap subclass now expects these types of quotations
than full lambdas.
</p>
        <p>
Next, I experimented with using type extensions to overload functions like Id and
Map, however I found out that F#, at least currently, does not add in type extensions
for overload resolution. So I ended up having a new subclass of ClassMap&lt;T&gt;,
'T ClassMapQ. I used the Q suffix consistently to denote "quotations". I added type
extensions for most of the other mapping types so that quotations could be used.
</p>
        <p>
As to the question of having to tag on " |&gt; ignore " to each mapping, I decided
to write an extension propery for IMappingPart called Done, which is simply unit.
Finally, the problem of lazy loading I took care of by setting "use_proxy_validator"
to false, as mentioned <a href="http://stackoverflow.com/questions/741489/ignore-public-internal-fields-for-nhibernate-proxy">here</a>.
The end result is that this mapping code:
</p>
        <div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt">
          <pre>
            <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px">type
StoreMap() <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">=</span> inherit
ClassMap&lt;Store&gt;() <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">do</span><span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">base</span>.Not.LazyLoad() <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">base</span>.Id
~@@ &lt;@ fun x -&gt; x.Id @&gt; |&gt; ignore <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">base</span>.Map
~@@ &lt;@ fun x -&gt; x.Name @&gt; |&gt; ignore (<span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">base</span>.HasManyX
&lt;@ fun x -&gt; upcast x.Staff @&gt;) .LazyLoad() .Inverse().Cascade.All() |&gt;
ignore (<span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">base</span>.HasManyToManyX
&lt;@ fun x -&gt; upcast x.Products @&gt;) .Cascade.All() .WithTableName(<span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px">"StoreProduct"</span>)
|&gt; ignore </span>
          </pre>
        </div>
        <!--EndFragment-->
        <p>
Is now:
</p>
        <p>
          <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px">type
StoreMap() <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">as</span> m <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">=</span> inherit
ClassMapQ&lt;Store&gt;() <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px">do</span><br />
    let x <span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px">=</span> m.DefaultX<br />
    (m.IdQ &lt;@ x.Id @&gt;).Done<br />
    (m.MapQ &lt;@ x.Name @&gt;).Done<br />
    (m.HasManyQ &lt;@ seq x.Staff @&gt;)<br />
        .LazyLoad()<br />
        .Inverse().Cascade.All()<br />
        .Done<br />
    (m.HasManyToManyQ &lt;@ seq x.Products @&gt;)<br />
        .LazyLoad()<br />
        .Cascade.All()<br />
        .WithTableName(<span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px">"StoreProduct"</span>)<br />
        .Done</span>
        </p>
        <p>
This is pretty enough that I'm satisfied with how well F# interops. Most of the things
I figured out here will apply to other .NET OO APIs, not just this one.
</p>
        <p>
I am hoping that VS2010 Beta 1 will ship soon, as F# is getting some interesting upgrades
then. With that, it should be easier to extend the support to other parts of NHibernate,
such as querying, and perhaps integrate in NHibernate.Linq.
</p>
        <img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=7583965b-185a-4677-ad9e-96c1d6e8abaa" />
      </body>
      <title>Update on F# with Fluent NHibernate</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,7583965b-185a-4677-ad9e-96c1d6e8abaa.aspx</guid>
      <link>http://www.atrevido.net/blog/2009/04/23/Update+On+F+With+Fluent+NHibernate.aspx</link>
      <pubDate>Thu, 23 Apr 2009 19:06:45 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://www.atrevido.net/blog/2009/04/01/Using+Fluent+NHibernate+With+F.aspx"&gt;Last
time&lt;/a&gt;, I hacked up some rudimentary support for F# and Fluent NHibernate. It really
looked ugly.&amp;nbsp;I&amp;nbsp;looked into what I could&amp;nbsp;do to make it not look as sucky. 
&lt;/p&gt;
&lt;p&gt;
First off, having to write a full lambda for each mapping was annoying. F# quotations
don't have to be lambdas, unlike C#'s expressions. So, instead of having to write,
say, "fun x -&amp;gt; x.Foo", we can write "x.Foo", assuming there's a local variable
x with the right type. The ClassMap subclass now expects these types of quotations
than full lambdas.
&lt;/p&gt;
&lt;p&gt;
Next, I experimented with using type extensions to overload functions like Id and
Map, however I found out that F#, at least currently, does not add in type extensions
for overload resolution. So I ended up having a new subclass of ClassMap&amp;lt;T&amp;gt;,
'T ClassMapQ. I used the Q suffix consistently to denote "quotations". I added type
extensions for most of the other mapping types so that quotations could be used.
&lt;/p&gt;
&lt;p&gt;
As to the question of having to tag on " |&amp;gt; ignore " to each mapping, I decided
to write an extension propery for IMappingPart&amp;nbsp;called Done, which is simply unit.
Finally, the problem of lazy loading I took care of by setting "use_proxy_validator"
to false, as mentioned &lt;a href="http://stackoverflow.com/questions/741489/ignore-public-internal-fields-for-nhibernate-proxy"&gt;here&lt;/a&gt;.
The end result is that this mapping code:
&lt;/p&gt;
&lt;div style="FONT-FAMILY: Consolas; BACKGROUND: white; COLOR: black; FONT-SIZE: 11pt"&gt;&lt;pre&gt;&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px"&gt;type
StoreMap() &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;=&lt;/span&gt; inherit
ClassMap&amp;lt;Store&amp;gt;() &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;do&lt;/span&gt; &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;base&lt;/span&gt;.Not.LazyLoad() &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;base&lt;/span&gt;.Id
~@@ &amp;lt;@ fun x -&amp;gt; x.Id @&amp;gt; |&amp;gt; ignore &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;base&lt;/span&gt;.Map
~@@ &amp;lt;@ fun x -&amp;gt; x.Name @&amp;gt; |&amp;gt; ignore (&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;base&lt;/span&gt;.HasManyX
&amp;lt;@ fun x -&amp;gt; upcast x.Staff @&amp;gt;) .LazyLoad() .Inverse().Cascade.All() |&amp;gt;
ignore (&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;base&lt;/span&gt;.HasManyToManyX
&amp;lt;@ fun x -&amp;gt; upcast x.Products @&amp;gt;) .Cascade.All() .WithTableName(&lt;span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px"&gt;"StoreProduct"&lt;/span&gt;)
|&amp;gt; ignore &lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;!--EndFragment--&gt;
&lt;p&gt;
Is now:
&lt;/p&gt;
&lt;p&gt;
&lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: black; FONT-SIZE: 11px"&gt;type
StoreMap() &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;as&lt;/span&gt; m &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;=&lt;/span&gt; inherit
ClassMapQ&amp;lt;Store&amp;gt;() &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: blue; FONT-SIZE: 11px"&gt;do&lt;/span&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; let x &lt;span style="BACKGROUND-COLOR: transparent; FONT-FAMILY: Courier New; COLOR: red; FONT-SIZE: 11px"&gt;=&lt;/span&gt; m.DefaultX&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; (m.IdQ &amp;lt;@ x.Id @&amp;gt;).Done&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; (m.MapQ &amp;lt;@ x.Name @&amp;gt;).Done&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; (m.HasManyQ &amp;lt;@ seq x.Staff @&amp;gt;)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .LazyLoad()&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Inverse().Cascade.All()&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Done&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; (m.HasManyToManyQ &amp;lt;@ seq x.Products @&amp;gt;)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .LazyLoad()&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Cascade.All()&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .WithTableName(&lt;span style="BACKGROUND-COLOR: #e4e4e4; FONT-FAMILY: Courier New; COLOR: #666666; FONT-SIZE: 11px"&gt;"StoreProduct"&lt;/span&gt;)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Done&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
This is pretty enough that I'm satisfied with how well F# interops. Most of the things
I figured out here will apply to other .NET OO APIs, not just this one.
&lt;/p&gt;
&lt;p&gt;
I am hoping that VS2010 Beta 1 will ship soon, as F# is getting some interesting upgrades
then. With that, it should be easier to extend the support to other parts of NHibernate,
such as querying, and perhaps integrate in NHibernate.Linq.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=7583965b-185a-4677-ad9e-96c1d6e8abaa" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,7583965b-185a-4677-ad9e-96c1d6e8abaa.aspx</comments>
      <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=cfe96f53-b5ad-4283-a498-e047d0027328</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,cfe96f53-b5ad-4283-a498-e047d0027328.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,cfe96f53-b5ad-4283-a498-e047d0027328.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=cfe96f53-b5ad-4283-a498-e047d0027328</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">I wanted to install the new Windows Live
-- Messenger looks better (normal windows instead of custom, yey!). Unfortunately,
the installer (wlsetup-web) has an annoying version check. Fortunately, it's nothing
OllyDbg couldn't patch.<br /><br />
For the paranoid, you can check it against the original:<br /><br />
&gt;fc wlsetup-web.exe wlsetup-web.original.exe<br />
Comparing files wlsetup-web.exe and WLSETUP-WEB.ORIGINAL.EXE<br />
00019DDD: C3 6A<br />
00019DDE: 90 20<br /><br />
I've only tested on Windows 2008, 32 Bit, English, and I only installed Messenger.
But it appears to work just fine. (I had to manually uninstall the current Messenger
version first.)<br /><br />
Here's to hoping the final version of the "new wave" of Live removes this check for
us. Enjoy! 
<p></p><a href="http://www.atrevido.net/blog/content/binary/wlsetup-web.exe">wlsetup-web.exe
(990.5 KB)</a><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=cfe96f53-b5ad-4283-a498-e047d0027328" /></body>
      <title>Windows Live Installer for Windows 2008</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,cfe96f53-b5ad-4283-a498-e047d0027328.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/12/03/Windows+Live+Installer+For+Windows+2008.aspx</link>
      <pubDate>Wed, 03 Dec 2008 02:48:06 GMT</pubDate>
      <description>I wanted to install the new Windows Live -- Messenger looks better (normal windows instead of custom, yey!). Unfortunately, the installer (wlsetup-web) has an annoying version check. Fortunately, it's nothing OllyDbg couldn't patch.&lt;br&gt;
&lt;br&gt;
For the paranoid, you can check it against the original:&lt;br&gt;
&lt;br&gt;
&amp;gt;fc wlsetup-web.exe wlsetup-web.original.exe&lt;br&gt;
Comparing files wlsetup-web.exe and WLSETUP-WEB.ORIGINAL.EXE&lt;br&gt;
00019DDD: C3 6A&lt;br&gt;
00019DDE: 90 20&lt;br&gt;
&lt;br&gt;
I've only tested on Windows 2008, 32 Bit, English, and I only installed Messenger.
But it appears to work just fine. (I had to manually uninstall the current Messenger
version first.)&lt;br&gt;
&lt;br&gt;
Here's to hoping the final version of the "new wave" of Live removes this check for
us. Enjoy! 
&lt;p&gt;
&lt;/p&gt;
&lt;a href="http://www.atrevido.net/blog/content/binary/wlsetup-web.exe"&gt;wlsetup-web.exe
(990.5 KB)&lt;/a&gt;&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=cfe96f53-b5ad-4283-a498-e047d0027328" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,cfe96f53-b5ad-4283-a498-e047d0027328.aspx</comments>
      <category>Misc. Technology</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=3a590b35-9327-44c6-bd61-bff9119c094f</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,3a590b35-9327-44c6-bd61-bff9119c094f.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,3a590b35-9327-44c6-bd61-bff9119c094f.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=3a590b35-9327-44c6-bd61-bff9119c094f</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">On a current project, I'm using F# with
ASMX Web Services (Mono, so no WCF). I started off declaring some types like this:<br /><br /><font face="Courier New">type Account() =<br />
    [&lt;DefaultValue&gt;]<br />
    val mutable Name : string<br />
    [&lt;DefaultValue&gt;]<br />
    val mutable Data : byte array</font><br /><br />
We have to tag "default value" to tell F# it should go generate the default (Unchecked.defaultof&lt;'a&gt;)
-- in this case, null.<br /><br />
Unfortunately, the serialized XML is not what we want. Currently F# generates both
a public field ("_Name") and a get/set property ("Name") to access it. I'm not sure
why this is, but there's probably some interesting reason (the part of the spec is
10.2.7 Explicit Fields, but it doesn't mention the implementation). The workaround
is simple: tag the field with "XmlIgnore".<br /><br />
As of F# 1.9.3.7, you can choose to target an attribute at the property or the field
for a val in a class type. See: <a href="http://blogs.msdn.com/dsyme/archive/2007/11/30/full-release-notes-for-f-1-9-3-7.aspx">http://blogs.msdn.com/dsyme/archive/2007/11/30/full-release-notes-for-f-1-9-3-7.aspx</a> (I
didn't find this part in the spec.)<br /><br />
So, the revised declaration for the XmlSerialization-friendly type is:<br /><br /><font face="Courier New">type Account() =<br />
    [&lt;DefaultValue; field: XmlIgnore&gt;]<br />
    val mutable Name : string<br />
    [&lt;DefaultValue; field: XmlIgnore&gt;]<br />
    val mutable Data : byte array</font><br /><br />
I found that to add a lot of noise, so I aliased them:<br /><br /><font face="Courier New">type DV = DefaultValueAttribute<br />
type XI = XmlIgnoreAttribute<br /><br />
type Account() =<br />
    [&lt;DV; field: XI&gt;] val mutable Name : string<br />
    [&lt;DV; field: XI&gt;] val mutable Data : byte array</font><br /><br />
Now it works just fine and creates the XML we'd expect. 
<br /><br />
One other thing might bite you: null. F# rightfully eschews null. If you have a function
that returns one of these types, you'll find it won't let you return null:<br /><br /><font face="Courier New">&gt; let test() : Account = null;;<br />
  let test() : Account = null;;<br />
  -----------------------^^^^^<br />
stdin(6,24): error FS0043: The type 'Account' does not have 'null' as a proper value.<br /></font><br />
This is generally good, but unfortunately, interop with the unenlightened world is
sometimes necessary. The right way to do this is:<br /><br /><font face="Courier New">let test() : Account = Unchecked.defaultof&lt;Account&gt;;;</font><br /><br />
That's a bit too verbose for my liking, since I have to go annotate the type. A simple
function will get around that:<br /><br /><font face="Courier New">&gt; let inline getnull() = Unchecked.defaultof&lt;_&gt;;;<br />
val inline getnull : unit -&gt; 'a<br /><br />
&gt; let test() : Account = getnull();;<br />
val test : unit -&gt; Account<br /></font><br />
Yes, I know it's not null, but default, but I think the purpose is clear enough.<br /><br /><p></p><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=3a590b35-9327-44c6-bd61-bff9119c094f" /></body>
      <title>XmlSerialization for F# Types</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,3a590b35-9327-44c6-bd61-bff9119c094f.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/11/25/XmlSerialization+For+F+Types.aspx</link>
      <pubDate>Tue, 25 Nov 2008 02:16:33 GMT</pubDate>
      <description>On a current project, I'm using F# with ASMX Web Services (Mono, so no WCF). I started off declaring some types like this:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;type Account() =&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; [&amp;lt;DefaultValue&amp;gt;]&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; val mutable Name : string&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; [&amp;lt;DefaultValue&amp;gt;]&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; val mutable Data : byte array&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
We have to tag "default value" to tell F# it should go generate the default (Unchecked.defaultof&amp;lt;'a&amp;gt;)
-- in this case, null.&lt;br&gt;
&lt;br&gt;
Unfortunately, the serialized XML is not what we want. Currently F# generates both
a public field ("_Name") and a get/set property ("Name") to access it. I'm not sure
why this is, but there's probably some interesting reason (the part of the spec is
10.2.7 Explicit Fields, but it doesn't mention the implementation). The workaround
is simple: tag the field with "XmlIgnore".&lt;br&gt;
&lt;br&gt;
As of F# 1.9.3.7, you can choose to target an attribute at the property or the field
for a val in a class type. See: &lt;a href="http://blogs.msdn.com/dsyme/archive/2007/11/30/full-release-notes-for-f-1-9-3-7.aspx"&gt;http://blogs.msdn.com/dsyme/archive/2007/11/30/full-release-notes-for-f-1-9-3-7.aspx&lt;/a&gt; (I
didn't find this part in the spec.)&lt;br&gt;
&lt;br&gt;
So, the revised declaration for the XmlSerialization-friendly type is:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;type Account() =&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; [&amp;lt;DefaultValue; field: XmlIgnore&amp;gt;]&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; val mutable Name : string&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; [&amp;lt;DefaultValue; field: XmlIgnore&amp;gt;]&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; val mutable Data : byte array&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
I found that to add a lot of noise, so I aliased them:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;type DV = DefaultValueAttribute&lt;br&gt;
type XI = XmlIgnoreAttribute&lt;br&gt;
&lt;br&gt;
type Account() =&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; [&amp;lt;DV; field: XI&amp;gt;] val mutable Name : string&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; [&amp;lt;DV; field: XI&amp;gt;] val mutable Data : byte array&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
Now it works just fine and creates the XML we'd expect. 
&lt;br&gt;
&lt;br&gt;
One other thing might bite you: null. F# rightfully eschews null. If you have a function
that returns one of these types, you'll find it won't let you return null:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;&amp;gt; let test() : Account = null;;&lt;br&gt;
&amp;nbsp; let test() : Account = null;;&lt;br&gt;
&amp;nbsp; -----------------------^^^^^&lt;br&gt;
stdin(6,24): error FS0043: The type 'Account' does not have 'null' as a proper value.&lt;br&gt;
&lt;/font&gt;
&lt;br&gt;
This is generally good, but unfortunately, interop with the unenlightened world is
sometimes necessary. The right way to do this is:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;let test() : Account = Unchecked.defaultof&amp;lt;Account&amp;gt;;;&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
That's a bit too verbose for my liking, since I have to go annotate the type. A simple
function will get around that:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;&amp;gt; let inline getnull() = Unchecked.defaultof&amp;lt;_&amp;gt;;;&lt;br&gt;
val inline getnull : unit -&amp;gt; 'a&lt;br&gt;
&lt;br&gt;
&amp;gt; let test() : Account = getnull();;&lt;br&gt;
val test : unit -&amp;gt; Account&lt;br&gt;
&lt;/font&gt;
&lt;br&gt;
Yes, I know it's not null, but default, but I think the purpose is clear enough.&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=3a590b35-9327-44c6-bd61-bff9119c094f" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,3a590b35-9327-44c6-bd61-bff9119c094f.aspx</comments>
      <category>FSharp</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=1533c44a-63b4-44b4-a055-bd82344dd464</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,1533c44a-63b4-44b4-a055-bd82344dd464.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,1533c44a-63b4-44b4-a055-bd82344dd464.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=1533c44a-63b4-44b4-a055-bd82344dd464</wfw:commentRss>
      <slash:comments>5</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">Compiling for Silverlight 2 is a bit of
a pain still. It's even worse with F#, because the Silverlight project system cannot
tell when you're building your F# components correctly (using the right flags). So
you get this error:<br /><br /><font face="Courier New">---------------------------<br />
Microsoft Visual Studio<br />
---------------------------<br />
You can only add project references to other Silverlight projects in the solution.<br />
---------------------------<br />
OK   
<br />
---------------------------<br /></font><br />
This happens even if you set up the F# compiler options correctly by adding:<br /><font face="Courier New">--standalone --noframework --cliroot "C:\program Files\Microsoft
Silverlight\2.0.31005.0"</font><br /><br />
It still happens if you reference the DLL directly (FSLib1\bin\debug), you get the
same error! Apparently VS or Silverlight projects go and try to find the project relating
to the DLLs when you add a reference. So, the solution is easy: Move the DLL somewhere
else. Then you can add a file reference, and it will work just fine.<br /><br />
One more problem. I get an FSC error when I turn optimize code on:<br /><font face="Courier New">C:\test\SilverlightApplication1\FSC(0,0): error FS0193: internal
error: the module/namespace 'System' from compilation unit 'mscorlib' did not contain
the namespace, module or type 'MarshalByRefObject'</font><br /><br />
If I leave optimize code off, then it seems to work. Good luck.<br /><br /><a href="http://stackoverflow.com/questions/237044/how-does-silverlight-determine-an-assembly-is-silverlight">http://stackoverflow.com/questions/237044/how-does-silverlight-determine-an-assembly-is-silverlight</a><br /><br /><br /><p></p><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=1533c44a-63b4-44b4-a055-bd82344dd464" /></body>
      <title>F# 1.9.6.2 and Silverlight 2</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,1533c44a-63b4-44b4-a055-bd82344dd464.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/10/28/F+1962+And+Silverlight+2.aspx</link>
      <pubDate>Tue, 28 Oct 2008 22:27:50 GMT</pubDate>
      <description>Compiling for Silverlight 2 is a bit of a pain still. It's even worse with F#, because the Silverlight project system cannot tell when you're building your F# components correctly (using the right flags). So you get this error:&lt;br&gt;
&lt;br&gt;
&lt;font face="Courier New"&gt;---------------------------&lt;br&gt;
Microsoft Visual Studio&lt;br&gt;
---------------------------&lt;br&gt;
You can only add project references to other Silverlight projects in the solution.&lt;br&gt;
---------------------------&lt;br&gt;
OK&amp;nbsp;&amp;nbsp; 
&lt;br&gt;
---------------------------&lt;br&gt;
&lt;/font&gt;
&lt;br&gt;
This happens even if you set up the F# compiler options correctly by adding:&lt;br&gt;
&lt;font face="Courier New"&gt;--standalone --noframework --cliroot "C:\program Files\Microsoft
Silverlight\2.0.31005.0"&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
It still happens if you reference the DLL directly (FSLib1\bin\debug), you get the
same error! Apparently VS or Silverlight projects go and try to find the project relating
to the DLLs when you add a reference. So, the solution is easy: Move the DLL somewhere
else. Then you can add a file reference, and it will work just fine.&lt;br&gt;
&lt;br&gt;
One more problem. I get an FSC error when I turn optimize code on:&lt;br&gt;
&lt;font face="Courier New"&gt;C:\test\SilverlightApplication1\FSC(0,0): error FS0193: internal
error: the module/namespace 'System' from compilation unit 'mscorlib' did not contain
the namespace, module or type 'MarshalByRefObject'&lt;/font&gt;
&lt;br&gt;
&lt;br&gt;
If I leave optimize code off, then it seems to work. Good luck.&lt;br&gt;
&lt;br&gt;
&lt;a href="http://stackoverflow.com/questions/237044/how-does-silverlight-determine-an-assembly-is-silverlight"&gt;http://stackoverflow.com/questions/237044/how-does-silverlight-determine-an-assembly-is-silverlight&lt;/a&gt;
&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=1533c44a-63b4-44b4-a055-bd82344dd464" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,1533c44a-63b4-44b4-a055-bd82344dd464.aspx</comments>
      <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=67023afb-7fdb-40c3-a14f-1437c4313a88</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,67023afb-7fdb-40c3-a14f-1437c4313a88.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,67023afb-7fdb-40c3-a14f-1437c4313a88.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=67023afb-7fdb-40c3-a14f-1437c4313a88</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">In this image, we see Banco Industrial
(Guatemala) online bank. The Flash applet displays:<br /><br />
  System Hours - Monday to Sunday: From 6:00am to 22:00 hours. Last day of month:
From 6am to 21:30 hours<br /><br />
WTF? Closing the online bank? By the way, who writes "Monday to Sunday?" And a 30
minute difference on the last day of the month? The levels of incompetence here just
stack up, but it's par for the country. 
<br /><p></p><img src="http://www.atrevido.net/blog/content/binary/BancoIndustrialFail.jpg" border="0" /><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=67023afb-7fdb-40c3-a14f-1437c4313a88" /></body>
      <title>Banco Industrial Fail: Online Banking Hours</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,67023afb-7fdb-40c3-a14f-1437c4313a88.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/10/10/Banco+Industrial+Fail+Online+Banking+Hours.aspx</link>
      <pubDate>Fri, 10 Oct 2008 03:13:41 GMT</pubDate>
      <description>In this image, we see Banco Industrial (Guatemala) online bank. The Flash applet displays:&lt;br&gt;
&lt;br&gt;
&amp;nbsp; System Hours - Monday to Sunday: From 6:00am to 22:00 hours. Last day of month:
From 6am to 21:30 hours&lt;br&gt;
&lt;br&gt;
WTF? Closing the online bank? By the way, who writes "Monday to Sunday?" And a 30
minute difference on the last day of the month? The levels of incompetence here just
stack up, but it's par for the country. 
&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img src="http://www.atrevido.net/blog/content/binary/BancoIndustrialFail.jpg" border="0"&gt;&lt;img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=67023afb-7fdb-40c3-a14f-1437c4313a88" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,67023afb-7fdb-40c3-a14f-1437c4313a88.aspx</comments>
      <category>Guatemala</category>
    </item>
    <item>
      <trackback:ping>http://www.atrevido.net/blog/Trackback.aspx?guid=9b1f6230-dfb8-4ed2-b1e0-d216786b6d4c</trackback:ping>
      <pingback:server>http://www.atrevido.net/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.atrevido.net/blog/PermaLink,guid,9b1f6230-dfb8-4ed2-b1e0-d216786b6d4c.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.atrevido.net/blog/CommentView,guid,9b1f6230-dfb8-4ed2-b1e0-d216786b6d4c.aspx</wfw:comment>
      <wfw:commentRss>http://www.atrevido.net/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=9b1f6230-dfb8-4ed2-b1e0-d216786b6d4c</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">Every now and then I read an article on
VoIP security. These articles almost always go over the obvious stuff such as lack
of encryption, eavesdropping and ensuring you firewall your networks and so on. While
certainly major issues, especially for a corporate deployment, there are still some
other interesting issues.<br /><br />
One thing that keeps getting mentioned is the possibility for VoIP peering. Peering
allows VoIP providers to send calls directly to each other (possibly over the Internet,
maybe over [semi-]private connections). The main idea is cost savings, since the call
doesn't need to go out over the public telephone network (PSTN). 
<br /><br />
To accomplish this, they'll set up a shared database mapping telephone numbers to
VoIP providers. So, when a VoIP provider attempts to place a call, it'll consult this
directory first. If it finds the number in there, it'll send it direct to the provider
instead of over the PSTN. All the providers sign some sort of contract to say they'll
be careful with the database and not populate it with invalid entries. Let's just
assume the VoIP provider is trustworthy and hires trustworthy people (this is a stupid
assumption, but I've had a peering company tell me this, as the security problems
are too obvious without this assumption).<br /><br />
This system actually holds true inside of a VoIP provider's own network. A provider
will want to terminate directly to a customer instead of out via the PSTN then back
into their own network. So they'll probably have a directory of their own numbers
so they can route those directly.<br /><br />
Well first off, now every peering member's security is bound by the security of every
other member. If just one "trustworthy" peering provider gets compromised (not a hard
task - more on that later), they can pollute the shared directory and hijack phone
numbers. Being able to redirect a financial institution's phone number sounds like
a profitable attack. An attacker can simply route the call to their system, then pass
it through to the PSTN to avoid detection by users. Note that none of the security
technologies available can prevent problems with a subverted, trusted, directory.<br /><br /><b>But it gets easier...</b><br />
Many providers let you port your existing number to them when you sign up. From my
limited experience, I've seen some of them immediately activate the number for you,
so you can get started and going with their network while the port happens. A port
can take a bit of time (and for now, let's assume the porting system is secure), so
this sounds like a reasonable approach. 
<br /><br />
Wrong. First off, the new customer's number will probably go right into the provider's
internal database, so all calls from that provider will go to the <strike>customer</strike> attacker.
Depending on the size of the provider, this could be a pretty decent attack in and
of itself.<br /><br />
But now, suppose the peering contract didn't specify not provisioning ports-in-progress,
or if it did, the implementation people messed up. Now ALL the VoIP providers have
been compromised, by a single provider who was agressive in their porting tactics.<br /><br />
Eventually it'll probably get resolved, but even a few hours or days of compromising
a valuable phone number can be a significant attack.<br /><br /><b>What's the threat?</b><br />
As a consumer, in general, I'd not worry too much about people trying to tap my line,
just like I rarely worry about the safety of my wired Internet connection. But similar
to intercepting credit card info versus hacking a company's database, this is a much
juicier target. An attacker who pulls this off gets access to bulk information. Thus,
I think the threat of something like this happening is much higher than having my
individual calls monitored.<br /><br /><p></p><img width="0" height="0" src="http://www.atrevido.net/blog/aggbug.ashx?id=9b1f6230-dfb8-4ed2-b1e0-d216786b6d4c" /></body>
      <title>VoIP Security - Peering</title>
      <guid isPermaLink="false">http://www.atrevido.net/blog/PermaLink,guid,9b1f6230-dfb8-4ed2-b1e0-d216786b6d4c.aspx</guid>
      <link>http://www.atrevido.net/blog/2008/10/10/VoIP+Security+Peering.aspx</link>
      <pubDate>Fri, 10 Oct 2008 00:25:14 GMT</pubDate>
      <description>Every now and then I read an article on VoIP security. These articles almost always go over the obvious stuff such as lack of encryption, eavesdropping and ensuring you firewall your networks and so on. While certainly major issues, especially for a corporate deployment, there are still some other interesting issues.&lt;br&gt;
&lt;br&gt;
One thing that keeps getting mentioned is the possibility for VoIP peering. Peering
allows VoIP providers to send calls directly to each other (possibly over the Internet,
maybe over [semi-]private connections). The main idea is cost savings, since the call
doesn't need to go out over the public telephone network (PSTN). 
&lt;br&gt;
&lt;br&gt;
To accomplish this, they'll set up a shared database mapping telephone numbers to
VoIP providers. So, when a VoIP provider attempts to place a call, it'll consult this
directory first. If it finds the number in there, it'll send it direct to the provider
instead of over the PSTN. All the providers sign some sort of contract to say they'll
be careful with the database and not populate it with invalid entries. Let's just
assume the VoIP provider is trustworthy and hires trustworthy people (this is a stupid
assumption, but I've had a peering company tell me this, as the security problems
are too obvious without this assumption).&lt;br&gt;
&lt;br&gt;
This system actually holds true inside of a VoIP provider's own network. A provider
will want to terminate directly to a customer instead of out via the PSTN then back
into their own network. So they'll probably have a directory of their own numbers
so they can route those directly.&lt;br&gt;
&lt;br&gt;
Well first off, now every peering member's security is bound by the security of every
other member. If just one "trustworthy" peering provider gets compromised (not a hard
task - more on that later), they can pollute the shared directory and hijack phone
numbers. Being able to redirect a financial institution's phone number sounds like
a profitable attack. An attacker can simply route the call to their system, then pass
it through to the PSTN to avoid detection by users. Note that none of the security
technologies available can prevent problems with a subverted, trusted, directory.&lt;br&gt;
&lt;br&gt;
&lt;b&gt;But it gets easier...&lt;/b&gt;
&lt;br&gt;
Many providers let you port your existing number to them when you sign up. From my
limited experience, I've seen some of them immediately activate the number for you,
so you can get started and going with their network while the port happens. A port
can take a bit of time (and for now, let's assume the porting system is secure), so
this sounds like a reasonable approach. 
&lt;br&gt;
&lt;br&gt;
Wrong. First off, the new customer's number will probably go right into the provider's
internal database, so all calls from that provider will go to the &lt;strike&gt;customer&lt;/strike&gt; attacker.
Depending on the size of the provider, this could be a pretty decent attack in and
of itself.&lt;br&gt;
&lt;br&gt;
But now, suppose the peering contract didn't specify not provisioning ports-in-progress,
or if it did, the implementation people messed up. Now ALL the VoIP providers have
been compromised, by a single provider who was agressive in their porting tactics.&lt;br&gt;
&lt;br&gt;
Eventually it'll probably get resolved, but even a few hours or days of compromising
a valuable phone number can be a significant attack.&lt;br&gt;
&lt;br&gt;
&lt;b&gt;What's the threat?&lt;/b&gt;
&lt;br&gt;
As a consumer, in general, I'd not worry too much about people trying to tap my line,
just like I rarely worry about the safety of my wired Internet connection. But similar
to intercepting credit card info versus hacking a company's database, this is a much
juicier target. An attacker who pulls this off gets access to bulk information. Thus,
I think the threat of something like this happening is much higher than having my
individual calls monitored.&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=9b1f6230-dfb8-4ed2-b1e0-d216786b6d4c" /&gt;</description>
      <comments>http://www.atrevido.net/blog/CommentView,guid,9b1f6230-dfb8-4ed2-b1e0-d216786b6d4c.aspx</comments>
      <category>Security</category>
      <category>VoIP</category>
    </item>
  </channel>
</rss>