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

<channel>
	<title>emphess .NET</title>
	<atom:link href="http://www.emphess.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.emphess.net</link>
	<description>Christoph Menge&#039;s Blog</description>
	<lastBuildDate>Thu, 11 Mar 2010 00:20:13 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Random Rant: Don&#8217;t Teach Units in Math Class</title>
		<link>http://www.emphess.net/2010/03/11/random-rant-dont-teach-units-in-math-class/</link>
		<comments>http://www.emphess.net/2010/03/11/random-rant-dont-teach-units-in-math-class/#comments</comments>
		<pubDate>Thu, 11 Mar 2010 00:13:23 +0000</pubDate>
		<dc:creator>Christoph Menge</dc:creator>
				<category><![CDATA[Off-Topic]]></category>
		<category><![CDATA[Germany]]></category>
		<category><![CDATA[Maths]]></category>
		<category><![CDATA[Physics]]></category>
		<category><![CDATA[Politics]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Startup]]></category>
		<category><![CDATA[Teaching]]></category>

		<guid isPermaLink="false">http://www.emphess.net/?p=110</guid>
		<description><![CDATA[A few days ago, I registered at bettermarks, a German startup co-founded by successful entrepreneur Arndt Kwiatkowski. I played around a little pretending I was in 7th class and looked at what they’ve built. This is certainly a very interesting project, and I hope that it will help to improve math lessons in Germany &#8211; [...]]]></description>
			<content:encoded><![CDATA[<p>A few days ago, I registered at <a href="http://de.bettermarks.com/">bettermarks</a>, a German startup co-founded by successful entrepreneur Arndt Kwiatkowski. I played around a little pretending I was in 7th class and looked at what they’ve built. This is certainly a very interesting project, and I hope that it will help to improve math lessons in Germany &#8211; but that is a long way to go.</p>
<p>Anyway, I don&#8217;t want to rant about bettermarks. On the contrary, I think bettermarks is great. But I&#8217;m worried about the content of math classes. The content that is specified by politicians. 7th-grade students in Germany seem to constantly deal with <em>units</em> in math. I guess the correct English term is &#8220;physical units&#8221;. Physical units because units are a concern of physics and, more importantly:</p>
<p><strong>Mathematics is not concerned with units.</strong></p>
<p>That&#8217;s the whole point of mathematics: You make things simple so you can handle them. In mathematics, there is no unit of area and unit of length.<br />
Mathematicians are happy if something can be measured <em>at all</em>, a property that not too many mathematical entities have. </p>
<p>Take fractals for example: Suppose I drew a <a href="http://en.wikipedia.org/wiki/Sierpinski_triangle">Sierpinski<br />
Triangle</a> on a piece of paper, how much space do I need to do that?<br />
Obviously, I will need some space if I wanted to actually draw it (physical reality), otherwise I couldn&#8217;t see it. Mathematically speaking, however, it has Lesbegue measure 0 and thus, vanishing area. Not square kilometers, apples or Newton, just a number. </p>
<p>How about a Hilbert Curve? I can draw an approximation on some finite area. Now I can refine it, thereby increasing its length, but I don&#8217;t need to extend my drawing. Eventually, the length will grow to infinity &#8211; how can this be? In the context of soccer fields and living rooms, this doesn&#8217;t make sense &#8211; it&#8217;s purely theoretical. It&#8217;s mathematics.</p>
<p>I agree, it is important to teach children about the typical size of a living room, a soccer field or the distance between some well-known cities. But that shouldn’t be done in mathematics: Mathematics should be concerned with abstract thinking only. Many people believe abstract thinking makes classes less appealing to children, but honestly: Do they really think that &#8220;Martha owns a set of Miley Cyrus stickers of cardinality 8&#8243; type of exercises make math more interesting, let alone be taken seriously by children?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.emphess.net/2010/03/11/random-rant-dont-teach-units-in-math-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>db4o Performance Pitfalls</title>
		<link>http://www.emphess.net/2010/02/11/db4o-performance-pitfalls/</link>
		<comments>http://www.emphess.net/2010/02/11/db4o-performance-pitfalls/#comments</comments>
		<pubDate>Thu, 11 Feb 2010 01:04:18 +0000</pubDate>
		<dc:creator>Christoph Menge</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[db4o]]></category>
		<category><![CDATA[Native Query]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[OODBMS]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://www.emphess.net/?p=96</guid>
		<description><![CDATA[This is just a quick note, but I just gotta share this now.
It&#8217;s actually in the manual so this is not exactly a secret, but I managed to overlook it so perhaps I&#8217;m not the only one&#8230; 
In our specific scenario, db4o was about 3 times slower than MSSQL via Linq to SQL in the [...]]]></description>
			<content:encoded><![CDATA[<p>This is just a quick note, but I just gotta share this <em>now</em>.</p>
<p>It&#8217;s actually in the manual so this is not exactly a secret, but I managed to overlook it so perhaps I&#8217;m not the only one&#8230; </p>
<p>In our specific scenario, db4o was about 3 times slower than MSSQL via Linq to SQL in the past days.</p>
<p>Just a few minutes ago, I finally read this:</p>
<blockquote><p>Native Query optimizer for .NET requires the following libraries to work:<br />
Db4obects.Db4o.Instrumentation.dll<br />
Db4objects.Db4o.NativeQueries.dll<br />
Mono.Cecil.dll<br />
Cecil.FlowAnalysis.dll</p></blockquote>
<p>(see <a href="http://developer.db4o.com/Documentation/Reference/db4o-7.12/net35/reference/html/reference/tuning/native_query_optimization.html">http://developer.db4o.com/Documentation/Reference/db4o-7.12/net35/reference/html/reference/tuning/native_query_optimization.html</a>)</p>
<p>I added these dll&#8217;s to my solution and wooosh! Now it&#8217;s up to 50 times faster than before! That&#8217;s what I needed&#8230; Will see how this works with larger data sets&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.emphess.net/2010/02/11/db4o-performance-pitfalls/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Areas, Routes and defaults in MVC 2 RC</title>
		<link>http://www.emphess.net/2010/01/31/areas-routes-and-defaults-in-mvc-2-rc/</link>
		<comments>http://www.emphess.net/2010/01/31/areas-routes-and-defaults-in-mvc-2-rc/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 17:36:44 +0000</pubDate>
		<dc:creator>Christoph Menge</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MVC 2]]></category>
		<category><![CDATA[MVC 2 Areas]]></category>

		<guid isPermaLink="false">http://www.emphess.net/?p=89</guid>
		<description><![CDATA[Download sample
There has been some discussion over at stackoverflow on setting a default route to an area in mvc, so I want to post some very crude, but working example code here&#8230; I will write some explanatory text here if I find the time.
I feel that the fact that the order of operation in Application_Start() [...]]]></description>
			<content:encoded><![CDATA[<p><a href='http://www.emphess.net/wp-content/uploads/2010/01/MvcApplication.zip'>Download sample</a></p>
<p>There has been some discussion over at stackoverflow on <a href="http://stackoverflow.com/questions/2140208/how-to-set-a-default-route-to-an-area-in-mvc/2172438#2172438">setting a default route to an area in mvc</a>, so I want to post some <a href='http://www.emphess.net/wp-content/uploads/2010/01/MvcApplication.zip'>very crude, but working example code here</a>&#8230; I will write some explanatory text here if I find the time.</p>
<p>I feel that the fact that the order of operation in <code>Application_Start()</code> matters is quite problematic, but that has been discussed elsewhere (I&#8217;ll be searching for the link&#8230;) Anyway, when registering the areas first, the default route can be set to an area.</p>
<pre class="brush: csharp">
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
        }
</pre>
<p>In the AreaRegistration, </p>
<pre class="brush: csharp">
        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                &quot;ShopArea_default&quot;,
                &quot;{controller}/{action}/{id}&quot;,
                new { action = &quot;Index&quot;, id = &quot;&quot;, controller = &quot;MyRoute&quot; },
                new { controller = &quot;MyRoute&quot; }
            );
        }
</pre>
<p>will do the job. Note the use of the constraint that will only accept requests to the areas&#8217; controller that should be used as a default.</p>
<p>This is a working solution, but I think it is quite error-prone and not very elegant. In the meantime, I started to use <a href="http://www.MvcContrib.org">MvcContrib</a>, because it&#8217;s <a href="http://www.lostechies.com/blogs/hex/archive/2009/11/01/asp-net-mvc-portable-areas-via-mvccontrib.aspx">portable areas are really smart</a>, make deployment easier and foster reusability of the code, <em>and</em> the views.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.emphess.net/2010/01/31/areas-routes-and-defaults-in-mvc-2-rc/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A Simple Standalone Server for db4o as Windows Service</title>
		<link>http://www.emphess.net/2010/01/23/a-simple-standalone-server-for-db4o-as-windows-service/</link>
		<comments>http://www.emphess.net/2010/01/23/a-simple-standalone-server-for-db4o-as-windows-service/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 03:48:38 +0000</pubDate>
		<dc:creator>Christoph Menge</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[db4o]]></category>
		<category><![CDATA[EventLog]]></category>
		<category><![CDATA[Object Database]]></category>
		<category><![CDATA[OODBMS]]></category>
		<category><![CDATA[ServiceBase]]></category>
		<category><![CDATA[ServiceInstaller]]></category>

		<guid isPermaLink="false">http://www.emphess.net/?p=73</guid>
		<description><![CDATA[Download: db4oSimpleServer

Lately, I have fiddled around with Versant&#8217;s excellent dual-license object database db4o a little and I think object databases are very neat. In fact, I read a few pages in PoEAA [Patterns of Enterprise Application Architecture] today, and here and there Fowler writes how cool object databases are. The Fowler knows!
Well, anyhow when you [...]]]></description>
			<content:encoded><![CDATA[<p>Download: <a href='http://www.emphess.net/wp-content/uploads/2010/01/db4oSimpleServer.zip'>db4oSimpleServer</a><br />
<a href="http://www.emphess.net/wp-content/uploads/2010/01/solution.png"><img src="http://www.emphess.net/wp-content/uploads/2010/01/solution.png" alt="" title="Solution Layout" width="222" height="372" class="alignright size-full wp-image-75" /></a></p>
<p>Lately, I have fiddled around with Versant&#8217;s excellent dual-license object database <a href="http://www.db4o.com">db4o</a> a little and I think object databases are very neat. In fact, I read a few pages in PoEAA [Patterns of Enterprise Application Architecture] today, and here and there Fowler writes how cool object databases are. The Fowler knows!</p>
<p>Well, anyhow when you <a href="http://www.db4o.com/DownloadNow.aspx">download db4o</a> (sign up and go for the latest release) there is no standalone server application included. That makes perfect sense, because the server needs access to your domain model / data model dll. In an object database, <em>there are no tables</em>, but there are objects, so you have to compile them into the application that runs the actual db4o server. There is server <em>code</em> which handles practically everything that is tricky, but it&#8217;s in a dll so you&#8217;ll have to write a few lines to build an application out of it. I figured this would be a great time to write my first windows service and so I mashed up some code I found on the net. </p>
<p>I initially thought the VS 2008 designer would set up pretty much everything, but it turned out that things are a little more complicated.</p>
<h2>The Installer</h2>
<p>Since a service will run in a different manner, potentially using a different user account, etc. it needs to be installed first. There is a tool called <code>installutil.exe</code>, but using it is a little awkward. Also, you&#8217;d have to deploy it along your application. <a href="http://stackoverflow.com/questions/593454/easiest-language-to-create-a-windows-service">Matt Davis posted a cool guide on stackoverflow</a> and <a href="http://stackoverflow.com/questions/1195478/how-to-make-a-net-windows-service-start-right-after-the-installation/1195621#1195621">some additional information here</a> on how to write a windows service that is esentially able to install itself! </p>
<h3>Unexpected Features</h3>
<p>One of the most peculiar features is that -should you prefer to have your own event log instead of writing to the ApplicationLog- you have to search through a tree of installers, find the <code>EventLogInstaller</code> and modify it instead of simply adding a new one because the <code>ServiceInstaller</code> will come along with the <code>EventLogInstaller</code> as a child:</p>
<pre class="brush: csharp">
EventLogInstaller installer = FindInstaller(this.Installers);
if (installer != null)
    installer.Log = ServiceConfiguration.LogName;
</pre>
<p>We also need to take care of spawning the actual worker thread, but fortunately there is a <a href="http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase(VS.80).aspx">comprehensive guide on MSDN</a> explaining this.</p>
<h2>Using the Sample</h2>
<p>First things first: Of course, this is not <em>nearly</em> production-safe code! Also, I did not include the db4o dll&#8217;s because I&#8217;m not sure about the licence terms.<br />
<div id="attachment_74" class="wp-caption alignleft" style="width: 695px"><a href="http://www.emphess.net/wp-content/uploads/2010/01/install.png"><img src="http://www.emphess.net/wp-content/uploads/2010/01/install.png" alt="" title="Install" width="685" height="193" class="size-full wp-image-74" /></a><p class="wp-caption-text">The installer in 'action'. Note the Administrator prompt</p></div></p>
<ol>
<li>Download <a href='http://www.emphess.net/wp-content/uploads/2010/01/db4oSimpleServer.zip'>the sample</a>, extract</li>
<li>Download db4o, install</li>
<li>Copy <code>Db4objects.Db4o.dll</code> and <code>Db4objects.Db4o.CS.dll</code> from the db4o install directory to the samples&#8217; lib directory</li>
<li>Compile</li>
<li>Open an <b>Administrator</b> command prompt and find the sample&#8217;s <code>bin</code> folder. There is no feedback in case anything goes wrong (at best, the program crashes)</li>
<li>Call the install routine by executing <code>emphess.db4oServer.exe -install</code>. This will install the db4o server and the associated event log. The server will not be started automatically.</li>
<li>Head over to <code>services.msc</code> or your EventLog, where you <a href="http://blogs.msdn.com/helloworld/archive/2008/12/11/creating-an-event-log.aspx">should find a new entry!</a></li>
<li>Edit the configuration file, ready to run!</li>
<li>Don&#8217;t use this for anything production&#8230;</li>
</ol>
<h3>The App.Config</h3>
<p>The configuration file looks like this</p>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;configuration&gt;
  &lt;appSettings&gt;
    &lt;add key=&quot;UseLocalFile&quot; value=&quot;false&quot; /&gt;
    &lt;!-- &lt;add key=&quot;DatabaseLocalFileName&quot; value=&quot;irrelevant&quot;/&gt; --&gt;
    &lt;add key=&quot;DatabaseHost&quot; value=&quot;localhost&quot; /&gt;
    &lt;add key=&quot;DatabasePort&quot; value=&quot;52354&quot; /&gt;
    &lt;add key=&quot;DatabaseServerFileName&quot; value=&quot;C:/Development/db4oServer/db/server.db4o&quot; /&gt;
    &lt;add key=&quot;DatabaseUser&quot; value=&quot;test&quot; /&gt;
    &lt;add key=&quot;DatabasePassword&quot; value=&quot;test&quot; /&gt;
  &lt;/appSettings&gt;
&lt;/configuration&gt;
</pre>
<p>The <code>UseLocalFile</code> setting is meant for clients so you can easily switch between file-based and network-based configurations. Since <code>db4oServer.Shared</code> contains a small class that holds this configuration data, you can easily reuse the code in a different app, e.g. in the client.</p>
<h3>Todo-List</h3>
<p>There are some things I&#8217;d like to add over the next weeks, so I put the list here to give me some &#8216;pseudo-extrinsic motivation&#8217;&#8230; (yes, I like complicated words)</p>
<ul>
<li>Simple sample client</li>
<li>Out-of-band data for backup, defragmentation commands, etc.</li>
<li>Tests / Benchmarks</li>
</ul>
<p>I hope you have any use for this.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.emphess.net/2010/01/23/a-simple-standalone-server-for-db4o-as-windows-service/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>A Nice Product Crippled</title>
		<link>http://www.emphess.net/2010/01/23/a-nice-product-crippled/</link>
		<comments>http://www.emphess.net/2010/01/23/a-nice-product-crippled/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 01:56:12 +0000</pubDate>
		<dc:creator>Christoph Menge</dc:creator>
				<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://www.emphess.net/?p=69</guid>
		<description><![CDATA[Well&#8230; with a few years delay, I just wanted to sign up to del.icio.us, which is now simply called delicious.com. When Yahoo bought it, they obviously decided they didn&#8217;t want to have any more users, as you can see on the right.
I want to store some bookmarks online. period. Do they really think I&#8217;ll signup [...]]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_70" class="wp-caption alignright" style="width: 330px"><a href="http://www.emphess.net/wp-content/uploads/2010/01/delicious_signup.png"><img src="http://www.emphess.net/wp-content/uploads/2010/01/delicious_signup.png" alt="A screenshot of Yahoo&#039;s signup page" title="NotSoDeliciousSignup" width="320" height="393" class="size-full wp-image-70" /></a><p class="wp-caption-text">Not so delicious</p></div>Well&#8230; with a few years delay, I just wanted to sign up to del.icio.us, which is now simply called delicious.com. When Yahoo bought it, they obviously decided they didn&#8217;t want to have any more users, as you can see on the right.</p>
<p>I want to store some <em>bookmarks</em> online. period. Do they really think I&#8217;ll signup for a yahoo mail account (given that I already have a dozen accounts anyway?) Why does one need two secret questions? Secret questions are stupid in my eyes anyhow, but in times of facebook, knowing one&#8217;s mothers maiden name does not mean anything&#8230; Anyway, can somebody recommend a (good) online bookmarking service? yeah, I know, shouldn&#8217;t be too hard to find, hm? I better get some sleep&#8230; <img src='http://www.emphess.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.emphess.net/2010/01/23/a-nice-product-crippled/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Updating WordPress Plugins</title>
		<link>http://www.emphess.net/2010/01/14/updating-wordpress-plugins/</link>
		<comments>http://www.emphess.net/2010/01/14/updating-wordpress-plugins/#comments</comments>
		<pubDate>Thu, 14 Jan 2010 12:10:55 +0000</pubDate>
		<dc:creator>Christoph Menge</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[Automatic Update]]></category>
		<category><![CDATA[Projects]]></category>

		<guid isPermaLink="false">http://www.emphess.net/?p=60</guid>
		<description><![CDATA[Automatic updates are great, especially for web applications. Apart from saving you some time, I believe they help to enhance security since updating is really easy if you just need to push a button. The &#8216;traditional&#8217; workflow involves backing up, finding and downloading the most recent (compatible) version from an external site, unzipping, uploading via [...]]]></description>
			<content:encoded><![CDATA[<p>Automatic updates are great, especially for web applications. Apart from saving you some time, I believe they help to enhance security since updating is really easy if you just need to push a button. The &#8216;traditional&#8217; workflow involves backing up, finding and downloading the most recent (compatible) version from an external site, unzipping, uploading via FTP, calling some update script, perhaps setting a maintenance mode, etc.</p>
<p>However, when using shared hosting there are some pitfalls. I just trapped into the &#8220;Unable to locate WordPress Content directory (wp-content).&#8221; error. Here&#8217;s what I did:<br />
My web hoster allows many FTP logins, so I created one especially for WordPress and set its ftp root to the WordPress root<br />
It seems that the error message is a little misleading, because it turned out that access to the temp-directory was the actual problem. In <a href="http://wordpress.org/support/topic/238738?replies=17#post-982487">this post</a>, user lightwolf posted a workaround:</p>
<pre class="brush: php">
putenv(&#039;TMPDIR=&#039; . ini_get(&#039;upload_tmp_dir&#039;));
</pre>
<p>Added to wp-config.php.</p>
<p>This fixed my problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.emphess.net/2010/01/14/updating-wordpress-plugins/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A very simple profiler</title>
		<link>http://www.emphess.net/2009/03/04/a-very-simple-profiler/</link>
		<comments>http://www.emphess.net/2009/03/04/a-very-simple-profiler/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 20:27:01 +0000</pubDate>
		<dc:creator>Christoph Menge</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[Handy]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Snippets]]></category>

		<guid isPermaLink="false">http://www.emphess.net/?p=46</guid>
		<description><![CDATA[When I just posted the source code of the Dependency Property Serialization sample, I realized it included a small piece of source code that might come in handy from time to time:
A very basic, but rather exact profiler. It uses QueryPerformanceCounter. Perhaps I shouldn&#8217;t even call this profiler, because a profiler typically keeps track of [...]]]></description>
			<content:encoded><![CDATA[<p>When I just posted the source code of the <a href="http://www.emphess.net/2009/03/04/dependencyproperty-serialization-part-ii/">Dependency Property Serialization sample</a>, I realized it included a small piece of source code that might come in handy from time to time:</p>
<p>A very basic, but rather exact profiler. It uses <code>QueryPerformanceCounter</code>. Perhaps I shouldn&#8217;t even call this profiler, because a profiler typically keeps track of the parts of code it measures. So let&#8217;s call it a precise stopwatch. Well, anyways, here&#8217;s the code:</p>
<p><span id="more-46"></span></p>
<pre lang="csharp">
using System.Runtime.InteropServices;

namespace SimpleProfiler
{
    public class Profiler
    {
        long mFrequency;

        long mAccumulatedTime;
        long mStartTime;
        long mEndTime;

        long mLastTime;

        bool mInitialized = false;
        bool mRunning = false;

        public Profiler()
        {
            mInitialized = QueryPerformanceFrequency(out mFrequency);
        }

        public bool StartMeasure()
        {
            if (mInitialized &#038;&#038; !mRunning)
            {
                mRunning = true;
                return QueryPerformanceCounter(out mStartTime);
            }

            return false;
        }

        public bool StopMeasure()
        {
            if (mInitialized &#038;&#038; mRunning)
            {
                mRunning = false;
                bool bSuccess = QueryPerformanceCounter(out mEndTime);

                if (bSuccess)
                {
                    mLastTime = mEndTime - mStartTime;
                    mAccumulatedTime += mLastTime;
                    return true;
                }
            }

            return false;
        }

        public double GetLastTime()
        {
            return (double)((double)mLastTime / (double)mFrequency);
        }

        public double GetAccumulatedTime()
        {
            return (double)((double)mAccumulatedTime / (double)mFrequency);
        }

        [DllImport("kernel32.dll")]
        private static extern bool QueryPerformanceCounter(out long count);

        [DllImport("kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(out long frequency);
    }
}
</pre>
<p>which is also contained in the <a href="http://www.emphess.net/wp-content/uploads/2009/03/bpboserialization.zip">source code for the previous article</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.emphess.net/2009/03/04/a-very-simple-profiler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DependencyProperty Serialization Part II</title>
		<link>http://www.emphess.net/2009/03/04/dependencyproperty-serialization-part-ii/</link>
		<comments>http://www.emphess.net/2009/03/04/dependencyproperty-serialization-part-ii/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 19:06:09 +0000</pubDate>
		<dc:creator>Christoph Menge</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Dependency Property]]></category>
		<category><![CDATA[ISerializationSurrogate]]></category>
		<category><![CDATA[Serialization]]></category>

		<guid isPermaLink="false">http://www.emphess.net/?p=43</guid>
		<description><![CDATA[First off, my apologies for not posting the second part earlier. I have had a lot to do in the past Months&#8230;
Part II of the article will show how a SerializationSurrogate works and explore wheter we can use it for generic de-serialization of DependencyProperties. Also, in this article I provide full source code for both [...]]]></description>
			<content:encoded><![CDATA[<p>First off, my apologies for not posting the second part earlier. I have had a lot to do in the past Months&#8230;</p>
<p>Part II of the article will show how a <code>SerializationSurrogate</code> works and explore wheter we can use it for generic de-serialization of <code>DependencyProperties</code>. Also, in this article I provide full source code for both parts of the article.</p>
<p>UPDATE: A much better version of this article can now be found at the CodeProject: <a href="http://www.codeproject.com/KB/cs/BPBOSerialization.aspx">DependencyProperty Serialization for Business Objects </a></p>
<p>Alternatively, directly get the source code here: <a href="http://www.emphess.net/wp-content/uploads/2009/03/bpboserialization1.zip">http://www.emphess.net/wp-content/uploads/2009/03/bpboserialization1.zip</a></p>
<p><span id="more-43"></span></p>
<p>Well, let&#8217;s get started:</p>
<h2>ISerializationSurrogate</h2>
<p>This interface is designed as a stand-in for your class upon serialization and de-serialization.</p>
<p>It is quite simple and contains only two methods:<br />
<code><br />
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)<br />
</code><br />
and<br />
<code><br />
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)<br />
</code></p>
<p>This is quite interesting, since there is an explanation on MSDN why they chose <em>not</em> to provide a <code>SetObjectData()</code> method for the <code>ISerializable</code> interface, so this makes quite a difference.</p>
<h2>Surrogate Serialization</h2>
<p>For serialization, we use almost the same code we used in part I, with a few modifications only:</p>
<pre class="brush: csharp">
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
    PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties(obj.GetType(),
            new Attribute[] { new PropertyFilterAttribute(PropertyFilterOptions.SetValues |
                                                          PropertyFilterOptions.UnsetValues |
                                                          PropertyFilterOptions.Valid ) });

    List&lt;FieldInfo&gt; fieldInformation = ReflectionHelper.GetFieldInformation(obj.GetType());

    foreach (FieldInfo fiRover in fieldInformation)
    {
        object[] attribs = fiRover.GetCustomAttributes(typeof(NonSerializedAttribute), false);

        if (attribs.Length &gt; 0)
            continue; // Don&#039;t serialize this

        info.AddValue(fiRover.Name, fiRover.GetValue(obj));
    }

    foreach (PropertyDescriptor propertyDescriptor in descriptors)
    {
        SerializeProperty(obj, info, propertyDescriptor);
    }
}
</pre>
<p>(Please note that I clean the code up a little, in the source download there is a lot of debugging output, etc.)</p>
<h2>Surrogate De-Serialization</h2>
<p>Now, it seems as if an implementation of <code>ISerializationSurrogate</code> might do the job and help us to circumvent the necessity to provide boring constructors through the <code>SetObjectData()</code> method. So let&#8217;s give it a try by basically using the deserialization code from part I:</p>
<pre class="brush: csharp">
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
    Type thisType = obj.GetType();
    DependencyObject depObj = obj as DependencyObject;

    // De-Serialize Fields
    List&lt;FieldInfo&gt; fieldInformation = ReflectionHelper.GetFieldInformation(thisType);

    foreach (FieldInfo fiRover in fieldInformation)
    {
        object[] attribs = fiRover.GetCustomAttributes(typeof(NonSerializedAttribute), false);

        if (attribs.Length &gt; 0)
            continue; // Don&#039;t deserialize this

        fiRover.SetValue(obj, info.GetValue(fiRover.Name, fiRover.FieldType));
    }

    // De-Serialize DependencyProperties
    PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties(thisType,
            new Attribute[] { new PropertyFilterAttribute(PropertyFilterOptions.SetValues |
                                                          PropertyFilterOptions.UnsetValues |
                                                          PropertyFilterOptions.Valid ) });

    // Try to use a mapping to set all DP values deferred. This will actually just
    // postpone the Exception
    List&lt;DependencyValueMap&gt; mappingList = new List&lt;DependencyValueMap&gt;();

    foreach (PropertyDescriptor propertyDescriptor in descriptors)
    {
        if (propertyDescriptor.Attributes[typeof(NonSerializedAttribute)] == null)
        {
            DependencyProperty dp = DependencyPropertyHelper.FindDependencyProperty(obj, propertyDescriptor.Name);

            if (null != dp)
            {
                mappingList.Add(new DependencyValueMap(dp, obj as DependencyObject, info.GetValue(propertyDescriptor.Name, propertyDescriptor.PropertyType)));
            }
            else
            {
                throw new SerializationException(String.Format(@&quot;Failed to deserialize property &#039;{0}&#039; on object of type &#039;{1}&#039;.
Property could not be found. Version Conflict?&quot;, propertyDescriptor.Name, thisType));
            }
        }
    }

    foreach (DependencyValueMap dvRover in mappingList)
    {
        // This call will cause an InvalidOperationException:
        depObj.SetValue(dvRover.dp, dvRover.value);
    }

    return null;
}
</pre>
<p>Now, unfortunately, we cannot set the values of these DependencyProperties. The <code>SetValue() </code> method in <code>DependencyObject</code> will throw the oh-so-magic <code>InvalidOperationException</code>. I haven&#8217;t been able to find a way to go around this.</p>
<h2>Summing it up</h2>
<p>Well, that&#8217;s it basically. Where are we now?</p>
<ul>
<li>It is possible to use DependencyProperties for business objects and serialize and deserialize them.</li>
<li>A reflection-based base class &#8220;SerializableDependencyProperty&#8221; does the job, as long as you stick to the naming convention and implement the deserialization constructor in all derived classes</li>
<li>Circumventing the explicit deserialization constructor seems impossible due to limitations of the DependencyObject base class</li>
</ul>
<h2>The Source</h2>
<p>The sample solutions contains two projects:<br />
WPFDependencyPropertySerialization shows how the serialization of part I can be accomplished.<br />
WPFDependencyPropertySerializationError shows the extension using an ISerializationSurrogate and, as mentioned before, will lead to an Exception &#8230; which will not be caught so you can really feel it rumbling:<br />
&#8220;Current local value enumeration is outdated because one or more local values have been set since its creation.&#8221;</p>
<p>You can download the source at <a href="http://www.emphess.net/wp-content/uploads/2009/03/bpboserialization1.zip">http://www.emphess.net/wp-content/uploads/2009/03/bpboserialization1.zip</a></p>
<p>Have Fun!</p>
<h2>A post scriptum on DependencyProperties for business entities</h2>
<p>The project I&#8217;m currently working on comes with a very complex data structure. It consists of a set of trees which can be connected in various different ways. We also have to account for circular dependencies between these objects. The user can create and modify all these different types of connections.<br />
Moreover, the architecture of the application is highly sophisticated and is based on Microsoft&#8217;s composite application guidance. A lot of modules interact with each other, each having their own data, similar to a ViewModel yet managed by a Presenter. What sounds a little messy has been proven to be the best solution in a number of discussions.<br />
These business entities are based on DependencyProperties and a lot of crucial features depend on the functionality provided by the DependencyProperties. It works well, though I should mention that I did not use a number of DependencyProperty features in the first place. For example, coercion and validation coupled with automated de-serialization might lead into trouble, so keep this in mind should you ever intend to go down the path&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.emphess.net/2009/03/04/dependencyproperty-serialization-part-ii/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>DependencyProperty Serialization</title>
		<link>http://www.emphess.net/2008/11/25/dependencyproperty-serialization/</link>
		<comments>http://www.emphess.net/2008/11/25/dependencyproperty-serialization/#comments</comments>
		<pubDate>Tue, 25 Nov 2008 00:24:56 +0000</pubDate>
		<dc:creator>Christoph Menge</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[DependencyProperties]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[Serialization]]></category>

		<guid isPermaLink="false">http://www.emphess.net/?p=41</guid>
		<description><![CDATA[Ok, I did it: I tried to do it the easy way &#8212; serialization! And I quickly ran into the following issue: Serializing DependencyObjects. There are a lot of sources saying &#8220;you can&#8217;t serialize dependency objects&#8221;, which is true, but you can get pretty close rather quickly and it might not be the worst decision. [...]]]></description>
			<content:encoded><![CDATA[<p>Ok, I did it: I tried to do it the easy way &#8212; serialization! And I quickly ran into the following issue: Serializing <code>DependencyObjects</code>. There are a lot of sources saying &#8220;you can&#8217;t serialize dependency objects&#8221;, which is true, but you can get pretty close rather quickly and it might not be the worst decision. </p>
<p>In this article, we&#8217;ll explore if and how reflection magic can assist us in doing it anyway, how we can locate <code>DependencyProperties</code> via reflection and what pitfalls remain. Moreover, I&#8217;ll give an outlook why the most desireable solution (that almost suggests itself) fails.</p>
<p><span id="more-41"></span></p>
<p>Using DPs in your business logic layer is a disputable decision. The application I work on has very unsual demands and I am still happy with the decision I made. I don&#8217;t want to discuss that here, though, since it is out of scope. </p>
<h2>The Issue</h2>
<p>When serializing objects, you can prevent certain properties from being serialized using the <code>[NonSerialized]</code> property, but if the base class is not marked as <code>[Serializable]</code>, such as the <code>DependencyObject</code> class, attempting to serialize will throw an exception.</p>
<p>However, implementing <code>ISerializable</code> manually does the job:</p>
<pre class="brush: csharp">
[Serializable]
public class SerializableDependencyObject : DependencyObject, ISerializable
{
    // Note that this does not call base(info, context) since the base class does not have
    // a deserialization constructor
    public DagNode(SerializationInfo info, StreamingContext context)
    { }

    // again, the base class is not an ISerializable
    public virtual void GetObjectData(SerializationInfo info,
                                                 StreamingContext context)
    {}
// ...
}
</pre>
<p>What bugs me, however, is that now, all derived classes need to implement <code>GetObjectData </code>and the deserialization constructor explicitly, producing both stupid and error-prone code:</p>
<pre class="brush: csharp">
public class StupidClass : SerializableDependencyObject
{
  #region ISerializable Members
  public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
  {
    info.AddValue(&quot;PropertyA&quot;, mPropertyA);
    info.AddValue(&quot;PropertyB&quot;, mPropertyB);
    info.AddValue(&quot;PropertyC&quot;, mPropertyC);
  }

  public StupidClass (SerializationInfo info, StreamingContext context)
  {
    mPropertyA = info.GetDouble(&quot;PropertyA&quot;);
    mPropertyB = info.GetDouble(&quot;PropertyB&quot;);
    mPropertyC = info.GetDouble(&quot;PropertyC&quot;);
  }
  #endregion
}
</pre>
<p>We obviously don&#8217;t want this, since it produces a lot of manually written, error-prone code that needs to be adjusted constantly when code changes are made &#8211; a lot of work when you consider we&#8217;re not necessarily adding functionality yet.</p>
<h2>One Step Back: .NET Serialization</h2>
<p>It took me some time to realize that .NET has quite a number of techniques aimed at serialization. The process is described quite well at <a href="http://msdn.microsoft.com/en-us/library/tyf8zbfk.aspx">http://msdn.microsoft.com/en-us/library/tyf8zbfk.aspx</a>, but it is still simplified since there are serialization attributes introduced in .NET 2.0 that allow you to hook up additional methods during the serialization/deserialization process:<br />
&#8220;If the class being deserialized implements the <code>IDeserilizationCallback</code>, the <code>OnDeserialization </code>method is automatically called when the entire object graph has been deserialized.&#8221; (see <a href="http://msdn.microsoft.com/en-us/library/ty01x675(VS.71).aspx">http://msdn.microsoft.com/en-us/library/ty01&#215;675(VS.71).aspx</a>)</p>
<p>These concepts are somewhat different and allow you to control the process of serialization and deserialization to a certain degree.<br />
You might be tempted to ask: &#8220;Why should I worry about .NET serialization if it is this complicated &#8211; isn&#8217;t it easier to do it myself?&#8221;, but the answer is probably &#8220;no&#8221;, since the <code>BinaryFormatter</code> really solves all the itty-gritty problems for you in a convenient manner. These are:</p>
<ul>
<li>Solving dependency chains and circular links</li>
<li>Creating unique identifier and associating them w/ object instances</li>
<li>Serializing generic containers</li>
<li>Constructing objects on de-serialization and re-assigning pointers</li>
</ul>
<p>All this does not help in serializing <code>DependencyProperties</code>, however, since your owning class is derived from <code>DependencyObject</code>, that is not marked as <code>[Serializable]</code> &#8211; unless you want to do it manually in each derived class.</p>
<h2>An intelligent base class</h2>
<p>How about a very intelligent base class that uses reflection to mimick the behaviour we&#8217;d expect?</p>
<p>We&#8217;d certainly need a class that is responsible for this behaviour, we might want to call it <code>SerializableDependencyObject</code> again:</p>
<pre class="brush: csharp">
[Serializable]
public class SerializableDependencyObject : DependencyObject, ISerializable
{
}
</pre>
<p>Now, the class needs to implement <code>ISerializable</code> in a sufficient manner, that is, in such way that derived classes behave just like normal serializable classes:</p>
<ul>
<li>The value of <code>DependencyProperties</code> is being stored and restored automatically</li>
<li><code>DependencyProperties</code> marked as <code>[NonSerialized]</code> are not being serialized</li>
</ul>
<h2>The GetObjectData method</h2>
<p>Let&#8217;s try to fetch all fields and properties from the current object instance (<code>this</code>) in the base class. We want to add all these fields to the <code>SerializationInfo</code> instance:</p>
<pre class="brush: csharp">
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
  PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties(GetType(),
        new Attribute[] {
            new PropertyFilterAttribute(PropertyFilterOptions.SetValues |
                                        PropertyFilterOptions.UnsetValues |
                                        PropertyFilterOptions.Valid ) });

  List&lt;FieldInfo&gt; fieldInformation =
    ReflectionHelper.GetFieldInformation(GetType());

  foreach (FieldInfo fiRover in fieldInformation)
  {
    object[] attribs =
      fiRover.GetCustomAttributes(typeof(NonSerializedAttribute), false);

    if (attribs.Length &gt; 0)
      continue; // Don&#039;t serialize this

    info.AddValue(fiRover.Name, fiRover.GetValue(this));
  }

  foreach (PropertyDescriptor propertyDescriptor in descriptors)
  {
    if (propertyDescriptor.Name == &quot;Dispatcher&quot; ||
        propertyDescriptor.Name == &quot;DependencyObjectType&quot; ||
        propertyDescriptor.Name == &quot;IsSealed&quot; )
          continue;

      SerializeProperty(info, propertyDescriptor);
  }
}
</pre>
<p>The first loop of the method will serialize all fields, resembling the functionality we have when not implementing <code>ISerializable</code> manually. The second part, adding functionality, cares for <code>DependencyProperties</code>. The <code>ReflectionHelper</code> is just a simple wrapper around the <code>System.Type.GetFields()</code> method with some performance improvements and minor tweaks.</p>
<p>Let&#8217;s have a look at the serialization constructor of <code>SerializableDependencyObject</code>:</p>
<pre class="brush: csharp">
public SerializableDependencyObject(SerializationInfo info,
                                     StreamingContext context)
{
    Type thisType = GetType();

    // De-Serialize Fields
    List&lt;FieldInfo&gt; fieldInformation =
        ReflectionHelper.GetFieldInformation(thisType);

    foreach (FieldInfo fiRover in fieldInformation)
    {
        object[] attribs =
          fiRover.GetCustomAttributes(typeof(NonSerializedAttribute), false);

        if (attribs.Length &gt; 0)
            continue; // Don&#039;t try to deserialize this

        fiRover.SetValue(this, info.GetValue(fiRover.Name, fiRover.FieldType));
    }

    // De-Serialize DependencyProperties
    PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties(thisType,
        new Attribute[] {
           new PropertyFilterAttribute(PropertyFilterOptions.SetValues |
                                       PropertyFilterOptions.UnsetValues |
                                       PropertyFilterOptions.Valid) });

    foreach (PropertyDescriptor propertyDescriptor in descriptors)
    {
        if (propertyDescriptor.Name == &quot;Dispatcher&quot; ||
            propertyDescriptor.Name == &quot;DependencyObjectType&quot; ||
            propertyDescriptor.Name == &quot;IsSealed&quot;)
            continue;

        DependencyProperty dp =
          DependencyPropertyHelper.FindDependencyProperty(this, propertyDescriptor.Name);

        if (null != dp)
            SetValue(dp, info.GetValue(propertyDescriptor.Name, propertyDescriptor.PropertyType));
        else
            throw new SerializationException(String.Format(@&quot;Failed to deserialize
            property &#039;{0}&#039; on object of type &#039;{1}&#039;. Property could not be found.
            Version Conflict?&quot;,
            propertyDescriptor.Name, thisType));
    }
}
</pre>
<p>Again, the first loop handles simple fields while the second part adds functionality for <code>DependencyProperties</code>. One line in the second part deserves some attention: </p>
<pre lang="csharp">
DependencyProperty dp =
  DependencyPropertyHelper.FindDependencyProperty(this, propertyDescriptor.Name);
</pre>
<p>Remember <code>DependencyProperties</code> are static members which are registered in some application-wide registry, for example:</p>
<pre class="brush: csharp">
public static DependencyProperty NameProperty =
DependencyProperty.Register(&quot;Name&quot;,
                            typeof(string),
                            typeof(GraphNode),
                            new PropertyMetadata(String.Empty));
</pre>
<p>Unfortunately, there is no <code>DependencyProperty.Find()</code> method. That is where the <code>DependencyPropertyHelper</code> comes into play:</p>
<pre class="brush: csharp">
class DependencyPropertyHelper
{
    /// &lt;summary&gt;
    /// Finds a dependency property on an object by its name.
    ///
    /// Motivation: There is no accesible DP registry. When creating DPs, one must register them using
    /// DependencyProperty.Register(), but there is no DependencyProperty.FindProperty()
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;_object&quot;&gt;The object that supposedly has a property of the supplied name&lt;/param&gt;
    /// &lt;param name=&quot;_propertyName&quot;&gt;The name of the property to find, e.g. &quot;Height&quot;. NOTE: The corresponding property is expected to be named &quot;HeightProperty&quot; in this case.&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public static DependencyProperty FindDependencyProperty(object _object, string _propertyName)
    {
        if (null != _object &amp;&amp; !String.IsNullOrEmpty(_propertyName))
        {
            Type typeAttachedTo = _object.GetType();
            FieldInfo fi = null;

            while (null == fi &amp;&amp; typeAttachedTo != null)
            {
                fi = typeAttachedTo.GetField(_propertyName + &quot;Property&quot;);
                typeAttachedTo = typeAttachedTo.BaseType;
            }

            if (null != fi)
            {
                return fi.GetValue(null) as DependencyProperty;
            }
        }
        return null;
    }
}
</pre>
<h2>First results</h2>
<p>At this point, we can supply a base class <code>SerializableDependencyObject</code> that allows simple serialization of <code>DependencyObjects</code> with their associated <code>DependencyProperties</code>. However, quite a number of dangerous pitfalls remain:</p>
<ul>
<li>Setting <code>DependencyValues</code> can be problematic: We might trigger callbacks (<code>PropertyChangedCallbacks</code>, <code>CoerceValueCallback</code>)</li>
<li>Triggered callbacks might rely on yet unitialized data</li>
<li>We rely on the &#8220;Property&#8221; naming convention (e.g. the DP of property <code>"Name"</code> is called <code>"NameProperty"</code>)</li>
<li>You need to define a deserialization constructor for each and every derived class which needs to call the base class&#8217; deserialization constructor. Failing to do so throws a run-time exception.</li>
<li>The current code does not handle versioning</li>
</ul>
<h2>Outlook</h2>
<p>Serializing dependency properties is indeed cumbersome. However, <code>INotifyPropertyChanged</code> might not be an alternative, and reinventing the wheel might not be desirable either. While basic functionality of <code>DependencyProperties</code> is probably quickly implemented, there are some obvious drawbacks, first and foremost the integration with other components that simply require a <code>DependencyObject</code> to work with.</p>
<p>Synchronizing a complex DataModel with sets of equally complex ViewModels can be a pain, too, so for those having such unusual demands, it&#8217;s their time to choose their poison.</p>
<p>In the second part, we&#8217;ll have a look at the <code>ISerializationSurrogate</code> interface and why we can&#8217;t implement it the same way we implemented the <code>SerializableDependencyObject</code>. We will also make the acquaintance of an infamous <code>InvalidOperationException</code>: &#8220;Current local value enumeration is outdated because one or more local values have been set since its creation.&#8221; which esentially keeps us (and probably microsoft) from implementing it just the way we did in here.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.emphess.net/2008/11/25/dependencyproperty-serialization/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Composite WPF, Aggressive GC and dead events</title>
		<link>http://www.emphess.net/2008/11/21/composite-wpf-aggressive-gc-and-dead-events/</link>
		<comments>http://www.emphess.net/2008/11/21/composite-wpf-aggressive-gc-and-dead-events/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 11:11:43 +0000</pubDate>
		<dc:creator>Christoph Menge</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[CAL]]></category>
		<category><![CDATA[Composite WPF]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[GC]]></category>

		<guid isPermaLink="false">http://www.emphess.net/?p=42</guid>
		<description><![CDATA[Well, this is the first post after a very long pause, I am sorry but I had very little time&#8230; 
Anyway, I stumbled over some strange bug this morning that turned out to be related to the GC. But let&#8217;s just step back a minute:
The application I currently work on is based on CompositeWPF . [...]]]></description>
			<content:encoded><![CDATA[<p>Well, this is the first post after a very long pause, I am sorry but I had very little time&#8230; </p>
<p>Anyway, I stumbled over some strange bug this morning that turned out to be related to the GC. But let&#8217;s just step back a minute:</p>
<p>The application I currently work on is based on <a href="http://www.codeplex.com/CompositeWPF">CompositeWPF </a>. I added a very simple module to the application, a simple passive debugging module. I called it &#8220;InspectorModule&#8221;. The <code>InspectorPresenter </code>now listens for global modifications to the business object which is kept by the <code>BusinessEntityManager</code>:</p>
<pre class="brush: csharp">
public InspectorPresenter(IInspectorView _view,
            IEventAggregator _eventAggregator,
            IBusinessEntityManager _businessEntityManager)
{
    mView = _view;
    mEventAggregator = _eventAggregator;
    mBusinessEntityManager = _businessEntityManager;

    mEventAggregator.GetEvent&lt;BusinessInstanceInvalidatedEvent&gt;().Subscribe(ReloadInspector);
}
</pre>
<p>Now, upon each modification of the business object, <code>ReloadInspector </code>shall be called. So, starting the application and triggering the event &#8212; nothing happened. The <code>ReloadInspector </code>method is not being called. Why?</p>
<p>After some debugging, it suddenly worked &#8211; the only problem being: I didn&#8217;t actually <em>change </em>anything! </p>
<p>To make a long story, I realized the <code>CompositeWPF DelegateReference</code>class keeps a <code>WeakReference</code> to the object (the <code>InspectorPresenter</code>, in this case) when registering it via the <code>EventAggregator </code>as above.</p>
<p>Unfortunately, due to the simplicity of the <code>InspectorPresenter</code>, no instantiated object actually keeps a reference to the Presenter (apart from the <code>WeakReference </code>of the event which, by definition, does not prevent it from being finalized).</p>
<p>That&#8217;s why the object is being finalized and the event never fires. Actually, on the first call of the associated <code>Publish()</code> method, the Composite WPF-Internal <code>EventBase.PruneAndReturnStrategies()</code> will remove it from the list after it&#8217;s associated <code>Action </code>is supposedly null.</p>
<p>Debugging this was quite cumbersome, and the solution of striking simplicity: I simply continued to develop the &#8220;Inspector&#8221;, a little more than I originally planned, so the user can now select an object in the inspector. Now, I have a simple event like this:</p>
<pre class="brush: csharp">
public InspectorPresenter(IInspectorView _view,
            IEventAggregator _eventAggregator,
            IBusinessEntityManager _businessEntityManager)
{
    // ...
    mView.SelectedNodeChanged += new OnSelectedNodeChanged(mView_SelectedNodeChanged);
    // ...
}
</pre>
<p>This keeps a (strong) reference to the Presenter, and the GC does not kill my presenter anymore! The reason it worked when debugging, I guess, is that the debugger will keep the GC from finalizing objects under certain circumstances.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.emphess.net/2008/11/21/composite-wpf-aggressive-gc-and-dead-events/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
