<?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>Einar Egilsson</title>
	<atom:link href="http://einaregilsson.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://einaregilsson.com</link>
	<description>A site for my programming pet projects</description>
	<lastBuildDate>Fri, 03 Feb 2012 20:08:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Spades</title>
		<link>http://einaregilsson.com/spades-card-game/</link>
		<comments>http://einaregilsson.com/spades-card-game/#comments</comments>
		<pubDate>Mon, 07 Nov 2011 08:37:25 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[Card Games]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://einaregilsson.com/?p=445</guid>
		<description><![CDATA[Yet another card game finished. The last card game I created was Hearts, which is a trick taking game, but you play on your own. This time I wanted to create a game where you play in teams, so a human player and a computer player work together against two other computer players. So I [...]]]></description>
			<content:encoded><![CDATA[<p>Yet another card game finished. The last card game I created was <a href="http://www.hearts-cardgame.com">Hearts</a>, which is a trick taking game, but you play on your own. This time I wanted to create a game where you play in teams, so a human player and a computer player work together against two other computer players. So I created <a href="http://www.spades-cardgame.com">Spades</a>, a nice trick taking game where you play in teams and must bid before each hand how many tricks you think you&#8217;ll take.<br />
<span id="more-445"></span><br />
It was an interesting game to implement, especially making the computer players work sensibly with their partners. Usually you want to get as many tricks as possible, but you can also bid 0, and then you can&#8217;t take any trick, and your partner has to try to help you out if he sees that you are about to take the trick. You also have to be careful to not get too many tricks above your bid, since if you get 10 tricks more (over the course of a few hands) you&#8217;ll get a big penalty.</p>
<p>I can track the win percentage of the human team and the computer team, so far the computer team only wins about 35% of its games, but it&#8217;s a nice challenge to try to make it win more. And now that the game is live, and has lots of plays every day it&#8217;s a lot of fun to tweak the computer players, publish the new version and then see the next day if the win percentage goes up or down.</p>
<p>For my next project I think I&#8217;ll do something different. I&#8217;ve purchased the domain <a href="http://solitaire-cardgame.com">http://solitaire-cardgame.com</a> and am going to try to create Klondike (classic solitaire) first, if that&#8217;s fun then I&#8217;ll probably add a few others later on.</p>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/spades-card-game/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Online Crazy Eights Card Game</title>
		<link>http://einaregilsson.com/online-crazy-eights-card-game/</link>
		<comments>http://einaregilsson.com/online-crazy-eights-card-game/#comments</comments>
		<pubDate>Wed, 01 Jun 2011 21:20:18 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[Card Games]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/?p=441</guid>
		<description><![CDATA[My pet projects over the last few months have been mostly Visual Studio Extensions and online card games. And now I&#8217;ve finished a new card game. This time I made Crazy Eights, a popular card game in Iceland under the name Olsen Olsen. There are dozens of variations of it possible but I just made [...]]]></description>
			<content:encoded><![CDATA[<p>My pet projects over the last few months have been mostly Visual Studio Extensions and online card games. And now I&#8217;ve finished a new card game. This time I made Crazy Eights, a popular card game in Iceland under the name Olsen Olsen. There are dozens of variations of it possible but I just made a simple one where eights change suits and you can play multiple cards together if they have the same rank. Not much more to say about it, now go and <a href="http://www.crazyeights-cardgame.com">play Crazy Eights online!</a> </p>
<p>UPDATE 28.06.2011: And now I have <a href="http://www.hearts-cardgame.com/">a new card game, Hearts</a>&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/online-crazy-eights-card-game/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ClipboardDiff Visual Studio Extension</title>
		<link>http://einaregilsson.com/clipboarddiff-visual-studio-extension/</link>
		<comments>http://einaregilsson.com/clipboarddiff-visual-studio-extension/#comments</comments>
		<pubDate>Fri, 29 Apr 2011 11:36:09 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Extensions]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Utilities]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/?p=430</guid>
		<description><![CDATA[tl;dr: I made a Visual Studio 2010 extension, ClipboardDiff, which lets you diff selected text against the contents of the clipboard. Get it in the Visual Studio Gallery. Follow me on twitter @einaregilsson to get notified of updates and other cool extensions and stuff. At work I sometimes run into &#8220;evil twin&#8221; methods in our codebase. [...]]]></description>
			<content:encoded><![CDATA[<p><strong>tl;dr:</strong> I made a Visual Studio 2010 extension, ClipboardDiff, which lets you diff selected text against the contents of the clipboard. <a title="Download the extension" href="http://visualstudiogallery.msdn.microsoft.com/a7519ab0-6029-49f3-9243-a74d1718a5bb">Get it in the Visual Studio Gallery</a>.</p>
<p><em>Follow me on twitter <a href="http://twitter.com/einaregilsson">@einaregilsson</a> to get notified of updates and other cool extensions and stuff.</em></p>
<p><a href="http://einaregilsson.com/wp-content/uploads/2011/04/cdlogo.png"><img class="alignright size-full wp-image-432" title="ClipboardDiff Logo" src="http://einaregilsson.com/wp-content/uploads/2011/04/cdlogo.png" alt="" width="140" height="140" /></a>At work I sometimes run into &#8220;evil twin&#8221; methods in our codebase. Those are methods that at a glance look almost exactly the same and where one has obviously been copy pasted from the other but then they have gotten out of sync over time. In these cases I try to refactor the two methods into one and add parameters for any behaviour that was different in the two original methods. But it can be hard to tell exactly what has changed between the two methods, especially when they are dozens of lines each. When dealing with this I used to copy each of the methods into their own temp file and then run a diff tool on them. After doing this a few times I got annoyed at the process, and decided to automate it somehow.<br />
<span id="more-430"></span></p>
<p>I&#8217;ve been playing around with Visual Studio extensions a lot lately and so I decided to make one for this problem. The extension is called ClipboardDiff and is now available in the Visual Studio Gallery. The idea is that you copy the first part of text you want to compare, then you select the next part you want to compare and then run the command &#8216;Diff selection against clipboard&#8217;. The command is available by right clicking on the selected text, it&#8217;s at the bottom of the context menu, or you can invoke it with they keyboard combination Alt+Shift+J. If you want to bind it to another keyboard combination just go into Tools-&gt;Customize-&gt;Keyboard and search for &#8216;ClipboardDiff&#8217;, it&#8217;ll find the command.</p>
<p><a href="http://einaregilsson.com/wp-content/uploads/2011/04/cd.png"><img class="alignnone size-full wp-image-431" title="Running the diff command" src="http://einaregilsson.com/wp-content/uploads/2011/04/cd.png" alt="" width="522" height="381" /></a></p>
<p>You can self choose which diff tool to use, to configure it go to Tools-&gt;ClipboardDiff settings and there you can enter the path to your diff tool of choice, and the arguments you want to pass to it. The placeholder values $FILE1$ and $FILE2$ will be replaced by the temp file names once you invoke the diff command. ClipboardDiff knows the default locations of a few diff programs, so if you have Perforce Merge, Tortoise Diff or WinMerge installed you won&#8217;t have to configure anything (Those are just the tools I happened to have installed on my machine). If you haven&#8217;t configured which tool to use the Settings window will be opened the first time you try to run a diff.</p>
<p><a href="http://einaregilsson.com/wp-content/uploads/2011/04/settings.png"><img class="alignnone size-full wp-image-433" title="Configure which diff tool to use" src="http://einaregilsson.com/wp-content/uploads/2011/04/settings.png" alt="" width="560" height="145" /></a></p>
<p>You can <a title="Download the extension" href="http://visualstudiogallery.msdn.microsoft.com/a7519ab0-6029-49f3-9243-a74d1718a5bb">download the extension in the Visual Studio Gallery</a> and the source, as always, is GPL&#8217;d and available on Github at <a href="https://github.com/einaregilsson/ClipboardDiff">https://github.com/einaregilsson/ClipboardDiff</a>. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/clipboarddiff-visual-studio-extension/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Stop Build on first error in Visual Studio 2010</title>
		<link>http://einaregilsson.com/stop-build-on-first-error-in-visual-studio-2010/</link>
		<comments>http://einaregilsson.com/stop-build-on-first-error-in-visual-studio-2010/#comments</comments>
		<pubDate>Thu, 06 Jan 2011 08:08:48 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Extensions]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[Utilities]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/?p=426</guid>
		<description><![CDATA[tl;dr: StopOnFirstBuildError is Visual Studio 2010 extension that cancels the rest of a solution build if a single project fails to compile, thus saving you time. Download it in the Visual Studio Gallery. Follow me on twitter @einaregilsson to get notified of updates and other cool extensions and stuff. At work I often work on a [...]]]></description>
			<content:encoded><![CDATA[<p><strong>tl;dr:</strong> StopOnFirstBuildError is Visual Studio 2010 extension that cancels the rest of a solution build if a single project fails to compile, thus saving you time. <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/91aaa139-5d3c-43a7-b39f-369196a84fa5">Download it in the Visual Studio Gallery</a>.</p>
<p><em>Follow me on twitter <a href="http://twitter.com/einaregilsson">@einaregilsson</a> to get notified of updates and other cool extensions and stuff.</em></p>
<p>At work I often work on a solution that has around 25 projects. When one of the projects fails to build, Visual Studio insists on trying to build the rest of the projects, even though at that point I don&#8217;t want it to, since I&#8217;m never going to run the program when some of the projects have failed. Often the other projects depend on the project that failed, and the error list gets filled with errors from those projects that just obscure the root cause of the problem. So, I figured I could probably do something about it.</p>
<p><span id="more-426"></span>I googled around for a solution and found a <a href="http://msdn.microsoft.com/en-us/library/microsoft.build.tasks.msbuild.stoponfirstfailure.aspx">StopOnFirstFailure</a> property in MSBuild that sounded promising, but I couldn&#8217;t find any good way to hook into the VS-&gt;MSBuild relationship. I&#8217;m sure there is some way to do this, so if anyone knows, please let me know. The next thing I found was a <a href="http://stevedunns.blogspot.com/2006/10/visual-studio-build-tip.html">tip from Steve Dunn</a>. It&#8217;s a nice little macro that listens for an event that is fired after each project is built, and calls the Cancel Build command if a project has failed to build. You just open the Macro IDE, open the EnvironmentEvents.vb file and paste the following code in at the bottom:</p>
<pre class="brush: vb; title: ; notranslate">
Private Sub BuildEvents_OnBuildProjConfigDone(
                   _ ByVal Project As String,
                   _ ByVal ProjectConfig As String,
                   _ ByVal Platform As String,
                   _ ByVal SolutionConfig As String,
                   _ ByVal Success As Boolean) Handles BuildEvents.OnBuildProjConfigDone
    If Success = False Then 'The build failed...cancel any further builds.
        DTE.ExecuteCommand(&quot;Build.Cancel&quot;)
    End If
End Sub
</pre>
<p>This does 95% of what I wanted to do. But still, I&#8217;m not a big fan of Visual Studio Macros, I prefer extensions where possible so I can easily see in one place what things I have installed instead of digging through the Macro projects. I also wanted to activate the error window after cancelling the build and be able to turn this on and off easily. So, I made an extension out of it. The main thing in it is still the macro code from Steve Dunn above, but in addition the extension:</p>
<ul>
<li>Activates the error list after cancelling the build.</li>
<li>Prints a message to the Build output window, saying why the build was cancelled.</li>
<li>Adds a menu item to the Build menu, &#8220;Stop Build on first error&#8221;, which you can use to turn the functionality on and off easily.</li>
<li>Is context aware, the menu item and functionality are only available in multi-project solutions, since it would be pretty useless in a single project solution.
</ul>
<p>And that&#8217;s it. You can <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/91aaa139-5d3c-43a7-b39f-369196a84fa5">download the extension</a> in the Visual Studio Gallery, get the GPL&#8217;d source code at <a href="https://github.com/einaregilsson/StopOnFirstBuildError">https://github.com/einaregilsson/StopOnFirstBuildError</a> and follow me on Twitter <a href="http://twitter.com/einaregilsson">@einaregilsson</a> to get notified of updates and other new extensions. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/stop-build-on-first-error-in-visual-studio-2010/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Better EventHandler names in Visual Studio 2010</title>
		<link>http://einaregilsson.com/better-eventhandler-names-in-visual-studio-2010/</link>
		<comments>http://einaregilsson.com/better-eventhandler-names-in-visual-studio-2010/#comments</comments>
		<pubDate>Wed, 22 Dec 2010 20:36:14 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Extensions]]></category>
		<category><![CDATA[Utilities]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/?p=422</guid>
		<description><![CDATA[tl;dr: I made a Visual Studio extension, EventHandler Naming, that lets you customize generated eventhandler names and use delegate inference. Not perfect, but works. Download it in the Visual Studio Gallery Follow me on twitter @einaregilsson to get notified of updates and other cool extensions and stuff. The problem I&#8217;ve been annoyed by the eventhandler [...]]]></description>
			<content:encoded><![CDATA[<p><strong>tl;dr:</strong> I made a Visual Studio extension, EventHandler Naming, that lets you customize generated eventhandler names and use delegate inference. Not perfect, but works. <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/14f62cb9-b559-4bad-9388-37da2150e238?SRC=Home">Download it in the Visual Studio Gallery</a></p>
<p><em>Follow me on twitter <a href="http://twitter.com/einaregilsson">@einaregilsson</a> to get notified of updates and other cool extensions and stuff.</em></p>
<h3>The problem</h3>
<p>I&#8217;ve been annoyed by the eventhandler names generated by Visual Studio for years. No, I don&#8217;t really want to name my methods <strong>txtName_TextChanged</strong>, which does not match any reasonable naming convention and looks ugly. I usually prefer something like <strong>OnNameTextChanged</strong> or something similar. Another thing that has annoyed me is</p>
<pre class="brush: csharp; title: ; notranslate">
this.Load +=new EventHandler(OnLoad);
</pre>
<p>instead of just</p>
<pre class="brush: csharp; title: ; notranslate">
this.Load += OnLoad;
</pre>
<p>So, I figured I could probably hack something together to fix these problems fairly easily. As it turns out, some of it was easy, some of it was hard and some of it was impossible.</p>
<p><span id="more-422"></span></p>
<h3>How do you use it?</h3>
<p><a href="http://einaregilsson.com/wp-content/uploads/2010/12/options.png"><img class="alignright size-full wp-image-424" title="options" src="http://einaregilsson.com/wp-content/uploads/2010/12/options.png" alt="" width="309" height="259" /></a></p>
<p>In the Tools menu there is a new menu item, EventHandler Naming. That will give you the options window shown here. The <em>&#8220;Pattern&#8221;</em> is what is used to create the eventhandler names, you can use two macros there, $(EventName) and $(SiteName). EventName is pretty self explanatory, but the SiteName can be the name of the variable/component that owns the event being subscribed to, the typename of the type that owns the event (in the case of static events) or again the typename if you are subscribing to events within the class that owns the event. For both $(SiteName) and $(EventName) you can specify simple transforms like changing the case to camelCase, PascalCase, UPPERCASE or lowercase.</p>
<p>The<em> &#8220;Omit $(SiteName) for own events&#8221;</em> is for the case where you are subscribing to your own, or a base class event. At least for me, if I&#8217;m in a form and am subscribing to its Load event I don&#8217;t want the handler to be named <strong>OnForm1Load</strong>, I just want it to be named <strong>OnLoad</strong>. Whereas if I&#8217;m subscribing to an event from some variable then I want the variable name (sitename) to be a part of the event handler name.</p>
<p>The <em>&#8220;Use delegate inference&#8221;</em> does what is says. Instead of getting <strong>+= new EventHandler(someName)</strong> you will get <strong>+= someName</strong>.</p>
<h3>Implementation: WinForms and WebForms</h3>
<p>Luckily the Win and WebForms designers have a fairly nice API that you can hook into. I just created my own implementation of <strong>IEventBindingService</strong> and implemented the <strong>CreateUniqueMethodName</strong> method. For all other methods I just delegated to the real event binding service. The code to hook that up is as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
    internal class DesignerCreationListener
    {
        internal DesignerCreationListener(IDesignerEventService designerEvents) {
            designerEvents.DesignerCreated += (s, e) =&gt; e.Designer.LoadComplete += OnDesignerLoaded;
        }

        private void OnDesignerLoaded(object sender, EventArgs e)
        {
            IDesignerHost host = sender as IDesignerHost;
            if (host == null)
            {
                return;
            }
            host.LoadComplete -= OnDesignerLoaded;

            Type type = typeof(IEventBindingService);
            IEventBindingService originalService = (IEventBindingService) host.GetService(type);
            if (originalService == null)
            {
                return;
            }

            host.RemoveService(type);
            host.AddService(type, new DesignerEventBindingService(originalService, new PatternNameProvider()));
        }
    }
</pre>
<p><strong>DesignerEventBindingService</strong> is my class, which takes the <strong>originalService</strong> in its constructor and delegates to it as necessary.</p>
<h3>Implementation: Code Window</h3>
<p>The code window implementation is basically a big hack. It&#8217;s the C# language service that takes care of inserting event handlers there and it basically has no hooks or extension points at all. (I would love it if someone proves me wrong on this). So, here I&#8217;m basically listening to two events, <strong>BeforeKeyPress </strong>and <strong>AfterKeyPress</strong>. I&#8217;m just checking whether the keypress is a tab key, doing some heuristics to make sure that we&#8217;re actually creating eventhandlers and not just pressing tab in some arbitrary place.</p>
<p>This is the reason why you get the old eventhandler name in the tooltip first after you press +=, the new name only comes after the delegate constructor is created. I tried everything I could think of to fix that, but the language service itself is responsible for showing that tooltip and drawing text on it and I can&#8217;t hook into that.</p>
<p>The language service is also the reason I have to show the delegate constructor while we are creating the name and only remove the explicit constructor afterwards for delegate inference. If I mess with the delegate constructor before the method is created then the language service just aborts the operation and the next tab key stroke won&#8217;t do anything.</p>
<p>So, overall it&#8217;s missing some things, but for the most part it does what you&#8217;d want.</p>
<h3>Implementation: WPF / XAML</h3>
<p>And this is the impossible part. The XAML designer doesn&#8217;t use the IDesignerHost interface at all, and as far as I could tell from looking at the VSX forum there is just no way to really extend the XAML editor in any meaningful way. It&#8217;s disappointing that they didn&#8217;t use the excellent IEventBindingService there, if someone knows a way that I could hook in here then please let me know.</p>
<h3>Conclusion</h3>
<p>I hope you find the extension useful, the source is GPL and available at<a href="https://github.com/einaregilsson/EventHandlerNaming"> https://github.com/einaregilsson/EventHandlerNaming</a> . If you have any tips, suggestions, or bug requests send me an email or a tweet at <a href="http://twitter.com/einaregilsson">@einaregilsson</a>.  And please tweet and share this if you like it <img src='http://einaregilsson.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 415px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">﻿</div>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/better-eventhandler-names-in-visual-studio-2010/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Write to a file in the Google App Engine Development server</title>
		<link>http://einaregilsson.com/write-to-a-file-in-the-googleapp-engine-development-server/</link>
		<comments>http://einaregilsson.com/write-to-a-file-in-the-googleapp-engine-development-server/#comments</comments>
		<pubDate>Thu, 16 Dec 2010 14:21:23 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[Google App Engine]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Tips & Tricks]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/?p=421</guid>
		<description><![CDATA[The App Engine development server tries to mimic the real environment by making it forbidden to write to the filesystem. However, for certain things you might want to do that anyway, for example to log to a file. In that case you can use this code snippet to enable writing to the filesystem:]]></description>
			<content:encoded><![CDATA[<p>The App Engine development server tries to mimic the real environment by making it forbidden to write to the filesystem. However, for certain things you might want to do that anyway, for example to log to a file. In that case you can use this code snippet to enable writing to the filesystem:</p>
<pre class="brush: python; title: ; notranslate">
if os.environ.get('SERVER_SOFTWARE','').startswith('Dev'):
    from google.appengine.tools.dev_appserver import FakeFile
    FakeFile.ALLOWED_MODES = frozenset(['a','r', 'w', 'rb', 'U', 'rU'])
</pre>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/write-to-a-file-in-the-googleapp-engine-development-server/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Idiot cardgame for Facebook</title>
		<link>http://einaregilsson.com/idiot-cardgame-for-facebook/</link>
		<comments>http://einaregilsson.com/idiot-cardgame-for-facebook/#comments</comments>
		<pubDate>Tue, 07 Dec 2010 22:28:19 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[Card Games]]></category>
		<category><![CDATA[Facebook]]></category>
		<category><![CDATA[Google App Engine]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/?p=419</guid>
		<description><![CDATA[A couple of years ago I created a simple javascript version of the cardgame Idiot. It was very simple, no animation, tracking of scores or anything like that. Still, it got a few users, and there was some activity on it every day. A few months ago I wanted to learn some new technologies. I [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of years ago I created a <a href="http://einaregilsson.com/2008/09/13/idiot-cardgame/">simple javascript version of the cardgame Idiot</a>. It was very simple, no animation, tracking of scores or anything like that. Still, it got a few users, and there was some activity on it every day. A few months ago I wanted to learn some new technologies. I wanted to try Google App Engine, learn more about jQuery and try creating a Facebook app. So, I decided to use Idiot as a test project and create a better version of the game. <span id="more-419"></span></p>
<p>I worked on it on and off for months. No pressure to finish since it was just a hobby project. And finally, on November 18th I launched the new version at <a href="http://www.idiot-cardgame.com">http://www.idiot-cardgame.com</a> and at <a href="http://apps.facebook.com/idiot-cardgame/">http://apps.facebook.com/idiot-cardgame/</a> to play it within Facebook itself.</p>
<div style="border:solid 1px black; margin-bottom:10px; padding:5px; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; background-color:#ddd;"><strong>UPDATE 24.05.2011:</strong> Because the game is better known under the name Shithead I bought a new domain for that, shithead-cardgame.com. Unfortunately both Facebook and Google App Engine were unhappy with a domain with profanity in the title so I forked the code and made a simple anonymous version that&#8217;s not a Facebook app. Go there to <a href="http://www.shithead-cardgame.com/play-shithead-online.html">play shithead card game online</a>.
</div>
<p>The new game has animated playing of cards, shows your avatars and tracks statistics. You can also choose cardbacks and cardfronts, animation speed and some other options, and there is a <a href="http://www.idiot-cardgame.com/highscores">High scores</a> page which shows the 10 best players.</p>
<p>Now, 6 weeks after launch it has about 250 registered Facebook users plus a lot of anonymous users. I wanted to allow anonymous play as well instead of forcing everyone to give their Facebook credentials. However, tracking of statistics and saving preferences requires Facebook registration. There are around 6-700 games played every day and the computer player wins around 45-50% of them.</p>
<p>All in all I&#8217;m happy with the game. I&#8217;ve been adding a few small features and fixing bugs since launch. The next major feature I&#8217;m planning is the ability to play against your friends. The newest App Engine SDK includes support for Comet style connections which would make this a lot easier than it was a few months ago.</p>
<p>Finally, some lessons learned:</p>
<ul>
<li>Create your basic game engine in vanilla javascript and use events (or callbacks) for rendering the actions. I did this and can run games for testing in a simple command line script, which is really nice while you&#8217;re developing the basic game.</li>
<li>Make the human player and the computer player implement the same interface, and let the Game object be ignorant of which player is which. This gives you the ability to play two computer players against each other during testing, which helps a lot if you don&#8217;t want to actually play the game thousands of times during development. I even have hidden options to do this in production so I can just watch an animated game play out.</li>
<li>Facebook SDK documentation is complete crap. Best resource to test things is <a href="http://fbrell.com">http://fbrell.com</a>.</li>
<li>App Engine regularly throws errors when connecting to the Datastore. Not all the time, but it is something you have to plan for.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/idiot-cardgame-for-facebook/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Unit testing model classes in Google App Engine</title>
		<link>http://einaregilsson.com/unit-testing-model-classes-in-google-app-engine/</link>
		<comments>http://einaregilsson.com/unit-testing-model-classes-in-google-app-engine/#comments</comments>
		<pubDate>Mon, 11 Oct 2010 18:25:56 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Google App Engine]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Tips & Tricks]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/?p=416</guid>
		<description><![CDATA[I&#8217;m currently writing my first Google App Engine app. I&#8217;ve created a few model classes which inherit from db.Model and I wanted to unit test them. That works fine until you try to save them to the datastore or retrieve them. Then you might get this error: BadArgumentError: app must not be empty. The problem [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently writing my first <a href="http://appengine.google.com">Google App Engine</a> app. I&#8217;ve created a few model classes which inherit from db.Model and I wanted to unit test them. That works fine until you try to save them to the datastore or retrieve them. Then you might get this error:</p>
<div style="background-color:black; color:white; padding:2px;">
BadArgumentError: app must not be empty.
</div>
<p>The problem here is that you need an environment variable with your app id, which you can set with the following code:<br />
<span id="more-416"></span></p>
<pre class="brush: python; title: ; notranslate">
os.environ['APPLICATION_ID'] = 'myapp'
</pre>
<p>After you do that you&#8217;ll get this error:</p>
<div style="background-color:black; color:white; padding:2px;">
AssertionError: No api proxy found for service &#8220;datastore_v3&#8243;
</div>
<p>To fix that one you need the following lines in your test setup:</p>
<pre class="brush: python; title: ; notranslate">
datastore_file = '/dev/null'
from google.appengine.api import apiproxy_stub_map,datastore_file_stub
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
stub = datastore_file_stub.DatastoreFileStub('myapp', datastore_file, '/')
apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)
</pre>
<p>This temp datastore is persisted just while you run your tests. But you can also give the datastore_file variable a real filename and then it will save the datastore between tests, or you could create different datastore files for different scenarios.</p>
<p>Finally, to put it all together, here is the setUp method for my TestCase classes:</p>
<pre class="brush: python; title: ; notranslate">
class SomeTestCase(unittest.TestCase):
	def setUp(self):
		app_id = 'myapp'
		os.environ['APPLICATION_ID'] = app_id
		datastore_file = '/dev/null'
		from google.appengine.api import apiproxy_stub_map,datastore_file_stub
		apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
		stub = datastore_file_stub.DatastoreFileStub(app_id, datastore_file, '/')
		apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/unit-testing-model-classes-in-google-app-engine/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Module initializers in C#</title>
		<link>http://einaregilsson.com/module-initializers-in-csharp/</link>
		<comments>http://einaregilsson.com/module-initializers-in-csharp/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 15:34:01 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Utilities]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/?p=352</guid>
		<description><![CDATA[One feature of the CLR that is not available in C# or VB.NET are module initializers (or module constructors). A module initializer is simply a global function which is named .cctor and marked with the attributes SpecialName and RTSpecialName. It is run when a module (each .NET assembly is comprised of one or more modules, [...]]]></description>
			<content:encoded><![CDATA[<p>One feature of the CLR that is not available in C# or VB.NET are module initializers (or module constructors). A module initializer is simply a global function which is named .cctor and marked with the attributes SpecialName and RTSpecialName. It is run when a module <small>(each .NET assembly is comprised of one or more modules, typically just one)</small> is loaded for the first time, and is guaranteed to run before any other code in the module runs, before any type initializers, static constructors or any other initialization code. I wanted to use this feature for a project I was doing but was unable to use it directly in C# so I created my own solution. <span id="more-352"></span></p>
<p>Now, why did I need this? Well, I was loading my other assemblies from an unusual place and I wanted to subscribe to the AppDomain.AssemblyResolve event before any types in my assembly were initialized. This feature is clearly not something you&#8217;re going to need every day, (actually I can&#8217;t think of a single other use case where I&#8217;d need it) but if you do, here&#8217;s how I solved it.</p>
<p>I used the excellent <a href="http://www.mono-project.com/Cecil">Mono.Cecil</a> library to create a small program that injects a module initializer into an existing assembly. Cecil is a fantastic library that makes it incredibly easy to manipulate assemblies and can do pretty much anything that you could possibly want to do with IL code. Using it I wrote a small program that simply takes in an assembly filename and the name of a parameterless static void method that exists in the assembly, and injects a module initializer that does nothing but call that method. The original code I wrote, the interesting part without all the error checking and stuff, is shown below:</p>
<pre class="brush: csharp; title: ; notranslate">
string assemblyName = &quot;Test.dll&quot;;
string typeName = &quot;Foo.Bar.ModuleInit&quot;;
string methodName = &quot;Run&quot;;

AssemblyDefinition assembly = AssemblyFactory.GetAssembly (assemblyName);
TypeReference voidRef = assembly.MainModule.Import(typeof(void));
var attributes = MethodAttributes.Static
                | MethodAttributes.SpecialName
                | MethodAttributes.RTSpecialName;
var cctor = new MethodDefinition( &quot;.cctor&quot;, attributes, voidRef);

TypeDefinition type = assembly.MainModule.Types[typeName];
MethodReference methodRef = type.Methods.GetMethod(methodName,new Type[]{});
cctor.Body.CilWorker.Append(cctor.Body.CilWorker.Create(OpCodes.Call, methodRef));
cctor.Body.CilWorker.Append(cctor.Body.CilWorker.Create(OpCodes.Ret));
assembly.MainModule.Inject(cctor, assembly.MainModule.Types[&quot;&lt;Module&gt;&quot;]);
AssemblyFactory.SaveAssembly(assembly, assemblyName);
</pre>
<p>I then added all the neccessary error handling, unit testing etc. and the resulting program can be <a href="/download/InjectModuleInitializer.exe">downloaded here</a>. The program is just a single executable since I embedded the Cecil assemblies as resources and load them by handling the AppDomain.Current.AssemblyResolve event. You can run it from the command line and give it the filename of your assembly and optionally specify the method to call and a key file to strong name sign the assembly after the injection. If no method is explicitly specified then the program looks for a type named ModuleInitializer (may be in any namespace) and looks for a method named Run in that type and calls that method in the module initializer.</p>
<p>Run without specifying the method, looks for ModuleInitializer::Run in any namespace.</p>
<p class="console"> InjectModuleInitializer.exe Test.dll</p>
<p>Run and specify the method as Foo.Bar.SomeClass::SomeMethod</p>
<p class="console"> InjectModuleInitializer.exe /m:Foo.Bar.SomeClass::SomeMethod Test.dll</p>
<p>Run and specify a keyfile to use for strong name signing</p>
<p class="console"> InjectModuleInitializer.exe /k:mykeyfile.snk Test.dll</p>
<p>Realistically though, if you want to do this you probably want to do it right after building your assembly.  The best way to do that is to use the &lt;Exec/&gt; command in MSBuild in the AfterBuild target. To do that you can have the following in your .csproj file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Target Name=&quot;AfterBuild&quot;&gt;
    &lt;Exec Command='InjectModuleInitializer.exe &quot;$(TargetPath)&quot;' /&gt;
&lt;/Target&gt;
</pre>
<p>Or, if you want to explicitly specify the method to run:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Target Name=&quot;AfterBuild&quot;&gt;
    &lt;Exec Command='InjectModuleInitializer.exe /m:MyNameSpace.MyClassName::MyMethodName &quot;$(TargetPath)&quot;' /&gt;
&lt;/Target&gt;
</pre>
<p>If you have set up your project to sign your assembly you will have the name of the strong name file in the $(AssemblyOriginatorKeyFile) variable. You can sign the assembly after the injection with:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Target Name=&quot;AfterBuild&quot;&gt;
    &lt;Exec Command=&quot;InjectModuleInitializer.exe /k:&quot;$(AssemblyOriginatorKeyFile)&quot; /m:MyNameSpace.MyClassName::MyMethodName &quot;$(TargetPath)&quot; /&gt;
&lt;/Target&gt;
</pre>
<p>And there you have it. You can <a href="/download/InjectModuleInitializer.exe">download the console program</a> or <a href="https://github.com/einaregilsson/InjectModuleInitializer">get the source on GitHub</a> and build it yourself (You can download a zip file there if you don&#8217;t want to mess with Git). Enjoy.</p>
<div style="font-size:14px">
<strong>UPDATE 03.02.2012: </strong> Now updated to version 1.3. Dropped MSBuild support, although it can of course still be used in MSBuild with the Exec command. Added support for strong name signing</p>
<p><strong>UPDATE 12.01.2012: </strong> Now updated to version 1.2. Supports injecting into .NET 2.0 and .NET 4.0 assemblies. Source code now lives on github at <a href="https://github.com/einaregilsson/InjectModuleInitializer">https://github.com/einaregilsson/InjectModuleInitializer</a>.</p>
<p><strong>UPDATE 04.05.2010: </strong> Now updated to version 1.1 with better support for Pdb files and using Mono.Cecil v0.9 instead of 0.6. That also means that the simple example in the blog post is no longer like the actual code, since Mono.Cecil changed drastically between versions. Thanks to Jonathan Evans for his help in figuring out how to get debug symbols to work correctly.
</div>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/module-initializers-in-csharp/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>Easy way to have custom icons in Visual Studio AddIn</title>
		<link>http://einaregilsson.com/easy-way-to-have-custom-icons-in-visual-studio-addin/</link>
		<comments>http://einaregilsson.com/easy-way-to-have-custom-icons-in-visual-studio-addin/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 09:39:34 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Extensions]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/?p=305</guid>
		<description><![CDATA[I&#8217;ve recently been developing a Visual Studio AddIn and I wanted to use custom icons for a command I had. Looking for a solution I found the offical MSDN article on the subject, that might possibly be the most misleading and useless article ever. Add the resource file in Visual Studio, then exclude from project, [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently been developing a Visual Studio AddIn and I wanted to use custom icons for a command I had. Looking for a solution I found the <a href="http://msdn.microsoft.com/en-us/library/ms228771.aspx">offical MSDN article on the subject</a>, that might possibly be the most misleading and useless article ever. Add the resource file in Visual Studio, then exclude from project, rename your images to numbers, edit with Notepad and then build satellite assemblies on the commandline? Really? That is a horrible way to do it and not at all necessary. I&#8217;ve found a very simple and easy way to add these icons without all that hassle.</p>
<p><span id="more-305"></span></p>
<p>There are a couple of other articles out there that approach the problem in a different way. Roy Osherove has an <a href="http://weblogs.asp.net/rosherove/archive/2008/08/02/howto-set-custom-visual-studio-addin-menu-icons-without-a-satellite-dll.aspx">article</a> where he shows how you can add icons without having satellite assemblies for them, but that has &gt; 350 lines of code for loading the images yourself including P/Invokes and all sorts of stuff, and I didn&#8217;t really need such a heavyweight solution. To be fair, his solution does give you the ability to use .ico files as well, and offers transparency, but transparency can be achieved in an easier way.</p>
<p>I also found <a href="http://www.mztools.com/articles/2005/MZ2005007.aspx">another article</a> that shows how you can get transparency by using a special color that, as far as I know, is not documented anywhere officially. It also shows you how you can build a satellite assembly from Visual Studio without resorting to Notepad and the command line tools, but this approach uses a special project for the satellite assembly, which is completely unneccessary.</p>
<p>So, finally, my approach, which is really a refinement of the last article I mentioned. If your add-in is meant for only VS2008 then you can get away with having no satellite assembly, VS2008 falls back to looking in your main assembly for the resources if it doesn&#8217;t find a satellite assembly. If you want to support VS2005 you must have a satellite assembly for it to work.</p>
<p>So, assume we have a project named MyProject which will compile to an assembly called MyProject.dll. Here&#8217;s what you do:</p>
<ol>
<li>Add a new &#8216;resources&#8217; item to the project and give it the name &#8220;MyProject.en.resx&#8221;.</li>
<li>Go the properties for the item and set the &#8220;Custom Tool&#8221; field to nothing. This will remove the auto-generated code for the .resx file</li>
<li>Double click on the .resx file, this opens up the resource editor. There you can add an existing image (Add Resource-&gt;Add existing file). The image should be a 16&#215;16 pixel bitmap image. It must be in True Color format. True Color is the same as a 24-bit bitmap.</li>
<li>If you want transparency in your image then use the special color: Red:0 , Green:254, Blue:0 . Note that it really is 254, NOT 255.</li>
<li>In the resource editor, give your image a name that is a number, e.g. 1. Note that you did not have to change the filename of your image file, just its name in the resource file.</li>
<li>Now add your command in your add-in file like so:
<pre class="brush: csharp; title: ; notranslate">
commands.AddNamedCommand2(_addInInstance, &quot;MyProject&quot;,
      &quot;MyProject&quot;, &quot;Executes the command for MyProject&quot;,
      false,
      1,
      ref contextGUIDS,
      (int)vsCommandStatus.vsCommandStatusSupported +
      (int)vsCommandStatus.vsCommandStatusEnabled,
      (int)vsCommandStyle.vsCommandStylePictAndText,
      vsCommandControlType.vsCommandControlTypeButton);
</pre>
<p>There you must send in <strong>false</strong> and then the number you gave the icon in your .resx file, e.g. 1.</li>
</ol>
<p>Now when you compile your solution, a satellite assembly with the name MyProject.resources.dll will automatically be created and put in a &#8220;en&#8221; subfolder of your output folder. If you only want to support VS2008 and don&#8217;t want satellite assemblies then you can name the .resx file just MyProject.resx instead, then no satellite assemblies will be created and the resources will be embedded in the main assembly.</p>
<p>And that&#8217;s it. Add more resources in Visual Studio, have things compile automatically and don&#8217;t touch command line tools, notepad, hundreds of lines of custom code or anything like that. I *think* it is enough to just have the &#8220;en&#8221; resources dll even if you use another locale, I&#8217;m pretty sure Visual Studio falls back to that if it doesn&#8217;t find a satellite assembly in your current culture. At least I have my Windows set up for Danish, but my &#8220;en&#8221; satellite assembly works just fine for me. Although, there doesn&#8217;t exist a Danish version of Visual Studio, maybe this works differently for localized Visual Studio, e.g. the German version. If someone has one of those and can test I&#8217;d love to know whether it falls back to &#8220;en&#8221; if nothing else is available. If it doesn&#8217;t then just create a few more MyProject.de.resx, MyProject.es.resx etc. to get more satellite assemblies. But like I said before, VS2008 and later doesn&#8217;t need this, so for that case just have the one MyProject.resx file.</p>
<p>I&#8217;ve made the small MyProject example and it can be <a href="/download/MyProjectAddIn.zip">downloaded here</a>. Let me know if this works (or doesn&#8217;t) for you. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/easy-way-to-have-custom-icons-in-visual-studio-addin/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

