<?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>hackinghat.com &#187; .NET</title>
	<atom:link href="http://www.hackinghat.com/index.php/category/windows/net/feed" rel="self" type="application/rss+xml" />
	<link>http://www.hackinghat.com</link>
	<description></description>
	<lastBuildDate>Wed, 19 May 2010 07:48:25 +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>MonoDevelop 2.0 makes me ashamed</title>
		<link>http://www.hackinghat.com/index.php/windows/net/monodevelop-20-makes-me-ashamed</link>
		<comments>http://www.hackinghat.com/index.php/windows/net/monodevelop-20-makes-me-ashamed#comments</comments>
		<pubDate>Mon, 18 May 2009 09:30:18 +0000</pubDate>
		<dc:creator>Steve Knight</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[unix]]></category>

		<guid isPermaLink="false">http://www.hackinghat.com/index.php/windows/net/monodevelop-20-makes-me-ashamed</guid>
		<description><![CDATA[I am ashamed to say that I wasn&#8217;t really sure if the Mono project would ever succeed.   It seemed like such an enormous task, and one that would forever be playing catch-up with M$, that it just didn&#8217;t make sense.

Even so, I&#8217;ve sort of been following it from the sidelines for a while [...]]]></description>
			<content:encoded><![CDATA[<p>I am ashamed to say that I wasn&#8217;t really sure if the Mono project would ever succeed.   It seemed like such an enormous task, and one that would forever be playing catch-up with M$, that it just didn&#8217;t make sense.</p>
<p><a style="float:right" href="http://www.hackinghat.com/wp-content/uploads/2009/05/screenshot-coretest-monodevelop-1.png"><img id="image138" src="http://www.hackinghat.com/wp-content/uploads/2009/05/screenshot-coretest-monodevelop-1.thumbnail.png" alt="MonoDevelop 2.0" /></a></p>
<p>Even so, I&#8217;ve sort of been following it from the sidelines for a while and I&#8217;m excited to say that Mono 2.4 seems to be a drop-in replacement for the bits of the .NET SDK I was actually using.   Now with the release of MonoDevelop 2.0 it seems that I&#8217;m also able to get a functioning alternative to the Visual Studio GUI I&#8217;ve been using.   It&#8217;s a colossal achievement and one that makes me even more ashamed.    Ashamed that I didn&#8217;t think it was possible, and ashamed that I didn&#8217;t help out.   </p>
<p>To get it working was a bit of a trial though.   It turns out that because I already had the default MonoDevelop 1.0 installed that when I started trying to build a new version things got very confused.    Not only that it turns out that the <a href="http://monodevelop.com/Download">build instructions for MonoDevelop 2.0</a> aren&#8217;t exactly correct.   After a lot of messing around I think I managed to damage the default installation and cross-link a few libraries here and there.    I think if I was doing it again I should probably have followed these instructions <a href="http://www.mono-project.com/Parallel_Mono_Environments">Parallel Mono Environments</a> before doing anything.   Too late now though.    After much building and swearing I ended up uninstalling all Mono environments and then rebuilding everything for Mono 2.4.   I didn&#8217;t put the Hardy version back yet, I&#8217;ll do that if I need to.</p>
<p>Here&#8217;s what I did, in case it helps anyone.</p>
<hr/>
<p>First of all I decided that this is a temporary solution and that eventually I would be able to get MonoDevelop 2.0 running from APT, therefore I decided to install everything in /usr/local.  </p>
<h2>Ubuntu Development Packages</h2>
<p>As ever with Ubuntu you will quite probably need to install a bunch of development libraries to make it work.   I probably had a lot of the dependencies I needed installed before I began but here are the ones that I didn&#8217;t have that I needed.   Your mileage might vary.</p>
<pre><code>sudo apt-get install bison  gnunet-gtk-dev libpango1.0-dev libgtk2.0-dev
libglade2-dev libgnome-dev libart-dev libgnome2-dev libgnome-dev libgnomeui-dev
libgnomeprint2.2-dev libgnomeprintui2.2-dev libgnomecanvas2-dev
libpanel-applet2-dev
</code></pre>
<h2>Mono</h2>
<p>As per the parallel environments guide I set up this environment in a script and executed it.</p>
<pre><code>#!/bin/bash
MONO_PREFIX=/usr/local
GNOME_PREFIX=/usr
export DYLD_LIBRARY_PATH=$MONO_PREFIX/lib:$DYLD_LIBRARY_PATH
export LD_LIBRARY_PATH=$MONO_PREFIX/lib:$LD_LIBRARY_PATH
export C_INCLUDE_PATH=$MONO_PREFIX/include:$GNOME_PREFIX/include
export ACLOCAL_PATH=$MONO_PREFIX/share/aclocal
export PKG_CONFIG_PATH=$MONO_PREFIX/lib/pkgconfig:$GNOME_PREFIX/lib/pkgconfig
PATH=$MONO_PREFIX/bin:$PATH
MONO_GAC_PREFIX=/usr/local
PS1="[mono] \w @ "</code></pre>
<p>I then downloaded the following libraries from the <a href="http://ftp.novell.com/pub/mono/sources-stable/">Mono 2.4 sources page</a>.</p>
<pre><code>wget http://ftp.novell.com/pub/mono/sources/libgdiplus/libgdiplus-2.4.tar.bz2 

http://ftp.novell.com/pub/mono/sources/mono/mono-2.4.tar.bz2

http://ftp.novell.com/pub/mono/sources/gtk-sharp212/gtk-sharp-2.12.8.tar.bz2

http://ftp.novell.com/pub/mono/sources/gnome-sharp220/gnome-sharp-2.20.1.tar.bz2

http://ftp.novell.com/pub/mono/sources/mono-addins/mono-addins-0.4.zip

http://ftp.novell.com/pub/mono/sources/mono-tools/mono-tools-2.4.tar.bz2

http://ftp.novell.com/pub/mono/sources/mono-debugger/mono-debugger-2.4.tar.bz2

http://ftp.novell.com/pub/mono/sources/monodevelop/monodevelop-2.0.tar.bz2

http://ftp.novell.com/pub/mono/sources/monodevelop-debugger-mdb/monodevelop-debugger-mdb-2.0.tar.bz2

http://ftp.novell.com/pub/mono/sources/monodevelop-database/monodevelop-database-2.0.tar.bz2</pre>
<p></code></p>
<p>Extract all these and then run the below command in each.   Because this is a dependency stack you will need to do them roughly in the order they're listed above.</p>
<pre><code>./configure --prefix=/usr/local
make &#038;&#038; sudo make install</code></pre>
<p>After that you should be left with a working MonoDevelop 2.0!   </p>
<h2>Troubles</h2>
<p>I encountered a few problems on the way, mostly there were problems relating to not having the correct Ubuntu development libraries and headers installed when the parts of the stack were configured.   </p>
<p>I also ran into some problems with the GAC having pre-installed versions of conflicting libraries installed.   Eventually though this problem was resolved by uninstalling the default Hardy version of Mono and starting again.   Hopefully you won't have this problem because you will have setup a parallel environment in the first place ...</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackinghat.com/index.php/windows/net/monodevelop-20-makes-me-ashamed/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Principle of Least Surprise</title>
		<link>http://www.hackinghat.com/index.php/windows/net/the-principle-of-least-surprise</link>
		<comments>http://www.hackinghat.com/index.php/windows/net/the-principle-of-least-surprise#comments</comments>
		<pubDate>Fri, 21 Mar 2008 07:13:41 +0000</pubDate>
		<dc:creator>Steve Knight</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.hackinghat.com/index.php/windows/net/the-principle-of-least-surprise</guid>
		<description><![CDATA[I first came across the principle of least surprise a couple of years ago when someone pointed out to me that some script that I had written had violated it.   Naturally defensive, and of course mildly arrogant, I asked my critic what he was talking about.   He said that a command [...]]]></description>
			<content:encoded><![CDATA[<p>I first came across the principle of least surprise a couple of years ago when someone pointed out to me that some script that I had written had violated it.   Naturally defensive, and of course mildly arrogant, I asked my critic what he was talking about.   He said that a command line script should return an explanation of its accepted arguments when given a <strong>&#8211;help</strong> or <strong>-h</strong> argument.    He was right and I was ashamed and so I naturally did what any respectful programmer would do, I fumed quietly for a few hours and then fixed it when he wasn&#8217;t looking.   </p>
<p>It seems then that almost any user-interface should not violate the principle of least surprise and this is common sense.   When I click on a cancel button in a dialog it should not accept my input it should return to where I had come from leaving everything unchanged.   This was my first violation this week and it&#8217;s a common one, a &#8216;Cancel&#8217; button in a dialogue did the opposite of what I expected.   This was in a popular source control tool (that I won&#8217;t name because my version is old and the bug is doubtless fixed now) and it did in fact &#8216;Submit&#8217; the broken change that I was so keen to cancel.   After a short bout of <a href="http://en.wikipedia.org/wiki/Tourrets">tourrette&#8217;s</a> and 5 minutes of trying to figure out how to undo the change I was back on track but my confidence shaken a little.</p>
<p>It&#8217;s not just user-interfaces that should not violate the principle of least surprise, APIs shouldn&#8217;t violate it either.   You know the sort of thing.   For instance, a &#8216;getter()&#8217; should be idempotent and not change any state.  Languages like C++ have support for this through the &#8216;const&#8217; method modifier but I can&#8217;t think of another language that I know of that enforces this in the same way.</p>
<p>So I was incensed when I thought I&#8217;d discovered an example of such a violation in the .NET framework.   I was having trouble using the method <a href="http://msdn2.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx"><strong>Uri.MakeRelative(Uri uri)</strong></a> because I had misunderstood exactly what it did (because I didn&#8217;t RTFM) and I expected it to simply strip the routing information from the Uri and return the document path.    What it actually does is a more general case and it will effectively &#8217;subtract&#8217; one Uri from the other.   Which is more useful when you have things like embedded Uri&#8217;s.   Anyway, the depth of my sickness isn&#8217;t important, the important thing is that I realised that I could have used the principle of least surprise to save me. </p>
<p>As far as I can tell I haven&#8217;t ever found a .NET framework method that didn&#8217;t do as I expected, that&#8217;s partly because of the number of people who use early-release versions of .NET and iron out these problems for me.   Thanks!   Not only that over the years I have entered into a love-hate relationship with Microsoft.   I won&#8217;t enumerate the things I hate because disk space is finite but what I really like is the way that M$ have a vast array of tools and products that seem to co-exist with very little problems.    This is no small feat, it&#8217;s a triumph of quality control and standards and I applaud them.    </p>
<p>The conclusion is then, that I should abide and uphold the principle of least surprise wherever possible.   Additionally though, I can apply the principle in reverse when I trust the source of the interface to not violate the principle.   Moreover if I can succeed in not violating the principle myself then people who use my and my team&#8217;s work will have more confidence in it &#8230; I can dream, can&#8217;t I?   </p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackinghat.com/index.php/windows/net/the-principle-of-least-surprise/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Imperfect Hash (but what percentage is beef?)</title>
		<link>http://www.hackinghat.com/index.php/windows/net/the-imperfect-hash-but-what-percentage-is-beef</link>
		<comments>http://www.hackinghat.com/index.php/windows/net/the-imperfect-hash-but-what-percentage-is-beef#comments</comments>
		<pubDate>Fri, 30 Nov 2007 07:23:22 +0000</pubDate>
		<dc:creator>Steve Knight</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://www.hackinghat.com/index.php/windows/net/the-imperfect-hash-but-what-percentage-is-beef</guid>
		<description><![CDATA[What would you do?  You&#8217;ve got a C# List&#60;T&#62; full of thousands of objects of the same class.   You think there&#8217;s a few duplicates hiding in there somewhere and you want to root them out.    You think that you would really like to put your objects into a dictionary [...]]]></description>
			<content:encoded><![CDATA[<p>What would you do?  You&#8217;ve got a C# List&lt;T&gt; full of thousands of objects of the same class.   You think there&#8217;s a few duplicates hiding in there somewhere and you want to root them out.    You think that you would really like to put your objects into a dictionary because if you did you could get that shiny O(1)-ness that the cool sleek lines of a dictionary is going to give you.   </p>
<p>Only thing is your keys aren&#8217;t exact, they&#8217;re doubles or DateTimes or some such and you can&#8217;t use them because you really need to apply a tolerance to those values.   What you need is an imperfect hash function.</p>
<p>The solution to this problem is obvious to me now but not so obvious at the time when I was trying to speed up my painfully O(N^2) application.   To add your elements into a dictionary and get faster lookup you must obviously include all the elements of the comparison in the Equals() method but <strong>exclude</strong> the non-exact ones from the GetHashCode() method.</p>
<p>Before I start with this analysis I&#8217;d like to apologise to all vegetarians on the planet for eating your friends.   Secondly, and more importantly, I&#8217;d like to apologise to all decent-folk for producing an example so contrived that it will make you want to vomit.   Please pay particular attention to avoid your shoes.</p>
<p>Let&#8217;s begin:</p>
<pre><code><span class="keyword">public class</span> Beefy
{
    <span class="keyword">public string</span>    name;
    <span class="keyword">public double</span>   percentage;

    <span class="keyword">public override bool</span> Equals(object o)
    {
        Beefy b = o <span class="keyword">as</span> Beefy;
        <span class="keyword">if</span> (b == null) <span class="keyword">return false</span>;
        <span class="keyword">return</span> (name.Equals(b.name) &#038;&#038; Math.Abs(percentage - b.percentage) >= 1);
    }

    <span class="keyword">public override int</span> GetHashCode()
    {
         <span class="keyword">return</span> name.GetHashCode();
    }
}
</pre>
<p></code></p>
<p>This works by only relying on the string "name" to derive the hashcode.    What this means is kind-of subtle and relies on what the Dictonary&lt;T&gt; does to resolve collisions.   A collision occurs when two items hash to the same location.   Since we know that for Beefy we're not using a unique identifier to place the items into the Dictionary&lt;T&gt; then that dictionary must have a way of coping with the situation that two hash-codes resolve to the same place.   Now you would need to check the language you love to find out exactly what it does in this instance.   But for .NET 2.0, C# uses a technique called chaining.   That is it creates a secondary data-structure which is commonly referred to as a bucket but is really just another list.   </p>
<p>Looking at the following diagram, (and again my sincere apologies) you'll see that we have 3 topsides in the same bucket.  This happened because the hashcode for the string "Topside" led us to the fourth bucket.   Every time we see "Topside" as the name we will end up inserting the Beefy object into its bucket.   Every time we want to retrieve a "Topside" we will start at the first element of the bucket and iterate over the chain until we find a match.</p>
<p><img id="image73" src="http://www.hackinghat.com/wp-content/uploads/2007/11/dictionarybeef.PNG" alt="Dictionary Beef" /></p>
<p>In this way then we can get the trade-off we need.   Hopefully our inexact matching fields will be few and our exact ones will be many so that we will get close to O(1) performance, however if it all goes horribly badly and every piece of beef we have is "Topside" then we will tend towards an O(N) lookup time.   </p>
<p>This started me thinking.    Exactly what does this continuum look like?   In other words for a trivial class like the one above what sort of read access times would I get searching for each of the 1000 objects in a variety of data structures?  Now what if I vary the number of hashcodes between 1 (i.e. everything hashes to the same bucket) and 1000 (where everything hashes to a different bucket) and try to access the same 1000 objects for each hashcode distribution.   I performed the process on a Dictionary&lt;T&gt;, my List&lt;T&gt; and a Hashtable, which has a <a href="http://msdn2.microsoft.com/en-us/library/ms379571(VS.80).aspx#datastructures20_2_topic6">different collision resolution mechanism in C# to the dictionary</a>.  </p>
<p><img id="image80" style="margin-left: -19px;" src="http://www.hackinghat.com/wp-content/uploads/2007/11/tablevsdict.PNG" alt="Table vs Dictionary (Beef Off!)" /></p>
<p>The results were almost as I expected.   The Dictionary&lt;T&gt; is faster than the Hashtable because when a Hashtable has an imperfect hash the collisions 'spill' over one another which means that other future values can potentially be mis-placed, not just the current one.   However, that performance converges as the quality of the hash improves.   Secondly, the way I set up my List&lt;T&gt; the items being searched for should on average be found in the middle (requiring iteration over half of the List&lt;T&gt; to find a single element).   You can see that for a very imperfect hash where there are less than 100 distinct hashes in 1000 items, it's better to use a List&lt;T&gt; than either a Hashtable or a Dictionary&lt;T&gt;.    At a 90% perfect hash then a List<T> is 22x slower than a Hashtable and more than 50x slower than a Dictionary&lt;T&gt;.</p>
<p>All good news for me because my real hashcode was much more discriminating than that typically sitting above the 90% perfect range.   So the List&lt;T&gt; has gone and my hash is meaty sister.   Very meaty indeed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackinghat.com/index.php/windows/net/the-imperfect-hash-but-what-percentage-is-beef/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MVP (a.k.a MVC) in VB.NET</title>
		<link>http://www.hackinghat.com/index.php/windows/mvp-aka-mvc-in-vbnet</link>
		<comments>http://www.hackinghat.com/index.php/windows/mvp-aka-mvc-in-vbnet#comments</comments>
		<pubDate>Thu, 28 Dec 2006 10:24:15 +0000</pubDate>
		<dc:creator>Steve Knight</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[article]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.hackinghat.com/?p=9</guid>
		<description><![CDATA[Model-view-controller is an old, old, old but very good idea.   It encourages the separation of model, presentation and control from each other.   It&#8217;s used in so many places I can&#8217;t name them but frameworks like: Struts and Ruby-On-Rails actually enforce it.
For a long time it seems to me that Microsoft has [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html">Model-view-controller</a> is an old, old, old but very good idea.   It encourages the separation of model, presentation and control from each other.   It&#8217;s used in so many places I can&#8217;t name them but frameworks like: <a href="http://struts.apache.org/">Struts</a> and <a href="http://www.rubyonrails.org/">Ruby-On-Rails</a> actually enforce it.</p>
<p>For a long time it seems to me that Microsoft has lagged behind in allowing us to use this idea.   Their once flagship product, Visual Basic 6, makes it almost impossible to write good MVC code.    First of all, in VB6 there is no real inheritance which makes writing good models difficult.   Secondly,  if those models should contain any items that generate events then those items can not be defined in a class module and must be made public.  Sure you can simulate and work-around these things by various means but in the end you will just be fighting the language.   And that is never good.   </p>
<p>So it&#8217;s good to see VB.NET, or .NET 2.0 to be precise, not only has excellent object support but a mechanism that can be used for MVC is actually built into the language. <span id="more-9"></span>   Someone mentioned to me, before I started using .NET, that you could use .NET delegates for MVC.   I nodded my head sagely and life continued unchanged for me.    So when it came to actually needing to do MVC in .NET I thought I&#8217;d just Google it and that would be that.    Several articles came back, but it seems that of the articles that actually worked when I tried them the descriptions about the application of MVC to .NET was more than lacking.     In short the articles focused on the event mechanism and that&#8217;s all.   Whilst this is an important part of the puzzle that&#8217;s definitely not all and so this is my attempt.    Hopefully mine will be better <img src='http://www.hackinghat.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>To begin with it&#8217;s worth mentioning that MVC has to be modified to fit into most modern GUI component frameworks.   However, </a>web-based frameworks actually do fit quite neatly into MVC and the approach requires no modification.  </p>
<p>The reason that GUI frameworks are a problem is that today&#8217;s client GUIs are substantially different from the GUIs of yester-year and these days the framework or OS actually takes up the responsibility of some of the parts of the traditional MVC triad.   Unfortunately this is where things often start to go wrong IMHO.   People see the obvious benefits of MVC and try to incorporate it into their GUI applications.   But as we already said MVC does not, as it stands, fit neatly into component based frameworks like Swing or Windows.Forms.   </p>
<p>Some very clever people have thought a lot about this.    If you think I&#8217;m crazy you should first check out a paper written by Taligent systems:  <a id="p10" href="http://www.hackinghat.com/wp-content/uploads/2006/12/mvp.pdf">MVP: Model-View-Presenter</a>.   If you still think I&#8217;m crazy you should read about ObjectArt&#8217;s <a href="http://www.object-arts.com/papers/TwistingTheTriad.PDF">experience</a> with trying to fit MVC (a Smalltalk idea) into their Smalltalk system.   If you still think I&#8217;m crazy I&#8217;ll go and see a psychiatrist.</p>
<p>So a good treatment of MVP is beyond the scope of this post.   But I will break down the component pieces as applied to an example and that should probably serve to demonstrate how it could be done and what&#8217;s trying to be achieved.   </p>
<p>Ok, so let&#8217;s have an example and get on with the show.   The easiest to comprehend is probably going to be something like an order, which has order items.  The presenter adds the items to the order model and the view is then responsibile for showing the order items when they update.</p>
<p><strong>Model</strong><br />
So the model is easy right?   Well sort of, it will be the object generating the events since the model triggers the changes into the view component to change contents of dialog boxes etc.   </p>
<p>So define a VB.NET class that contains an <code>Event</code> that lookes like a function prototype.   And then call it when you want to fire that event.   Simple.     So &#8230;</p>
<pre><code>
Public Class Order
    Public Event OrderChanged()
    Private mItems As List(Of OrderItem) = New List(Of OrderItem)

    Public ReadOnly Property Items() As List(Of OrderItem)
        Get
            Return mItems
        End Get
    End Property

    Public Sub AddItem(ByRef i As Integer)
        Dim item As OrderItem = New OrderItem(i)
        items.Add(item)
        RaiseEvent OrderChanged()
    End Sub
End Class</code></pre>
<p>Most of this code is fairly straight-forward.   The unusual part was that I defined a variable of type <code>Event</code> which has a function style definition that I subsequently access through a call to <code>RaiseEvent</code>.   The way this is going to work is that interested parties in this object will declare an instance of my Order object <code>WithEvents</code> and then also define a public method as <code>Handles [OrderInstace].OrderChanged</code>.    When the model raises the event then all the interested parties will be notified.   </p>
<p>Not for the first time, though, VB.NET is holding out on us.   It has really defined a multi-cast delegate for <code>OrderChanged()</code> behind the scenes which is actually a type.   If we were to attempt to port this solution to C# then we would actually need to define and reference the delegate ourselves in that way.</p>
<p>The affect of this is to produce something very similar to the <a ref="http://en.wikipedia.org/wiki/Observer_pattern">Observer</a> pattern.   Where the adding of a new delegate instance calls <code>registerObserver()</code> and the subtracting calls <code>unregisterObserver()</code>.   Calling the delegate instance itself will force the analgous <code>notify()</code> method, and this is exactly what <code>RaiseEvent</code> will do.</p>
<p>For the remainder of the model we just need some data-holding for the order item.  So lets just add that for fun, no need to discuss.</p>
<pre><code>
Public Class OrderItem
    Private mid As Integer
    Public Sub New(ByVal id As Integer)
        mid = id
    End Sub

    Public Overrides Function ToString() As String
        Return Str(mid)
    End Function
End Class</code></pre>
<p>Finally, note that the model also has a contract with the presenter and the presenter is dependent upon it.  Therefore the presenter will actually call the AddItem() method as a result of actions made in the UI,  more on this shortly.   Note that the model should not be dependent upon any other component.</p>
<p><strong>Presenter</strong></p>
<p>The presenter is relatively straight-forward.   It is the place where this part of the application lives and is responsible for constructing/managing the view and the model.   With the removal of the controller (from traditional MVC) the logic about which components handle which responsibilities is blurred slightly.   Since our MVP definition could lead us to put simple controller functionality directly into the view (since the view handles the windowing event queue messages).    However, we will try and keep this example pure and have the presenter handle all the model prodding and therefore have the view forward calls on to the presenter when something in the model needs to change.   Clearly in a simple example like this the benefit is not clear however larger, more complicated components would benefit from this approach.</p>
<pre><code>
Public Class OrderPresenter
    Private mOrderModel As Order
    Private mOrderView As OrderView
    Public Sub New(ByRef view As OrderView)
        mOrderModel = New Order
        mOrderView = view
        mOrderView.Init(mOrderModel, Me)
    End Sub

    Public Sub AddItem(ByVal partId As Integer)
        mOrderModel.AddItem(partId)
    End Sub
End Class</code></pre>
<p>So exactly what did buy us?   There&#8217;s two answers to this.   Firstly by &#8216;bunching&#8217; our model calls together in a presenter we&#8217;ve allowed ourselves to provide the same functionality from anywhere within our application, so we can hook our presenter/model calls up to a button, or a menu with just a couple of extra code lines.   </p>
<p>Even better though, is that we can remove this presenter and replace it with a different one if it offers the same contract.   To facillitate this we should probably try and place the view/presenter contract behind an interface to make this distinction clear.    I haven&#8217;t done this here but it would be a simple case of defining an interface that the presenter implements that handles <code>AddItem(ByVal as Integer)</code>.   A place that this might be useful is, perhaps, when developing presenters that exhibit additional behaviour to the default implementation.   For instance when an item is added to an order the &#8216;auditing&#8217; presenter could additionally write details of the order change to a database or file.    Clearly any number of presenters can exist.</p>
<p><strong>View</strong></p>
<p>The view therefore is a subscriber to the Model and is the place where user gestures come in to be forwarded to the Presenter.  In this example it is the view for two model objects: Order and OrderItem.</p>
<pre><code>
Public Class OrderView
    Private mOrderPresenter As OrderPresenter
    Private WithEvents mOrderModel As Order
    Private last As Integer = 0

    Public Sub Init(ByRef model As Order, ByRef presenter As OrderPresenter)
        mOrderPresenter = presenter
        mOrderModel = model
    End Sub

    Private Sub OrderChanged() Handles mOrderModel.OrderChanged
        ListBox1.Items.Clear()
        Dim i As OrderItem
        For Each i In mOrderModel.Items()
            ListBox1.Items.Add(String.Format("Part id# {0}", i))
        Next
    End Sub

    Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        mOrderPresenter.AddItem(last)
        last += 1
    End Sub

    Private Sub OrderView_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        mOrderPresenter = New OrderPresenter(Me)
    End Sub
End Class</code></pre>
<p>Our view, of course, is a simple VB form that has a list box in it that lists the items and a button to add an item.   Thus:</p>
<p><img id="image13" src="http://www.hackinghat.com/wp-content/uploads/2006/12/frm1.bmp" alt="OrderView form" /></p>
<p>You will see that the view handles mOrderModel.OrderChanged() as well as events coming from user gestures.   The single user gesture that we handle simply forwards a call on to the Presenter to add an item.   Note that this is probably overly simplistic.   If this were a more concrete example the view might take user input from a combo box, or some other source, and then actually pass model objects onto the presenter.</p>
<p>Now our implementation contains one additional wrinkle and that is that our definition of MVP states that it&#8217;s the presenter that handles the construction of the application model and view.    For simplicity&#8217;s sake here I&#8217;ve actually made the view the application entry point.   From there it constructs the presenter and effectively &#8220;passes&#8221; control over in the expected way.   To circumvent this we would need to step outside of VB.NET&#8217;s application framework which provides useful functionality so is not done here.</p>
<p><strong>Scaling it up</strong></p>
<p>This idea although complete was only presented on a very small scale.   If you were to try and develop an entire application this way things are slightly different.   The truth of the matter is that MVP is probably <b>only</b> applicable to largeish projects and attempting to use it on very small applications is probably a waste of time.</p>
<p>So, scaling up means two different things with respect to MVP.   The model is a little bit amorphous in as much as it is whatever size and shape it is because that&#8217;s the way it needs to be to represent the relationships that exist.   The view and presenter though are somewhat different.    The view/presenter pair will begin by forming groups of controls and ultimately lead to group other view/presenter pairs.   So that the contained view/presenters will receive incoming messages from container views.   In this way a form of separation can exist.   It makes sense then that the contained components know nothing about their surroundings.   Otherwise they can not easily be contained in other components and actually become glued to a specific container. </p>
<p><a id="p14" href="http://www.hackinghat.com/wp-content/uploads/2006/12/mvp.zip">MVP VB.NET solution</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackinghat.com/index.php/windows/mvp-aka-mvc-in-vbnet/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
