<?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:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Useless Inc. - Development|Compact Framework</title>
    <link>http://www.tomergabel.com/</link>
    <description>Tomer Gabel's annoying spot on the 'net</description>
    <language>en-us</language>
    <copyright>Tomer Gabel</copyright>
    <lastBuildDate>Sun, 11 Mar 2007 14:40:49 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>tomer@tomergabel.com</managingEditor>
    <webMaster>tomer@tomergabel.com</webMaster>
    <item>
      <trackback:ping>http://www.tomergabel.com/Trackback.aspx?guid=7577aed0-917a-4c35-810d-a0c47b558211</trackback:ping>
      <pingback:server>http://www.tomergabel.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.tomergabel.com/PermaLink,guid,7577aed0-917a-4c35-810d-a0c47b558211.aspx</pingback:target>
      <dc:creator>Tomer Gabel</dc:creator>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
With my project finally nearing completion, it's nigh time for Microsoft to release
yet another update to the .NET Compact Framework 2.0. <a href="http://www.microsoft.com/downloads/details.aspx?familyid=aea55f2f-07b5-4a8c-8a44-b4e1b196d5c0&amp;displaylang=en">Service
Pack 2</a> ought to bring it to about "beta 2" level.
</p>
        <p>
Check out these gems:
</p>
        <span>
          <ul>
            <li>
NETCF deadlocks on exit if native callback delegate has been called on native thread
(<em>this is one of the few bugs in the CF I </em>haven't<em> encountered. Ironic,
considering we make heavy use of native code in our project.</em>)</li>
            <li>
              <span>Access violation marshaling a class with a string field (<em>there is a dent
in the nearby wall on account of this one.</em>)</span>
            </li>
            <li>
TypeLoadException using generics with NETCF 2.0 (<em>TypeLoadExceptions in general
are a lot of fun in the CF.)</em></li>
            <span>
              <span>
                <li>
Installing multiple locales of same MSI results in multiple instances of NetCF showing
up in Add Remove Programs (<em>we've had some complaints regarding this from our client.
They'll be mighty pleased to hear this, I'm sure.)</em></li>
              </span>
            </span>
          </ul>
          <p>
            <span>Now don't get me wrong - I think the CF is an impressive platform, or at the
very least could've been. I would venture to say that the people on the CF implementation
team are probably skilled professionals just doing the best job they can. But I can't
forgive Microsoft - as a company - for shipping a half-baked, half-assed product that
even at version 2.0 and after two service packs is still riddled with bugs! It boggles
the mind that for any but the most hard-core developers, a <a href="http://www.opennetcf.org/home.ocf">third-party
extension</a> to the .NET CF is practically a necessity because the class library
itself is <em>simply inadequate</em>.</span>
          </p>
          <p>
            <span>As an aside, I seriously doubt we'll chance regression bugs this close to the
launch date, so we'll probably stick with SP1 (we've worked around the issues we've
encountered anyway.)</span>
          </p>
        </span>
        <img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=7577aed0-917a-4c35-810d-a0c47b558211" />
      </body>
      <title>Perfect timing</title>
      <guid isPermaLink="false">http://www.tomergabel.com/PermaLink,guid,7577aed0-917a-4c35-810d-a0c47b558211.aspx</guid>
      <link>http://www.tomergabel.com/PerfectTiming.aspx</link>
      <pubDate>Sun, 11 Mar 2007 14:40:49 GMT</pubDate>
      <description>&lt;p&gt;
With my project finally nearing completion, it's nigh time for Microsoft to release
yet another update to the .NET Compact Framework 2.0.&amp;nbsp;&lt;a href="http://www.microsoft.com/downloads/details.aspx?familyid=aea55f2f-07b5-4a8c-8a44-b4e1b196d5c0&amp;amp;displaylang=en"&gt;Service
Pack 2&lt;/a&gt; ought to bring it to about "beta 2" level.
&lt;/p&gt;
&lt;p&gt;
Check out these gems:
&lt;/p&gt;
&lt;span&gt; 
&lt;ul&gt;
&lt;li&gt;
NETCF deadlocks on exit if native callback delegate has been called on native thread
(&lt;em&gt;this is one of the few bugs in the CF I &lt;/em&gt;haven't&lt;em&gt; encountered. Ironic,
considering we make heavy use of native code in our project.&lt;/em&gt;)&lt;/li&gt;
&lt;li&gt;
&lt;span&gt;Access violation marshaling a class with a string field (&lt;em&gt;there is a dent
in the nearby wall on account of this one.&lt;/em&gt;)&lt;/span&gt;
&lt;/li&gt;
&lt;li&gt;
TypeLoadException using generics with NETCF 2.0 (&lt;em&gt;TypeLoadExceptions in general
are a lot of fun in the CF.)&lt;/em&gt;
&lt;/li&gt;&lt;span&gt;&lt;span&gt; 
&lt;li&gt;
Installing multiple locales of same MSI results in multiple instances of NetCF showing
up in Add Remove Programs (&lt;em&gt;we've had some complaints regarding this from our client.
They'll be mighty pleased to hear this, I'm sure.)&lt;/em&gt;
&lt;/li&gt;&lt;/span&gt;&lt;/span&gt;
&lt;/ul&gt;
&lt;p&gt;
&lt;span&gt;Now don't get me wrong - I think the CF is an impressive platform, or at the
very least could've been. I would venture to say that the people on the CF implementation
team are probably skilled professionals just doing the best job they can. But I can't
forgive Microsoft - as a company - for shipping a half-baked, half-assed product that
even at version 2.0 and after two service packs is still riddled with bugs! It boggles
the mind that for any but the most hard-core developers, a &lt;a href="http://www.opennetcf.org/home.ocf"&gt;third-party
extension&lt;/a&gt; to the .NET CF is practically a necessity because the class library
itself is &lt;em&gt;simply inadequate&lt;/em&gt;.&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;span&gt;As an aside, I seriously doubt we'll chance regression bugs this close to the
launch date, so we'll probably stick with SP1 (we've worked around the issues we've
encountered anyway.)&lt;/span&gt;
&lt;/span&gt;&gt;
&lt;img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=7577aed0-917a-4c35-810d-a0c47b558211" /&gt;</description>
      <category>Development</category>
      <category>Development/Compact Framework</category>
    </item>
    <item>
      <trackback:ping>http://www.tomergabel.com/Trackback.aspx?guid=23428e06-234d-4899-8ff3-52016f2e5c0d</trackback:ping>
      <pingback:server>http://www.tomergabel.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.tomergabel.com/PermaLink,guid,23428e06-234d-4899-8ff3-52016f2e5c0d.aspx</pingback:target>
      <dc:creator>Tomer Gabel</dc:creator>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
By far one of the most annoying aspects of the .NET Compact Framework is how heavily
it relies on P/Invoke to fill in the gaps. The framework itself is missing <em>huge</em> pieces
of functionality, and with the lack of C++/CLI for the Compact Framework a developer
is often time left with no choice but to hack around the missing functionality with
P/Invoke (or COM interop, if you have the patience to muck about with ATL).
</p>
        <p>
The problem is that, on occasion, a P/Invoke call would result in a <span class="codetext">MissingMethodException</span> (in
fact, if you're <em>really</em> unlucky, the type loader will throw the same exception
on loading the method actually making the P/Invoke call). Although a lot of the scenarios
have been thoroughly ironed out by now and can be resolved through a Google search
or some hacking on the developer's part, there is one scario that is esoteric enough
that I couldn't find any references to it on the internet: you can get a <span class="codetext">MissingMethodException</span> when <strong>you
are out of memory</strong>.
</p>
        <p>
We're working on an extremely large (in mobile proportions) and complex project, involving
massive amounts of .NET logic combined with a very large, performance-concious and
memory-hungry native codebase. We've had to hack around a lot of missing capabilities
in the .NET Compact Framework (as well as some bugs and/or shortcomings in other parts
of the OS), and one of our native calls would inconsistently throw a <span class="codetext">MisingMethodException</span>;
having reearched the problem for a day or two I was convinced that the problem was
an incorrect function prototype for the exported function and added explicit
calling convention declarations. This seemed to have resolved and I was content for
a couple of days, until the problem resurfaced.
</p>
        <p>
The exception content itself is next-to-useless, and since the same P/Invoke
call would work intermittently I was hoping that <a href="http://blogs.msdn.com/stevenpr/archive/2005/02/28/381744.aspx">enabling
the loader log</a> might supply some further information. Alas, all the log would
provide was the following line:
</p>
        <blockquote>
          <span class="codetext">
            <p>
Failed to find/load [SomeDll.dll] (even in [\Program Files\Somewhere\])
</p>
          </span>
        </blockquote>
        <p>
Not good. I then dug up <a href="http://blogs.msdn.com/netcfteam/archive/2005/07/24/442609.aspx">another
article</a> on the subject and proceeded to enable the interop log, which provided
some additional information:
</p>
        <blockquote>
          <span class="codetext">
            <p>
JIT ERROR FOR PINVOKE METHOD (Managed -&gt; Native): 
<br />
[pinvokeimpl][preservesig]<br />
int Workarounds::GetSinkWrapper(out IImageSink , IImageEncoder );<br />
int (I4_VAL) GetSinkWrapper(IImageSink&amp; ** (INTF_REF) , IImageEncoder *(INTF_VAL)
);
</p>
          </span>
        </blockquote>
        <p>
I was originally interested in the bizarre native signature generation
(specifically the <span class="codetext">IImageSink&amp; **</span> parameter - where'd
the reference come from?), but upon reading some valid log files for working
methods I was convinced that it's a dead duck. I then set my attention to the JIT
message: what has the JIT to do with a native function? I theorized that the
JIT is responsible for the native signature generation for native functions and kept
working under that assumption. That narrowed the question down to, "what went
wrong with the JIT compiler?"
</p>
        <p>
Eventually it occured to me that this might be yet another manifestation of the memory limitation
issue (processes under Windows CE 5.0 are limited to a 32MB address space). The P/Invoke
call is made fairly late into the application; I added a dummy function to the
library which I called on application initialization. This forced the JIT to
take care of the native library before anything was sucking up memory, and the issue
was resolved.
</p>
        <p>
The moral of the story? If you get <span class="codetext">MissingMethodExceptions</span> on
your P/Invoke calls, fisrt make sure your DLL is actually deployed; then check
the DllImport signature (you can find a lot of useful resources on <a href="http://msdn2.microsoft.com/en-us/netframework/aa497275.aspx">this
FAQ</a>). Finally, make sure you're not out of memory.
</p>
        <img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=23428e06-234d-4899-8ff3-52016f2e5c0d" />
      </body>
      <title>.NET Compact Framework, P/Invoke and MissingMethodException</title>
      <guid isPermaLink="false">http://www.tomergabel.com/PermaLink,guid,23428e06-234d-4899-8ff3-52016f2e5c0d.aspx</guid>
      <link>http://www.tomergabel.com/NETCompactFrameworkPInvokeAndMissingMethodException.aspx</link>
      <pubDate>Sat, 17 Feb 2007 14:26:26 GMT</pubDate>
      <description>&lt;p&gt;
By far one of the most annoying aspects of the .NET Compact Framework is how heavily
it relies on P/Invoke to fill in the gaps. The framework itself is missing &lt;em&gt;huge&lt;/em&gt; pieces
of functionality, and with the lack of C++/CLI for the Compact Framework a developer
is often time left with no choice but to hack around the missing functionality with
P/Invoke (or COM interop, if you have the patience to muck about with ATL).
&lt;/p&gt;
&lt;p&gt;
The problem is that, on occasion, a P/Invoke call would result in a &lt;span class="codetext"&gt;MissingMethodException&lt;/span&gt; (in
fact, if you're &lt;em&gt;really&lt;/em&gt; unlucky, the type loader will throw the same exception
on loading the method actually making the P/Invoke call). Although a lot of the&amp;nbsp;scenarios
have been thoroughly ironed out by now and can be resolved through a Google search
or some hacking on the developer's part, there is one scario that is esoteric enough
that I couldn't find any references to it on the internet: you can get a &lt;span class="codetext"&gt;MissingMethodException&lt;/span&gt; when &lt;strong&gt;you
are out of memory&lt;/strong&gt;.
&lt;/p&gt;
&lt;p&gt;
We're working on an extremely large (in mobile proportions) and complex project, involving
massive amounts of .NET logic combined with a very large, performance-concious and
memory-hungry native codebase. We've had to hack around a lot of missing capabilities
in the .NET Compact Framework (as well as some bugs and/or shortcomings in other parts
of the OS), and one of our native calls would inconsistently throw a &lt;span class="codetext"&gt;MisingMethodException&lt;/span&gt;;
having reearched the problem for a day or two I was convinced that the problem was
an incorrect function prototype for the exported function&amp;nbsp;and added explicit
calling convention declarations. This seemed to have resolved and I was content for
a couple of days, until the problem resurfaced.
&lt;/p&gt;
&lt;p&gt;
The exception content&amp;nbsp;itself is next-to-useless, and since the same P/Invoke
call would work intermittently I was hoping that &lt;a href="http://blogs.msdn.com/stevenpr/archive/2005/02/28/381744.aspx"&gt;enabling
the loader log&lt;/a&gt; might supply some further information. Alas, all the log would
provide was the following line:
&lt;/p&gt;
&lt;blockquote&gt;&lt;span class="codetext"&gt; 
&lt;p&gt;
Failed to find/load [SomeDll.dll] (even in [\Program Files\Somewhere\])
&lt;/span&gt;&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Not good. I then dug up &lt;a href="http://blogs.msdn.com/netcfteam/archive/2005/07/24/442609.aspx"&gt;another
article&lt;/a&gt; on the subject and proceeded to enable the interop log, which provided
some additional information:
&lt;/p&gt;
&lt;blockquote&gt;&lt;span class="codetext"&gt; 
&lt;p&gt;
JIT ERROR FOR PINVOKE METHOD (Managed -&amp;gt; Native): 
&lt;br&gt;
[pinvokeimpl][preservesig]&lt;br&gt;
int Workarounds::GetSinkWrapper(out IImageSink , IImageEncoder );&lt;br&gt;
int (I4_VAL) GetSinkWrapper(IImageSink&amp;amp; ** (INTF_REF) , IImageEncoder *(INTF_VAL)
);
&lt;/p&gt;
&lt;/span&gt;&lt;/blockquote&gt; 
&lt;p&gt;
I was originally interested in the&amp;nbsp;bizarre&amp;nbsp;native signature&amp;nbsp;generation
(specifically the &lt;span class="codetext"&gt;IImageSink&amp;amp; **&lt;/span&gt; parameter - where'd
the reference come from?), but upon reading some&amp;nbsp;valid log files for working
methods I&amp;nbsp;was convinced that it's a dead duck. I then set my attention to the&amp;nbsp;JIT
message: what has&amp;nbsp;the JIT to do with a native function? I theorized that the
JIT is responsible for the native signature generation for native functions and kept
working under that assumption. That narrowed the question down&amp;nbsp;to, "what went
wrong with the JIT compiler?"
&lt;/p&gt;
&lt;p&gt;
Eventually it occured to me that this might be yet another manifestation of the memory&amp;nbsp;limitation
issue (processes under Windows CE 5.0 are limited to a 32MB address space). The P/Invoke
call is made fairly late into the application; I added a dummy function&amp;nbsp;to the
library which I called on application initialization. This forced the&amp;nbsp;JIT to
take care of the native library before anything was sucking up memory, and the issue
was resolved.
&lt;/p&gt;
&lt;p&gt;
The moral of the story? If you get &lt;span class="codetext"&gt;MissingMethodExceptions&lt;/span&gt; on
your P/Invoke calls, fisrt make sure your DLL is actually deployed; then&amp;nbsp;check
the DllImport signature (you can find a lot of useful resources on &lt;a href="http://msdn2.microsoft.com/en-us/netframework/aa497275.aspx"&gt;this
FAQ&lt;/a&gt;). Finally, make sure you're not out of memory.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=23428e06-234d-4899-8ff3-52016f2e5c0d" /&gt;</description>
      <category>Development</category>
      <category>Development/Compact Framework</category>
    </item>
    <item>
      <trackback:ping>http://www.tomergabel.com/Trackback.aspx?guid=a67e5118-6194-417f-8ea0-a128415ec09f</trackback:ping>
      <pingback:server>http://www.tomergabel.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.tomergabel.com/PermaLink,guid,a67e5118-6194-417f-8ea0-a128415ec09f.aspx</pingback:target>
      <dc:creator>Tomer Gabel</dc:creator>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p style="font-size: xx-small;">
          <u>Footnote</u>: This is fast becoming a series of posts on the woes of using the
.NET Compact Framework. In fact, I've added a subcategory for this exact purpose;
you can access the category and its RSS feed from the Categories list on the right-hand
side of the screen.
</p>
        <p>
Here's another one of those "bang your head repeatedly against the wall and look for
a sharp object" issues: closing a stream derived from <span class="codetext">HttpWebResponse.GetResponseStream</span> takes
an abnormally long time. In fact, the (blocking) call to <span class="codetext">Stream.Close</span> takes
approximately the same amount of time as it would to read to the end of the stream.
I've only encountered <a href="http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_frm/thread/04839a0cb5fb4655/8ed0dad89ee3b282?&amp;hl=en#8ed0dad89ee3b282">one
other reference</a> to this in a newsgroup post from 2004, which (according to Todd,
the original author of the post) was never actually answered.
</p>
        <p>
Seeing as I was trying to use <span class="codetext">HttpWebRequest</span> to create
a minimalistic download manager for one of our applications, I had to come up with
a solution: one option was to close the stream asynchronously and just let the download
run its course, wasting valuable memory, CPU time and bandwidth; another was to never
close the stream and make do with a resource leak. Not content with these solutions
I decided to dig into the framework code with the ever-useful <a href="http://www.aisto.com/roeder/DotNet/">Reflector</a>.
The first hurdle was locating the assemblies; they're not trivial to find, but if
you look hard enough you can find actually useful versions in your Visual Studio 2005
installation folder, under <span class="codetext">SmartDevices\SDK\CompactFramework\2.0\v2.0\Debugger\BCL</span>.
These are regular .NET Assembly PEs so it's trivial to load them up in Reflector.
</p>
        <p>
Some digging into the BCL sources proved that <span class="codetext">HttpWebRequest</span> does,
in fact, read until the end of the stream when closing; this is the relevant code
excerpt, from <span class="codetext">HttpWebRequest.doClose</span>:
</p>
        <blockquote>
          <pre>
            <span style="color: rgb(0, 0, 255);">if</span> (!<span style="color: rgb(0, 0, 255);">this</span>.m_doneReading)<br />
{<br /><span style="color: rgb(0, 0, 255);">byte</span>[] buffer1 = <span style="color: rgb(0, 0, 255);">new</span><span style="color: rgb(0, 0, 255);">byte</span>[0x100];<br /><span style="color: rgb(0, 0, 255);">while</span> (<span style="color: rgb(0, 0, 255);">this</span>.ReadInternal(buffer1,
0, buffer1.Length, <span style="color: rgb(0, 0, 255);">true</span>) != 0)<br />
{<br />
}<br />
}</pre>
        </blockquote>
        <p>
It only started to make sense when I did some reading on HTTP (a protocol I'm not
deeply familiar with). Apparently, HTTP 1.1 connections are <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.6.2">persistent
by default</a>, which means the connection is maintained even after the request is
completed, and further requests are served from the same connection. Technically,
this means that the <span class="codetext">KeepAlive</span> property of <span class="codetext">HttpWebRequest</span> is
true by default, and a <span class="codetext">Connection="Keep-alive"</span> header
is added to the HTTP request. I can only surmise that, with persistent connections,
the response must be read in full in order to allow future requests (if the response
was cut off, some concurrency issues may apply). Unfortunately, setting the <span class="codetext">KeepAlive</span> property
to false did not resolve the issue and the connection was maintained until closed.
</p>
        <p>
Since I could find no way to resolve the problem, I decided to hack around it:
</p>
        <blockquote>
          <pre>stream.GetType().BaseType<br />
.GetField( "<span style="color: rgb(139, 0, 0);">m_doneReading</span>", BindingFlags.Instance
| BindingFlags.NonPublic )<br />
.SetValue( stream, <span style="color: rgb(0, 0, 255);">true</span> );</pre>
        </blockquote>
        <p>
Screwing around with BCL internals is obviously NOT a recommended practise and it's
something I tried very hard to avoid, however this problem had to be resolved in one
way or another. I traced the code a bit deeper to see if this would actually have
the expected results; apparently <span class="codetext">HttpWebRequest</span> keeps
an internal "reference counter" (actually a bitfield, but same principle) on
the connection. According to the implementation for <span class="codetext">HttpWebRequest.connectionRemoveRef</span>,
if the reference counter reaches 0 the private <span class="codetext">m_connection</span> field
of the request becomes null, and the connection is released. I started out by testing
this:
</p>
        <p align="center">
          <a href="http://www.tomergabel.com/content/binary/netcf_stream_connbefore.png" atomicselection="true">
            <img style="border-width: 0px;" src="http://www.tomergabel.com/content/binary/WindowsLiveWriter/OnHttpWebRequestandClosingStreams_D4D8/netcf_stream_connbefore_thumb%5B1%5D.png" border="0" height="103" width="240" />
          </a>
          <a href="http://www.tomergabel.com/content/binary/netcf_stream_connafter.png" atomicselection="true">
            <img style="border-width: 0px;" src="http://www.tomergabel.com/content/binary/WindowsLiveWriter/OnHttpWebRequestandClosingStreams_D4D8/netcf_stream_connafter.png" border="0" height="103" width="240" />
          </a>
          <br />
          <span style="font-size: xx-small;">Before and after - you can see that the m_connection
field becomes null</span>
        </p>
        <p>
Unfortunately I have no idea how to test whether ot not the connection is actually
disposed (conceptually, if <span class="codetext">KeepAlive</span> is set to false
then the connection should be immediately closed); when I find the time I'll try and
track the HTTP session using Wireshark, but currently this horrible hack will just
have to do.
</p>
        <img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=a67e5118-6194-417f-8ea0-a128415ec09f" />
      </body>
      <title>On HttpWebRequest and Closing Streams</title>
      <guid isPermaLink="false">http://www.tomergabel.com/PermaLink,guid,a67e5118-6194-417f-8ea0-a128415ec09f.aspx</guid>
      <link>http://www.tomergabel.com/OnHttpWebRequestAndClosingStreams.aspx</link>
      <pubDate>Tue, 16 Jan 2007 13:33:43 GMT</pubDate>
      <description>&lt;p style="font-size: xx-small;"&gt;
&lt;u&gt;Footnote&lt;/u&gt;: This is fast becoming a series of posts on the woes of using the
.NET Compact Framework. In fact, I've added a subcategory for this exact purpose;
you can access the category and its RSS feed from the Categories list on the right-hand
side of the screen.
&lt;/p&gt;
&lt;p&gt;
Here's another one of those "bang your head repeatedly against the wall and look for
a sharp object" issues: closing a stream derived from &lt;span class="codetext"&gt;HttpWebResponse.GetResponseStream&lt;/span&gt; takes
an abnormally long time. In fact, the (blocking) call to &lt;span class="codetext"&gt;Stream.Close&lt;/span&gt; takes
approximately the same amount of time as it would to read to the end of the stream.
I've only encountered &lt;a href="http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_frm/thread/04839a0cb5fb4655/8ed0dad89ee3b282?&amp;amp;hl=en#8ed0dad89ee3b282"&gt;one
other reference&lt;/a&gt; to this in a newsgroup post from 2004, which (according to Todd,
the original author of the post) was never actually answered.
&lt;/p&gt;
&lt;p&gt;
Seeing as I was trying to use &lt;span class="codetext"&gt;HttpWebRequest&lt;/span&gt; to create
a minimalistic download manager for one of our applications, I had to come up with
a solution: one option was to close the stream asynchronously and just let the download
run its course, wasting valuable memory, CPU time and bandwidth; another was to never
close the stream and make do with a resource leak. Not content with these solutions
I decided to dig into the framework code with the ever-useful &lt;a href="http://www.aisto.com/roeder/DotNet/"&gt;Reflector&lt;/a&gt;.
The first hurdle was locating the assemblies; they're not trivial to find, but if
you look hard enough you can find actually useful versions in your Visual Studio 2005
installation folder, under &lt;span class="codetext"&gt;SmartDevices\SDK\CompactFramework\2.0\v2.0\Debugger\BCL&lt;/span&gt;.
These are regular .NET Assembly PEs so it's trivial to load them up in Reflector.
&lt;/p&gt;
&lt;p&gt;
Some digging into the BCL sources proved that &lt;span class="codetext"&gt;HttpWebRequest&lt;/span&gt; does,
in fact, read until the end of the stream when closing; this is the relevant code
excerpt, from &lt;span class="codetext"&gt;HttpWebRequest.doClose&lt;/span&gt;:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;span style="color: rgb(0, 0, 255);"&gt;if&lt;/span&gt; (!&lt;span style="color: rgb(0, 0, 255);"&gt;this&lt;/span&gt;.m_doneReading)&lt;br&gt;
{&lt;br&gt;
&lt;span style="color: rgb(0, 0, 255);"&gt;byte&lt;/span&gt;[] buffer1 = &lt;span style="color: rgb(0, 0, 255);"&gt;new&lt;/span&gt; &lt;span style="color: rgb(0, 0, 255);"&gt;byte&lt;/span&gt;[0x100];&lt;br&gt;
&lt;span style="color: rgb(0, 0, 255);"&gt;while&lt;/span&gt; (&lt;span style="color: rgb(0, 0, 255);"&gt;this&lt;/span&gt;.ReadInternal(buffer1,
0, buffer1.Length, &lt;span style="color: rgb(0, 0, 255);"&gt;true&lt;/span&gt;) != 0)&lt;br&gt;
{&lt;br&gt;
}&lt;br&gt;
}&lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
It only started to make sense when I did some reading on HTTP (a protocol I'm not
deeply familiar with). Apparently, HTTP 1.1 connections are &lt;a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.6.2"&gt;persistent
by default&lt;/a&gt;, which means the connection is maintained even after the request is
completed, and further requests are served from the same connection. Technically,
this means that the &lt;span class="codetext"&gt;KeepAlive&lt;/span&gt; property of &lt;span class="codetext"&gt;HttpWebRequest&lt;/span&gt; is
true by default, and a &lt;span class="codetext"&gt;Connection="Keep-alive"&lt;/span&gt; header
is added to the HTTP request. I can only surmise that, with persistent connections,
the response must be read in full in order to allow future requests (if the response
was cut off, some concurrency issues may apply). Unfortunately, setting the &lt;span class="codetext"&gt;KeepAlive&lt;/span&gt; property
to false did not resolve the issue and the connection was maintained until closed.
&lt;/p&gt;
&lt;p&gt;
Since I could find no way to resolve the problem, I decided to hack around it:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;stream.GetType().BaseType&lt;br&gt;
.GetField( "&lt;span style="color: rgb(139, 0, 0);"&gt;m_doneReading&lt;/span&gt;", BindingFlags.Instance
| BindingFlags.NonPublic )&lt;br&gt;
.SetValue( stream, &lt;span style="color: rgb(0, 0, 255);"&gt;true&lt;/span&gt; );&lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
Screwing around with BCL internals is obviously NOT a recommended practise and it's
something I tried very hard to avoid, however this problem had to be resolved in one
way or another. I traced the code a bit deeper to see if this would actually have
the expected results; apparently &lt;span class="codetext"&gt;HttpWebRequest&lt;/span&gt; keeps
an internal&amp;nbsp;"reference counter" (actually a bitfield, but&amp;nbsp;same principle)&amp;nbsp;on
the connection. According to the implementation for &lt;span class="codetext"&gt;HttpWebRequest.connectionRemoveRef&lt;/span&gt;,
if the reference counter reaches 0 the private &lt;span class="codetext"&gt;m_connection&lt;/span&gt; field
of the request becomes null, and the connection is released. I started out by testing
this:
&lt;/p&gt;
&lt;p align="center"&gt;
&lt;a href="http://www.tomergabel.com/content/binary/netcf_stream_connbefore.png" atomicselection="true"&gt;&lt;img style="border-width: 0px;" src="http://www.tomergabel.com/content/binary/WindowsLiveWriter/OnHttpWebRequestandClosingStreams_D4D8/netcf_stream_connbefore_thumb%5B1%5D.png" border="0" height="103" width="240"&gt;&lt;/a&gt; &lt;a href="http://www.tomergabel.com/content/binary/netcf_stream_connafter.png" atomicselection="true"&gt;&lt;img style="border-width: 0px;" src="http://www.tomergabel.com/content/binary/WindowsLiveWriter/OnHttpWebRequestandClosingStreams_D4D8/netcf_stream_connafter.png" border="0" height="103" width="240"&gt;&lt;/a&gt; 
&lt;br&gt;
&lt;span style="font-size: xx-small;"&gt;Before and after - you can see that the m_connection
field becomes null&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Unfortunately I have no idea how to test whether ot not the connection is actually
disposed (conceptually, if &lt;span class="codetext"&gt;KeepAlive&lt;/span&gt; is set to false
then the connection should be immediately closed); when I find the time I'll try and
track the HTTP session using Wireshark, but currently this horrible hack will just
have to do.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=a67e5118-6194-417f-8ea0-a128415ec09f" /&gt;</description>
      <category>Development</category>
      <category>Development/Compact Framework</category>
    </item>
    <item>
      <trackback:ping>http://www.tomergabel.com/Trackback.aspx?guid=126c1dc1-3229-431e-aea4-c96eaff53dbb</trackback:ping>
      <pingback:server>http://www.tomergabel.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.tomergabel.com/PermaLink,guid,126c1dc1-3229-431e-aea4-c96eaff53dbb.aspx</pingback:target>
      <dc:creator>Tomer Gabel</dc:creator>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I've been hacking away quite a bit at an application that contains large managed
and unmanaged portions, and a necessarily complex interop layer in between. It appears
that interop marshalling behaves somewhat differently between the full and Compact
framework. Here's a somewhat laconic list of the issues I've encountered and how to
resolve them:
</p>
        <ol>
          <li>
You may encounter <span class="codetext">NotSupportedException</span> on calls to <span class="codetext">Marshall.SizeOf</span>.
Although the documentation does not specify this as a possible exception, experience
shows that this is a result of wrong marshalling attributes: for example, although trying
to marshal a <span class="codetext">bool</span> to <span class="codetext">UnmanagedType.I4</span> makes
sense from a C programmer's perspective, it results in the behavior described above.
The article describing this is called "<a href="http://msdn2.microsoft.com/en-us/library/ms172514.aspx">Using
the MarshalAsAttribute Attribute</a>," but the version in my locally installed copy
of MSDN Library (August 2006) does not contain this information. 
</li>
          <li>
Annoyingly, the default marshalling, or even an explicit <span class="codetext">UnmanagedType.Bool</span>,
results in corrupt values (probably some minor framework bug). I worked around this
by defining the member as <span class="codetext">int</span> and manually giving it
the value 0 or -1. 
</li>
          <li>
It's not obvious, but you can't use <span class="codetext">UnmanagedType.LPArray</span> from
within structures - it only works on P/Invoke method declaration parameters. The only
way to do this is to manually call <span class="codetext">Marshal.StructureToPtr</span> and
do some pointer arithmetic with <span class="codetext">IntPtr</span> (annoying, but
at least it's safe code). 
</li>
          <li>
The marshaller always <a href="http://msdn2.microsoft.com/en-us/library/f1cf4kkz.aspx">frees
up memory</a>; although this makes a lot of sense from the .NET perspective, it probably
means that you'll have to code in some sort of deep copying mechanism in your native
code if you want any of that information in your state. This also has performance
repercussions you should consider when architecting your interop layer.</li>
        </ol>
        <p>
I'll post updates to this as I come across more issues.
</p>
        <img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=126c1dc1-3229-431e-aea4-c96eaff53dbb" />
      </body>
      <title>Unusual Marshalling Behavior in the .NET Compact Framework</title>
      <guid isPermaLink="false">http://www.tomergabel.com/PermaLink,guid,126c1dc1-3229-431e-aea4-c96eaff53dbb.aspx</guid>
      <link>http://www.tomergabel.com/UnusualMarshallingBehaviorInTheNETCompactFramework.aspx</link>
      <pubDate>Tue, 09 Jan 2007 16:34:43 GMT</pubDate>
      <description>&lt;p&gt;
I've been hacking away quite a bit at an application that contains&amp;nbsp;large managed
and unmanaged portions, and a necessarily complex interop layer in between. It appears
that interop marshalling behaves somewhat differently between the full and Compact
framework. Here's a somewhat laconic list of the issues I've encountered and how to
resolve them:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
You may encounter &lt;span class="codetext"&gt;NotSupportedException&lt;/span&gt; on calls to &lt;span class="codetext"&gt;Marshall.SizeOf&lt;/span&gt;.
Although&amp;nbsp;the documentation does not specify this as a possible exception, experience
shows that this is a result of wrong marshalling attributes: for example, although&amp;nbsp;trying
to marshal a &lt;span class="codetext"&gt;bool&lt;/span&gt; to &lt;span class="codetext"&gt;UnmanagedType.I4&lt;/span&gt; makes
sense from a C programmer's perspective, it results in the behavior described above.
The article describing this is called "&lt;a href="http://msdn2.microsoft.com/en-us/library/ms172514.aspx"&gt;Using
the MarshalAsAttribute Attribute&lt;/a&gt;," but the version in my locally installed copy
of MSDN Library (August 2006) does not contain this information. 
&lt;/li&gt;
&lt;li&gt;
Annoyingly, the default marshalling, or even an explicit &lt;span class="codetext"&gt;UnmanagedType.Bool&lt;/span&gt;,
results in corrupt values (probably some minor framework bug). I worked around this
by defining the member as &lt;span class="codetext"&gt;int&lt;/span&gt; and manually giving it
the value 0 or -1. 
&lt;/li&gt;
&lt;li&gt;
It's not obvious, but you can't use &lt;span class="codetext"&gt;UnmanagedType.LPArray&lt;/span&gt; from
within structures - it only works on P/Invoke method declaration parameters. The only
way to do this is to manually call &lt;span class="codetext"&gt;Marshal.StructureToPtr&lt;/span&gt; and
do some pointer arithmetic with &lt;span class="codetext"&gt;IntPtr&lt;/span&gt; (annoying, but
at least it's safe code). 
&lt;/li&gt;
&lt;li&gt;
The marshaller always &lt;a href="http://msdn2.microsoft.com/en-us/library/f1cf4kkz.aspx"&gt;frees
up memory&lt;/a&gt;; although this makes a lot of sense from the .NET perspective, it probably
means that you'll have to code in some sort of deep copying mechanism in your native
code if you want any of that information in your state. This also has performance
repercussions you should consider when architecting your interop layer.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
I'll post updates to this as I come across more issues.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=126c1dc1-3229-431e-aea4-c96eaff53dbb" /&gt;</description>
      <category>Development</category>
      <category>Development/Compact Framework</category>
    </item>
    <item>
      <trackback:ping>http://www.tomergabel.com/Trackback.aspx?guid=a73d1d21-8cea-4b60-960b-01f69eb053f3</trackback:ping>
      <pingback:server>http://www.tomergabel.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.tomergabel.com/PermaLink,guid,a73d1d21-8cea-4b60-960b-01f69eb053f3.aspx</pingback:target>
      <dc:creator>Tomer Gabel</dc:creator>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
For some reason the Visual Studio 2005 debugger (on my native Smart Device project)
flat out refused to halt on Data Abort errors. Instead it would just show the
error information on the debug trace and crash the application: 
</p>
        <blockquote>
          <span class="codetext">Data Abort: Thread=81e27040 Proc=804c68c0 'Client.exe'<br />
AKY=00000041 PC=00eb1cc0(emnative.dll+0x00001cc0) RA=00eb6d6c(emnative.dll+0x00006d6c)
BVA=0e537510 FSR=00000007</span>
        </blockquote>
        <p>
For obvious reasons, I wasn't particularly happy with this. Digging into Google and
the documentation didn't help; after some serious headscratching I figured that the
Windows CE kernel must be catching these exceptions at some point, so from the <span class="codetext">Debug-&gt;Exceptions...</span> menu
I enabled, under Win32 Exceptions, catching of thrown Access Violations:
</p>
        <p align="center">
          <img src="http://www.tomergabel.com/content/binary/catch_dataabort_debug.png" />
        </p>
        <p>
After this, I managed to finally get proper trapping in the debugger, and easily find
out what code actually caused the access violation:
</p>
        <p align="center">
 <img src="http://www.tomergabel.com/content/binary/catch_dataabort_exception.png" /></p>
        <img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=a73d1d21-8cea-4b60-960b-01f69eb053f3" />
      </body>
      <title>Catching Data Abort Exceptions</title>
      <guid isPermaLink="false">http://www.tomergabel.com/PermaLink,guid,a73d1d21-8cea-4b60-960b-01f69eb053f3.aspx</guid>
      <link>http://www.tomergabel.com/CatchingDataAbortExceptions.aspx</link>
      <pubDate>Thu, 04 Jan 2007 15:50:12 GMT</pubDate>
      <description>&lt;p&gt;
For some reason the Visual Studio 2005 debugger (on my native Smart Device project)
flat out refused to halt on Data Abort errors.&amp;nbsp;Instead it would just show the
error information on the debug trace and crash the application:&amp;nbsp;
&lt;/p&gt;
&lt;blockquote&gt;&lt;span class="codetext"&gt;Data Abort: Thread=81e27040 Proc=804c68c0 'Client.exe'&lt;br&gt;
AKY=00000041 PC=00eb1cc0(emnative.dll+0x00001cc0) RA=00eb6d6c(emnative.dll+0x00006d6c)
BVA=0e537510 FSR=00000007&lt;/span&gt;&lt;/blockquote&gt; 
&lt;p&gt;
For obvious reasons, I wasn't particularly happy with this. Digging into Google and
the documentation didn't help; after some serious headscratching I figured that the
Windows CE kernel must be catching these exceptions at some point, so from the &lt;span class="codetext"&gt;Debug-&amp;gt;Exceptions...&lt;/span&gt; menu
I enabled, under Win32 Exceptions, catching of thrown Access Violations:
&lt;/p&gt;
&lt;p align="center"&gt;
&lt;img src="http://www.tomergabel.com/content/binary/catch_dataabort_debug.png"&gt; 
&lt;/p&gt;
&lt;p&gt;
After this, I managed to finally get proper trapping in the debugger, and easily find
out what code actually caused the access violation:
&lt;/p&gt;
&lt;p align="center"&gt;
&amp;nbsp;&lt;img src="http://www.tomergabel.com/content/binary/catch_dataabort_exception.png"&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=a73d1d21-8cea-4b60-960b-01f69eb053f3" /&gt;</description>
      <category>Development</category>
      <category>Development/Compact Framework</category>
    </item>
    <item>
      <trackback:ping>http://www.tomergabel.com/Trackback.aspx?guid=933f35b1-4854-4793-8bb0-7fe2732bb46c</trackback:ping>
      <pingback:server>http://www.tomergabel.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.tomergabel.com/PermaLink,guid,933f35b1-4854-4793-8bb0-7fe2732bb46c.aspx</pingback:target>
      <dc:creator>Tomer Gabel</dc:creator>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
It really yanks my chain when I put my faith into what is presumably a solid foundation
for my code, and end up running into a huge number of unexpected pitfalls.
</p>
        <p>
Be warned: .NET Compact Framework is <strong>incomplete</strong>. Oh yes, it's a fleshed
out version of CF 1.0 with generics and various important bits and pieces finally
included (COM interop. I mean, seriously, .NET is useless without it even on the desktop),
but it's still lacking a lot of vital components (ActiveX hosting) and has
major shortcomings in others (no XSLT support). But that isn't the worst of it:
the documentation is sparse at best, and flat out wrong in some cases.
</p>
        <p>
          <strong>You cannot use asynchronous delegates in .NET CF 2.0.</strong>
        </p>
        <p>
In case it isn't clear to you, let me repeat it: you can't use <span class="codetext">Delegate.BeginInvoke</span>.
If you're really unlucky, like me, you'll write a bunch of code and go on to compile,
run, test and debug it and then run into a <a href="http://www.devx.com/codemag/Article/17441/0/page/6">completely
bogus</a><span class="codetext">NotSupportedException on</span> a seemingly innocuous
internal method call, and have to do some serious digging to figure out the culprit.
This goes particularly well with (admittedly documented) fineprint in methods such
as Windows Media Player's <span class="codetext">player.URL</span> property setter,
which for some reason <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmpsdk11/mmp_sdk/playerurl.asp">mustn't
be called</a> from an event handler.
</p>
        <img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=933f35b1-4854-4793-8bb0-7fe2732bb46c" />
      </body>
      <title>.NET CF: v2.0 my ass</title>
      <guid isPermaLink="false">http://www.tomergabel.com/PermaLink,guid,933f35b1-4854-4793-8bb0-7fe2732bb46c.aspx</guid>
      <link>http://www.tomergabel.com/NETCFV20MyAss.aspx</link>
      <pubDate>Mon, 25 Dec 2006 01:59:25 GMT</pubDate>
      <description>&lt;p&gt;
It really yanks my chain when I put my faith into what is presumably a solid foundation
for my code, and end up running into a huge number of unexpected pitfalls.
&lt;/p&gt;
&lt;p&gt;
Be warned: .NET Compact Framework is &lt;strong&gt;incomplete&lt;/strong&gt;. Oh yes, it's a fleshed
out version of CF 1.0 with generics and various important bits and pieces finally
included (COM interop. I mean, seriously, .NET is useless without it even on the desktop),
but it's still lacking a lot of vital components (ActiveX hosting)&amp;nbsp;and&amp;nbsp;has
major shortcomings&amp;nbsp;in others (no XSLT support). But that isn't the worst of it:
the documentation is sparse at best, and flat out wrong in some cases.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;You cannot use asynchronous delegates in .NET CF 2.0.&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
In case it isn't clear to you, let me repeat it: you can't use &lt;span class="codetext"&gt;Delegate.BeginInvoke&lt;/span&gt;.
If you're really unlucky, like me, you'll write a bunch of code and go on to compile,
run, test and debug it and then run into a &lt;a href="http://www.devx.com/codemag/Article/17441/0/page/6"&gt;completely
bogus&lt;/a&gt; &lt;span class="codetext"&gt;NotSupportedException on&lt;/span&gt; a seemingly innocuous
internal method call, and have to do some serious digging to figure out the culprit.
This goes particularly well with (admittedly documented) fineprint in methods such
as Windows Media Player's &lt;span class="codetext"&gt;player.URL&lt;/span&gt; property setter,
which for some reason&amp;nbsp;&lt;a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmpsdk11/mmp_sdk/playerurl.asp"&gt;mustn't
be called&lt;/a&gt; from an event handler.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=933f35b1-4854-4793-8bb0-7fe2732bb46c" /&gt;</description>
      <category>Development</category>
      <category>Development/Compact Framework</category>
    </item>
    <item>
      <trackback:ping>http://www.tomergabel.com/Trackback.aspx?guid=1592439b-d756-4818-8bd5-77b99cea14a0</trackback:ping>
      <pingback:server>http://www.tomergabel.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.tomergabel.com/PermaLink,guid,1592439b-d756-4818-8bd5-77b99cea14a0.aspx</pingback:target>
      <dc:creator>Tomer Gabel</dc:creator>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <u>Update (January 16th, 2007)</u>: Not only does this apparently only work on the
emulator, you would do well to stay away from Managed DirectX in general because common
drivers, such as those on the <a href="http://www.willcom-inc.com/ja/lineup/ws/004sh/index.html">Willcom
W-Zero3</a> - do not <a href="http://msdn2.microsoft.com/en-us/library/ms229671%28VS.80%29.aspx">support
rendering</a> in landscape mode (I wonder which devices DO support those features).
After messing with this collectively for weeks we eventually went with the obsolete
GAPI. <font color="#ff0000">The code here will probably not work for you</font>.<br /></p>
        <p>
For some reason, elementary DirectX operations are not very well documented in the
.NET Compact Framework documentation; I kept running into InvalidCallExceptions for
no aparent reason, and couldn't figure out the "simple" way to lock surfaces from
the documentation (it's worth noting that I was only interested in basic 2D functionality).
</p>
        <p>
Basically you just need the right set of flags and the right order of operations.
Here's the code I used and that worked for me (even under the considerably buggy emulator).
To create the device, use the following parameters:
</p>
        <blockquote>
          <pre>PresentParameters p = <span style="color: rgb(0, 0, 255);">new</span> PresentParameters();
p.SwapEffect = SwapEffect.Discard; p.Windowed = <span style="color: rgb(0, 0, 255);">true</span>;
p.EnableAutoDepthStencil = <span style="color: rgb(0, 0, 255);">false</span>; p.PresentFlag
|= PresentFlag.LockableBackBuffer; p.MultiSample = MultiSampleType.None; m_device
= <span style="color: rgb(0, 0, 255);">new</span> Device( 0, DeviceType.Default, <span style="color: rgb(0, 0, 255);">this</span>,
CreateFlags.None, p ); </pre>
        </blockquote>
        <p>
To draw on the backbuffer, you can use the following code:
</p>
        <blockquote>
          <pre>m_device.BeginScene();

<span style="color: rgb(0, 0, 255);">using</span> (
Surface s = m_device.GetBackBuffer( 0, BackBufferType.Mono ) ) { <span style="color: rgb(0, 0, 255);">int</span> pitch; <span style="color: rgb(0, 0, 255);">using</span> (
GraphicsStream gs = s.LockRectangle( <span style="color: rgb(0, 0, 255);">this</span>.ClientRectangle,
LockFlags.None, <span style="color: rgb(0, 0, 255);">out</span> pitch ) ) { <span style="color: rgb(0, 128, 0);">//
Your code goes here...</span> } s.UnlockRectangle(); } m_device.EndScene(); m_device.Present();</pre>
        </blockquote>
        <p>
I hope this helps someone avoid a couple hours of frustration.
</p>
        <img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=1592439b-d756-4818-8bd5-77b99cea14a0" />
      </body>
      <title>Getting Surface.LockRectangle to work with .NET Compact Framework 2.0</title>
      <guid isPermaLink="false">http://www.tomergabel.com/PermaLink,guid,1592439b-d756-4818-8bd5-77b99cea14a0.aspx</guid>
      <link>http://www.tomergabel.com/GettingSurfaceLockRectangleToWorkWithNETCompactFramework20.aspx</link>
      <pubDate>Tue, 19 Dec 2006 14:25:24 GMT</pubDate>
      <description>&lt;p&gt;
&lt;u&gt;Update (January 16th, 2007)&lt;/u&gt;: Not only does this apparently only work on the
emulator, you would do well to stay away from Managed DirectX in general because common
drivers, such as those on the &lt;a href="http://www.willcom-inc.com/ja/lineup/ws/004sh/index.html"&gt;Willcom
W-Zero3&lt;/a&gt; - do not &lt;a href="http://msdn2.microsoft.com/en-us/library/ms229671%28VS.80%29.aspx"&gt;support
rendering&lt;/a&gt; in landscape mode (I wonder which devices DO support those features).
After messing with this collectively for weeks we eventually went with the obsolete
GAPI. &lt;font color="#ff0000"&gt;The code here will probably not work for you&lt;/font&gt;.&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;
For some reason, elementary DirectX operations are not very well documented in the
.NET Compact Framework documentation; I kept running into InvalidCallExceptions&amp;nbsp;for
no aparent reason, and couldn't figure out the "simple" way to lock surfaces from
the documentation (it's worth noting that I was only interested in basic 2D functionality).
&lt;/p&gt;
&lt;p&gt;
Basically you just need the right set of flags and the right order of operations.
Here's the code I used and that worked for me (even under the considerably buggy emulator).
To create the device, use the following parameters:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;PresentParameters p = &lt;span style="color: rgb(0, 0, 255);"&gt;new&lt;/span&gt; PresentParameters();
p.SwapEffect = SwapEffect.Discard; p.Windowed = &lt;span style="color: rgb(0, 0, 255);"&gt;true&lt;/span&gt;;
p.EnableAutoDepthStencil = &lt;span style="color: rgb(0, 0, 255);"&gt;false&lt;/span&gt;; p.PresentFlag
|= PresentFlag.LockableBackBuffer; p.MultiSample = MultiSampleType.None; m_device
= &lt;span style="color: rgb(0, 0, 255);"&gt;new&lt;/span&gt; Device( 0, DeviceType.Default, &lt;span style="color: rgb(0, 0, 255);"&gt;this&lt;/span&gt;,
CreateFlags.None, p ); &lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
To draw&amp;nbsp;on the backbuffer, you can use the following code:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;m_device.BeginScene();

&lt;span style="color: rgb(0, 0, 255);"&gt;using&lt;/span&gt; (
Surface s = m_device.GetBackBuffer( 0, BackBufferType.Mono ) ) { &lt;span style="color: rgb(0, 0, 255);"&gt;int&lt;/span&gt; pitch; &lt;span style="color: rgb(0, 0, 255);"&gt;using&lt;/span&gt; (
GraphicsStream gs = s.LockRectangle( &lt;span style="color: rgb(0, 0, 255);"&gt;this&lt;/span&gt;.ClientRectangle,
LockFlags.None, &lt;span style="color: rgb(0, 0, 255);"&gt;out&lt;/span&gt; pitch ) ) { &lt;span style="color: rgb(0, 128, 0);"&gt;//
Your code goes here...&lt;/span&gt; } s.UnlockRectangle(); } m_device.EndScene(); m_device.Present();&lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
I hope this helps someone avoid a couple hours of frustration.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=1592439b-d756-4818-8bd5-77b99cea14a0" /&gt;</description>
      <category>Development</category>
      <category>Development/Compact Framework</category>
    </item>
    <item>
      <trackback:ping>http://www.tomergabel.com/Trackback.aspx?guid=78b9b239-2cf4-410d-b1bb-80669d118ce3</trackback:ping>
      <pingback:server>http://www.tomergabel.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.tomergabel.com/PermaLink,guid,78b9b239-2cf4-410d-b1bb-80669d118ce3.aspx</pingback:target>
      <dc:creator>Tomer Gabel</dc:creator>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Quick link: To download the wrapper classes click <a href="http://www.tomergabel.com/content/binary/IStreamWrapper.zip">here</a></p>
        <p>
While working on a large application targetting the .NET Compact Framework 2.0 I realized
that I'll need to feed some native code (specifically, the XSLT processor in MSXML
3.0 SP1) with an <span class="codetext">IStream</span> implementation.
</p>
        <p>
Articles about interoperating with unmanaged code in the CF are not exactly abundant;
to save you the time I spent on incorrect and/or conflicting research, here's the
bottom line:
</p>
        <ul>
          <li>
            <strong>There is no Managed C/C++ for .NET Compact Framework 2.0</strong>. To some
this may be old news, but you should really pay attention to this point if you're
going to do any serious development against CF. 2.0 adds support for managed
COM/ActiveX interop, but otherwise you're completely stuck with P/Invoke. 
</li>
          <li>
Although it's not immediately obvious, CF 2.0 <strong>does</strong> support exposing managed
classes via COM. 
</li>
          <li>
The CF is missing some usually-minor classes from the BCL; in this case I was missing <span class="codetext">System.Runtime.InteropServices.ComTypes.IStream</span>.
Annoying but easy to work around. 
</li>
          <li>
Finally, as an aside, MSXML 3.0 SP1 for Windows Mobile <strong>does not support </strong>the <span class="codetext">IXslTemplate</span> and <span class="codetext">IXslProcessor</span> interfaces,
meaning that MSXML 3.0's already <a href="http://blogs.msdn.com/antosha/archive/2006/07/24/677560.aspx">lackluster
performance</a> in XSLT transformations is further hindered by not being able
to cache the interpreted stylesheets. This means that, if you use XSLT, your
application <strong>will not scale</strong>. I was not initially aware of this
issue, so I hope our data sets are small enough to handle this, or I may yet
come to regret the decision to use XSLT in this project.</li>
        </ul>
        <p>
I managed to save quite a bit of time by leveraging <a href="http://www.sturmnet.org/blog/archives/2005/03/03/cds-csharp-extractor/">Oliver
Sturm's work</a>, which was originally intended for the desktop. Since the CF is missing
a whole bunch of minor classes, the managed definition of IStream included, I originally
mucked about with <span class="codetext">midl</span> trying to generate these definitions
from the .IDL files. After this proved to be a genuine chore, I just ripped the definitions
straight out of the .NET Framework 2.0 assemblies with the ever-useful <a href="http://www.aisto.com/Roeder/DotNet/">Reflector</a>.
</p>
        <p>
You can download the class file <a href="http://www.tomergabel.com/content/binary/IStreamWrapper.zip">here</a>.
If you use this it would really be cool if you could drop me an e-mail, and I bet <a href="http://www.sturmnet.org/blog/archives/2005/03/03/cds-csharp-extractor/">Oliver</a> would
be equally appreciative. Enjoy!
</p>
        <img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=78b9b239-2cf4-410d-b1bb-80669d118ce3" />
      </body>
      <title>Managed IStream wrapper for .NET Compact Framework 2.0</title>
      <guid isPermaLink="false">http://www.tomergabel.com/PermaLink,guid,78b9b239-2cf4-410d-b1bb-80669d118ce3.aspx</guid>
      <link>http://www.tomergabel.com/ManagedIStreamWrapperForNETCompactFramework20.aspx</link>
      <pubDate>Sun, 10 Dec 2006 13:31:16 GMT</pubDate>
      <description>&lt;p&gt;
Quick link: To download the wrapper classes click &lt;a href="http://www.tomergabel.com/content/binary/IStreamWrapper.zip"&gt;here&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
While working on a large application targetting the .NET Compact Framework 2.0 I realized
that I'll need to feed some native code (specifically, the XSLT processor in MSXML
3.0 SP1) with an &lt;span class="codetext"&gt;IStream&lt;/span&gt; implementation.
&lt;/p&gt;
&lt;p&gt;
Articles about interoperating with unmanaged code in the CF are not exactly abundant;
to save you the time I spent on incorrect and/or conflicting research, here's the
bottom line:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;There is no Managed C/C++ for .NET Compact Framework 2.0&lt;/strong&gt;. To some
this may be old news, but you should really pay attention to this point if you're
going to do any serious&amp;nbsp;development against CF. 2.0 adds support for managed
COM/ActiveX interop, but otherwise you're completely stuck with P/Invoke. 
&lt;/li&gt;
&lt;li&gt;
Although it's not immediately obvious, CF 2.0 &lt;strong&gt;does&lt;/strong&gt; support&amp;nbsp;exposing&amp;nbsp;managed
classes via COM. 
&lt;/li&gt;
&lt;li&gt;
The CF is missing some usually-minor classes from the BCL; in this case I was missing &lt;span class="codetext"&gt;System.Runtime.InteropServices.ComTypes.IStream&lt;/span&gt;.
Annoying but easy to work around. 
&lt;/li&gt;
&lt;li&gt;
Finally, as an aside, MSXML 3.0 SP1 for Windows Mobile &lt;strong&gt;does not support &lt;/strong&gt;the &lt;span class="codetext"&gt;IXslTemplate&lt;/span&gt; and &lt;span class="codetext"&gt;IXslProcessor&lt;/span&gt; interfaces,
meaning that MSXML 3.0's&amp;nbsp;already &lt;a href="http://blogs.msdn.com/antosha/archive/2006/07/24/677560.aspx"&gt;lackluster
performance&lt;/a&gt;&amp;nbsp;in XSLT transformations is further hindered by not being able
to cache the interpreted stylesheets. This means that, if you use XSLT,&amp;nbsp;your
application &lt;strong&gt;will not scale&lt;/strong&gt;. I was not&amp;nbsp;initially aware of this
issue, so&amp;nbsp;I hope our data sets are small enough to handle this, or I may yet
come to regret the decision to use XSLT in this project.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
I managed to save quite a bit of time by leveraging &lt;a href="http://www.sturmnet.org/blog/archives/2005/03/03/cds-csharp-extractor/"&gt;Oliver
Sturm's work&lt;/a&gt;, which was originally intended for the desktop. Since the CF is missing
a whole bunch of minor classes, the managed definition of IStream included, I originally
mucked about with &lt;span class="codetext"&gt;midl&lt;/span&gt; trying to generate these definitions
from the .IDL files. After this proved to be a genuine chore, I just ripped the definitions
straight out of the .NET Framework 2.0 assemblies with the ever-useful &lt;a href="http://www.aisto.com/Roeder/DotNet/"&gt;Reflector&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
You can download the class file &lt;a href="http://www.tomergabel.com/content/binary/IStreamWrapper.zip"&gt;here&lt;/a&gt;.
If you use this it would really be cool if you could drop me an e-mail, and I bet &lt;a href="http://www.sturmnet.org/blog/archives/2005/03/03/cds-csharp-extractor/"&gt;Oliver&lt;/a&gt; would
be equally appreciative. Enjoy!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.tomergabel.com/aggbug.ashx?id=78b9b239-2cf4-410d-b1bb-80669d118ce3" /&gt;</description>
      <category>Development</category>
      <category>Development/Compact Framework</category>
    </item>
  </channel>
</rss>