<?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 &#187; Code</title>
	<atom:link href="http://einaregilsson.com/category/code/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>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>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>While Compiler for the .NET Platform</title>
		<link>http://einaregilsson.com/while-compiler-for-the-dotnet-platform/</link>
		<comments>http://einaregilsson.com/while-compiler-for-the-dotnet-platform/#comments</comments>
		<pubDate>Fri, 06 Feb 2009 14:12:34 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[Boo]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Compilers]]></category>
		<category><![CDATA[While Language]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/?p=191</guid>
		<description><![CDATA[My masters project at DTU involves writing compilers for the .NET platform and since I had never written a compiler before I decided to start by writing a compiler for a simple language called While. This language is used in the Program Analysis course that is taught at DTU and has integer and boolean expressions, [...]]]></description>
			<content:encoded><![CDATA[<p>My masters project at DTU involves writing compilers for the .NET platform and since I had never written a compiler before I decided to start by writing a compiler for a simple language called While. This language is used in the Program Analysis course that is taught at DTU and has integer and boolean expressions, read and write commands, an if branching statement and a while looping statement. The compiler compiles this language and the programs can be run with the .NET CLR or Mono. The programs can also be debugged using a free graphical .NET debugger. I put the project up on Github, I think it is a fairly nice example of a simple compiler for .NET.The compiler and its source code along with a better description of the language is available at <a href="https://github.com/einaregilsson/While-Language">https://github.com/einaregilsson/While-Language</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/while-compiler-for-the-dotnet-platform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extensionless urls in ASP.NET MVC on IIS 6</title>
		<link>http://einaregilsson.com/extensionless-urls-in-asp-net-mvc-on-iis-6/</link>
		<comments>http://einaregilsson.com/extensionless-urls-in-asp-net-mvc-on-iis-6/#comments</comments>
		<pubDate>Thu, 06 Nov 2008 18:45:52 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Tips & Tricks]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/?p=129</guid>
		<description><![CDATA[I recently started playing around with ASP.NET MVC to build a small website. I&#8217;m pretty impressed, I like working with MVC a lot better than the web forms model. One thing that ASP.NET MVC offers is to have &#8220;pretty urls&#8221; similar to frameworks like Ruby on Rails or Django, that is, instead of urls that [...]]]></description>
			<content:encoded><![CDATA[<p>I recently started playing around with <a href="http://asp.net/mvc">ASP.NET MVC</a> to build a small website. I&#8217;m pretty impressed, I like working with MVC a lot better than the web forms model. One thing that ASP.NET MVC offers is to have &#8220;pretty urls&#8221; similar to frameworks like <a href="http://rubyonrails.org">Ruby on Rails</a> or <a href="http://djangoproject.com">Django</a>, that is, instead of urls that look like <strong>http://example.com/index.aspx?car=Ford&#038;year=1990</strong> you get urls like <strong>http://example.com/cars/Ford/1990</strong>. This works flawlessly in Visual Studio using the development webserver but there can be some complications when deploying to IIS. The new IIS 7 has support for this built in when using integrated mode, however my webhost is still on IIS 6 and there are problems there. Essentially there are two ways that can be used with IIS 6. The first way is to map all requests to the ASP.NET engine, even ones for images, css etc. That works but has some performance implications. The other way is to use a file extension in all urls, so our example url might have to be something like <strong>http://example.com/cars.aspx/Ford/1990/</strong>. That&#8217;s not horrible but not the way I want it either. So, I came up with another way. <span id="more-129"></span></p>
<p>I wrote a blog post a while ago about how to get <a href="/2007/07/30/pretty-wordpress-permalinks-on-iis/">pretty wordpress permalinks on IIS</a> using IIS&#8217;s 404 page, so I figured I might be able to hack something similar together for this. Just a bit about how the IIS 404 page works: when IIS doesn&#8217;t find an item for a request it will execute the 404 page with the missing page&#8217;s url as a querystring. So, if we make a request for <strong>http://example.com/doesntexist</strong> and the 404 page is <strong>/notfound.aspx</strong> then the server executes <strong>http://example.com/notfound.aspx?404;http://example.com/doesntexist</strong>. The important thing here is that IIS executes this in response to the original request, it does not redirect to this page. That means that even as we&#8217;re executing the 404 page the user still sees <strong>http://example.com/doesntexist</strong> in his browser url bar. (Note that when you set the 404 page in IIS it allows you to specify either <em>file</em> or <em>url</em>, you must choose <em>url</em>. Shared hosting webhosts typically offer just <em>url</em>, at least mine only does. Also, the 404 page you can specify in web.config is a completely different thing, that is redirected to and so is useless for this.)</p>
<p>When you create a new MVC project in Visual Studio you get a file called Default.aspx in your root directory. (Note: this whole article is about how things are in the MVC beta, they might change in other versions). In the codebehind file, Default.aspx.cs there is a page load method that does some rewriting and then executes an Mvc http handler. I set this file to be my 404 page in IIS (you might use a different file if you want it somewhere else) and then changed its Page_Load method to be like this:</p>
<pre class="brush: csharp; title: ; notranslate">
public void Page_Load(object sender, System.EventArgs e) {
    string querystring = Request.ServerVariables[&amp;amp;quot;QUERY_STRING&amp;amp;quot;];
    if (querystring.StartsWith(&amp;amp;quot;404;&amp;amp;quot;)) {
        int startPos = querystring.IndexOf('/', &amp;amp;quot;404;https://1&amp;amp;quot;.Length);
        HttpContext.Current.RewritePath(querystring.Substring(startPos));
    } else {
        HttpContext.Current.RewritePath(Request.ApplicationPath);
    }
    IHttpHandler httpHandler = new MvcHttpHandler();
    httpHandler.ProcessRequest(HttpContext.Current);
}
</pre>
<p>If we step through this a bit, first it checks if the querystring starts with 404; in that case the page is being executed as a 404 page, otherwise we do what this file previously did. Then we parse out the path from our querystring, rewrite it into our current http context and then execute the MvcHttpHandler on it. So, all requests with paths like <strong>/cars/Ford/1990</strong> will end up here where we parse the relevant bit out of them and execute them with MVC.</p>
<p>Now we have this working, but at the expense of ruining the real 404 system. Any 404 request will be routed through there, no matter what it&#8217;s for, so how can we handle real 404&#8242;s? What I did was to add a new Action to my HomeController called PageNotFound which simply looks like this:</p>
<pre class="brush: csharp; title: ; notranslate">
public ActionResult PageNotFound(string path) {
    ViewData[&amp;amp;quot;path&amp;amp;quot;] = &amp;amp;quot;/&amp;amp;quot; + path;
    Response.StatusCode = 404;
    return View();
}
</pre>
<p>and then I added a catch-all rout map at the very bottom of my route map, like so:</p>
<pre class="brush: csharp; title: ; notranslate">
routes.MapRoute(
    &amp;amp;quot;PageNotFound&amp;amp;quot;,                                      // Route name&amp;amp;lt;/span&amp;amp;gt;
    &amp;amp;quot;{*path}&amp;amp;quot;,                                           // URL with parameters&amp;amp;lt;/span&amp;amp;gt;
    new { controller = &amp;amp;quot;Home&amp;amp;quot;, action = &amp;amp;quot;PageNotFound&amp;amp;quot;}  // Parameter defaults&amp;amp;lt;/span&amp;amp;gt;
);
</pre>
<p>The <strong>{*path}</strong> means that this will match any possible path, having it at the bottom means that it will only ever execute if no other route matches => this is executed for pages that don&#8217;t exist. Then it passes the non-existent path to the controller, which sets the status code to 404 and adds the path to the ViewData, so the view can print a nice error message. One thing I had to change also was to remove the <em>Default</em> route from the route map, the one that had the url defined as <strong>{controller}/{action}/{id}</strong>. I removed it because it matched any url with three components and in the case when the components didn&#8217;t match any controller or action I got some ugly error message about missing controllers when what I really wanted was a 404 page. Instead I just explicitly state my routes now and usually don&#8217;t have the <strong>{controller}</strong> or <strong>{action}</strong> in the urls. With a bigger site this might be annoying and there are probably cleaner ways to handle it so any suggestions are welcome in the comments.</p>
<p>So that&#8217;s it. It&#8217;s all a big hack, but it does work without reducing performance by mapping everything to asp.net. I&#8217;m also not sure if the raw logs will show all those requests as 404&#8242;s or 200&#8242;s since my webhost doesn&#8217;t let me see raw lows for my subdomains, but I think they&#8217;ll be marked as 200. This has also only been tested when the site is in the root folder, I don&#8217;t know if it will work unchanged if the application is in a subfolder on the server. </p>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/extensionless-urls-in-asp-net-mvc-on-iis-6/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Idiot cardgame (a.k.a. Shithead)</title>
		<link>http://einaregilsson.com/idiot-cardgame/</link>
		<comments>http://einaregilsson.com/idiot-cardgame/#comments</comments>
		<pubDate>Sat, 13 Sep 2008 18:47:33 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[Card Games]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/?p=107</guid>
		<description><![CDATA[UPDATE 20.10.2010: A few days ago I launched a completely revamped version of this game, with animation, tracking of results, connection to Facebook and a lot more. That means that the blog post is completely out of date! Play the new version at http://www.idiot-cardgame.com or at http://www.shithead-cardgame.com. Or, you can play the original version, the [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE 20.10.2010:</strong> A few days ago I launched a completely revamped version of this game, with animation, tracking of results, connection to Facebook and a lot more. That means that the blog post is completely out of date! Play the new version at <a href="http://www.idiot-cardgame.com">http://www.idiot-cardgame.com</a> or at <a href="http://www.shithead-cardgame.com/play-shithead-online.html">http://www.shithead-cardgame.com</a>. Or, you can play the original version, the one that this blog post is talking about at <a href="http://einaregilsson.com/idiot/">http://einaregilsson.com/idiot/</a>. </p>
<p>Original blog post follows:</p>
<p>The last few weeks my hobby project has been creating a cardgame in Javascript. I&#8217;ve always wanted to create a cardgame and I decided to use simple Javascript so I could make it available online since no-one wants to bother to download small games. I figured there were thousands of blackjacks and solitaires out there so I decided to create my favorite cardgame, Idiot. <span id="more-107"></span>After googling around I found that there was a <a href="http://en.wikipedia.org/wiki/Shithead_(card_game)">Wikipedia page</a> about it under the name Shithead which listed all sorts of different variations. My variation uses the rules that I&#8217;ve usually used in real life:</p>
<ul>
<li>The point is to lose all your cards by putting them on the pile, a card that is put on the pile must be equal or higher than the top card of the pile. If you have no card to put on the pile you must take the entire pile.</li>
<li>There are always three cards in your hand, if you have less than three you must draw enough cards from the deck to get three again. After the deck is finished no more cards are drawn.</li>
<li>There are three downwards facing cards and three upwards facing cards on the table. You cannot play them until your hand is finished. You cannot look at a downward facing card before playing it.</li>
<li>Before you start you can exchange cards from your hand with the upwards facing cards on the table.</li>
<li>You can put a two on top of everything, it is the restart card.</li>
<li>You can put a five on top of everything, it is the reverse card, meaning that in the next turn the opponent must put a card equal or lower than five.</li>
<li>You can put a ten on top of everything and it burns the pile, and you get to put out the first card in the new pile.</li>
<li>You can put out more than one card at a time as long as they have the same rank.</li>
<li>If there are four cards with the same rank at the top of the pile then the pile is removed.</li>
<li>If you have no card that you can put on top of the pile then you may draw the top card of the deck and put on the pile, if it is a legal move then you do not have to take the pile.</li>
</ul>
<p>The game can be played at the url <a href="http://einaregilsson.com/idiot/">http://einaregilsson.com/idiot/</a>. As for the implementation, don&#8217;t expect any animation or fancy stuff. You simply choose the cards you want to put out and press the <em>Play selected cards</em> button. When the computer is playing the cards simply disappear from its hand and show up on the pile. However there is a small delay between each move by the computer so you can see when it puts out two or more cards and when it&#8217;s drawing cards. As for the rule about drawing a card off the top of the deck when you have to take the pile, that is done automatically. You simply press the <em>Take the pile</em> button and you will see a new card appear at the top of the pile (given that the deck is not empty). If the move is legal then the pile will stay, if it is not legal you will get the whole pile in your hand.</p>
<p>The game is implemented in two files, <a href="/download/cards.js">cards.js</a> and <a href="/download/idiot.js">idiot.js</a>. Cards.js is a generic library that has a base class for a card container and concrete classes for a hand, deck and card, it could easily be re-used for any card game. Idiot.js is the game itself, it works allright, although there are a lot of edge cases that could be added to the computer player to make it smarter. The code is pretty heavily commented so it should be easy to follow should anyone want to extend the game or use the library for something. The game files are licensed under a <a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution license</a> and so can be used for pretty much anything, they have been tested on the latest versions of all the major browsers. Please leave any error reports or suggestions as comments on this page.</p>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/idiot-cardgame/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Subtitle Fixer</title>
		<link>http://einaregilsson.com/subtitle-fixer/</link>
		<comments>http://einaregilsson.com/subtitle-fixer/#comments</comments>
		<pubDate>Thu, 20 Mar 2008 13:04:13 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Utilities]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/2008/03/20/subtitle-fixer/</guid>
		<description><![CDATA[I was watching a movie on my computer the other day and I had gotten the subtitles for it off the internet, I think from http://opensubtitles.com or something like that. The only problem was that they were a bit out of sync with the picture, about 2 seconds too late. Using a good media player, [...]]]></description>
			<content:encoded><![CDATA[<p>I was watching a movie on my computer the other day and I had gotten the subtitles for it off the internet, I think from <a href="http://opensubtitles.com">http://opensubtitles.com</a> or something like that. The only problem was that they were a bit out of sync with the picture, about 2 seconds too late. Using a good media player, such as <a href="http://videolan.org">VLC</a> you can add an offset to the subtitles every time you watch the movie but I figured I could probably whip up a small script to do it for me so I could just do it once and then have the subtitles correct every time I watched the movie. <span id="more-58"></span> The subtitles were in the .srt format, which is basically just a very simple text file with time information and the text, a typical screen is something like</p>
<pre>
00:20:24,345 --> 00:20:25,200
Hello there.
How are you?
</pre>
<p>So I created a little script, suboffset.py, which takes in the name of a subtitle file and the offset to add to the file in milliseconds, modifies the file contents and writes it back out to the same file. Alternately you can specify &#8211; as the filename and then the script will read the file from stdin and write the output to stdout so you can pipe it together to write to another file. The original script was about 10 lines, but just to make it a little more useful I made it a module so you could get access to the script from other scripts and added the stdin option and some comments. You can view the script below or <a href="http://einaregilsson.com/download/suboffset.py">download the actual script here</a>.</p>
<pre class="brush: python; title: ; notranslate">
#!/usr/bin/python
&quot;&quot;&quot;
   Script to offset the time in subtitle files in the .srt format. Script
   takes in the filename and the offset (in milliseconds) to add or
   subtract from the subtitles. It then writes the new subtitles to the
   same file. Alternately you can specify the filename as '-' and then
   the script will read input from stdin and write output to stdout.

&quot;&quot;&quot;

__version__   = '1.0'
__author__    = 'Einar Egilsson'
__date__      = 'March 20th 2008'
__url__       = 'http://einaregilsson.com/2008/03/20/subtitle-fixer/' 

import sys, re, datetime

MILLISECOND = 1
SECOND = 1000 * MILLISECOND
MINUTE = 60 * SECOND
HOUR = 60 * MINUTE

def offset_time(time, offset):
    &quot;&quot;&quot; Takes in list with [hour, minute, second, millisecond] and returns
        it with offset milliseconds added and normalized
    &quot;&quot;&quot;
    ms = sum(map(int.__mul__,  time, [HOUR, MINUTE, SECOND, MILLISECOND]))
    ms += offset
    return [ms / HOUR, ms % HOUR / MINUTE, ms % MINUTE / SECOND, ms % SECOND]

def fix_subtitles(lines, offset, output):
    &quot;&quot;&quot; Takes in list (lines) with all the lines from the subtitle file, adds
        offset milliseconds to it and writes the file to output.
    &quot;&quot;&quot;
    for line in lines:
        pattern = r'(\d\d):(\d\d):(\d\d),(\d\d\d) --&gt; (\d\d):(\d\d):(\d\d),(\d\d\d)'
        match = re.match(pattern, line)
        if match:
            nrs = [int(nr) for nr in match.groups(0)]
            start = offset_time(nrs[:4], offset)
            end = offset_time(nrs[4:], offset)
            output.write('%02d:%02d:%02d,%03d' % tuple(start))
            output.write(' --&gt; ')
            output.write('%02d:%02d:%02d,%03d\n' % tuple(end))
        else:
            output.write(line)

def print_header():
    print 'Subtitle Fixer v%s' % __version__
    print 'Author: %s' % __author__
    print __url__
    print ''

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print_header()
        print 'Usage: suboffset.py &lt;filename&gt; &lt;offset-in-milliseconds&gt;'
        print 'Use - for filename to read from stdin and print to stdout'
        sys.exit(1)

    offset = int(sys.argv[2])
    file = None
    if sys.argv[1] == '-': #Read from stdin and print to stdout
        fix_subtitles(sys.stdin.readlines(), offset, sys.stdout)
    else: #read from file and write to same file
        file = open(sys.argv[1], 'r')
        lines = file.readlines()
        file.close()
        file = open(sys.argv[1], 'w')
        fix_subtitles(lines, offset, file)
        file.close()
        print 'Finished adding %s milliseconds to %s' % (offset, sys.argv[1])
</pre>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/subtitle-fixer/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Binary Tree Image</title>
		<link>http://einaregilsson.com/binary-tree-image/</link>
		<comments>http://einaregilsson.com/binary-tree-image/#comments</comments>
		<pubDate>Thu, 20 Sep 2007 23:37:33 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/2007/09/20/binary-tree-image/</guid>
		<description><![CDATA[Recently I had a school project where we needed to parse a certain grammar into a syntax tree and do some analysis on the code. Everytime I&#8217;ve had to work with trees (which has only been for school projects actually) I&#8217;ve been frustrated because it can be hard to visualize the tree, especially when it [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I had a school project where we needed to parse a certain grammar into a syntax tree and do some analysis on the code. Everytime I&#8217;ve had to work with trees (which has only been for school projects actually) I&#8217;ve been frustrated because it can be hard to visualize the tree, especially when it starts getting large. I&#8217;ve pretty much done two things in that situation, either draw the tree on a piece of paper, which takes a lot of time and is very boring, or try to look through the structure in the debugger, which gives you some idea but is not really very convenient. So, when I was working on this new project I figured I could probably come up with some simple way of displaying the tree while I was working on it. I wanted the solution to be re-usable so I could pull it out again the next time I have to work with binary trees without having to change it to match the new project. So, here&#8217;s what I came up with.<br />
<span id="more-56"></span></p>
<p>I created an interface called INode, which looks like this:</p>
<pre class="brush: csharp; title: ; notranslate">
public interface INode
{
    INode Left { get;}
    INode Right { get; }
    string Text { get;}
    object Value { get; }
}
</pre>
<p>In every binary tree structure I&#8217;ve ever made the nodes have pretty much looked like this, so this interface should be general enough that I could use it again. Then I created a class called BinaryTreeImage, which takes the root node of the tree as an argument in the constructor. It has four public methods (+ some overloads) that you can use to view the tree:</p>
<pre class="brush: csharp; title: ; notranslate">
//The bitmap object for the image
public virtual Bitmap Bitmap

//Saves the image to file as a .jpg
public virtual void Save(string filename)
//Saves the image to file in the specified image format
public virtual void Save(string filename, ImageFormat format)

//Writes the file to an outputstream in jpg format, for instance a response
//stream in an asp.net application
public virtual void WriteToStream(Stream outputStream)
//Writes the file to an outputstream in the specified image format
public virtual void WriteToStream(Stream outputStream, ImageFormat format)

//Saves the file as a temporary jpg file, then launches it so it will open in
//your default jpg editor
public virtual void Show()
</pre>
<p>In my current project I just added a -img switch to the program, and if it was set I used the Show() method to launch the image as soon as the tree was parsed. That made it a lot easier to work with and get a better grasp of the trees I was using.</p>
<p>When you draw the binary tree you have to figure out how much space it&#8217;s gonna need to draw all the nodes. The naive way of calculating this is to first find the depth of the tree, then figure out how many nodes can possibly be in the bottom row, with 2<sup>maxdepth-1</sup>, and make the image wide enough to fit all those nodes in. Then you can just draw the nodes at the exact places that they should be if the tree was full and then everything is great, right? Wrong! I tried that approach first and while it works, it has some problems. As soon as you have a tree that&#8217;s more than 5 or 6 levels deep you start getting a reeaally wide tree! If the tree is full than that can&#8217;t be helped, that&#8217;s just how wide the tree has to be. But if you have a pretty sparse tree (like I did) then you start getting some really crappy drawings. For instance, the root node of my syntax tree always had only one childnode. So when I had a few levels I had an image that was something like 3000 pixels wide, but was only using the right 1500 pixels of all that space.</p>
<p>So I thought about how I could fit my tree in as little space as possible and I finally found a solution that works pretty well. Recursion to the rescue! What I do now is use a depth first traversal and on the way back up I calculate the width of every subtree.</p>
<pre class="brush: csharp; title: ; notranslate">
protected virtual ImageNode CreateImageNodeTree(INode node)
{
    if (node == null)
        return null;

    ImageNode left = CreateImageNodeTree(node.Left);
    ImageNode right = CreateImageNodeTree(node.Right);
    ImageNode newNode = new ImageNode();
    newNode.Node = node;
    newNode.Left = left;
    newNode.Right = right;

    newNode.RightTreeWidth = (right == null) ? 0 : right.TotalWidth;
    newNode.LeftTreeWidth = (left == null) ? 0 : left.TotalWidth;
    newNode.TotalWidth = newNode.RightTreeWidth + newNode.LeftTreeWidth + NodeWidth + DX;

    return newNode;
}
</pre>
<p>So after that I have the right, left  and total width of every subtree. Then I can just start on the root node, draw that in the middle, then call my left child with my co-ordinates and that node will draw itself at parent.X &#8211; me.RightTreeWidth and the right node will draw itself at parent.X + me.LeftTreeWidth. And so it goes on recursively until all the nodes are drawn.</p>
<p>I&#8217;m maybe not so good at explaining it, but below you can see how it works. Just add a few nodes to the binary tree and you&#8217;ll see what happens. This is inside the blog template so as the image gets larger it might get clipped off by the sidebar or something, but you can also view the example at <a href="/binary-tree-image/">http://einaregilsson.com/binary-tree-image/</a>. You can also <a href="/download/BinaryTreeImage.cs.html">view the BinaryTreeImage class here</a> or <a href="/download/BinaryTreeImage.zip">download the example project</a> which includes the class, and the webpage to view it with. The code is released under the you-must-let-me-know license. Basically, do what you want with it, but let me know if you use it, just so I&#8217;ll know if anyone else finds it useful <img src='http://einaregilsson.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  .<br />
<script type="text/javascript" src="/binary-tree-image/js/BinaryTreeImage.js"></script></p>
<div style="text-align:center;">
<h3>Binary Tree Image Generator</h3>
<p>Enter a number between 1 and 100</p>
<input type="text" id="number" style="width:40px;" onkeypress="keyPress(event);"/>
&nbsp;&nbsp;<button onclick="addNode();" id="addNr">Add Number</button><br />
<img id="tree" src="/binary-tree-image/BinaryTreeImageGenerator.ashx?50" alt="Image of binary tree" style="margin:auto; border:dotted 1px grey; background:none; padding:0px; margin:10px;"/>
</div>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/binary-tree-image/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Run Windows Service as a console program</title>
		<link>http://einaregilsson.com/run-windows-service-as-a-console-program/</link>
		<comments>http://einaregilsson.com/run-windows-service-as-a-console-program/#comments</comments>
		<pubDate>Wed, 15 Aug 2007 17:01:27 +0000</pubDate>
		<dc:creator>einar</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Tips & Tricks]]></category>

		<guid isPermaLink="false">http://tech.einaregilsson.com/2007/08/15/run-windows-service-as-a-console-program/</guid>
		<description><![CDATA[Visual Studio and the .NET framework make it really easy to create Windows Services. All you have to do is create a new project, select &#8216;Windows Service&#8217; as your project type and you&#8217;re all set. However, debugging Windows Services in Visual Studio can be a big pain. The recommended way is to use InstallUtil to [...]]]></description>
			<content:encoded><![CDATA[<p>Visual Studio and the .NET framework make it really easy to create Windows Services. All you have to do is create a new project, select &#8216;Windows Service&#8217; as your project type and you&#8217;re all set. However, debugging Windows Services in Visual Studio can be a big pain. The recommended way is to use InstallUtil to install them, and then restart the service and attach the debugger everytime you want to debug it. I wanted <a href="/projects/windows-live-bot/">Windows Live! Bot</a> to be available as a Windows Service, but I also wanted to be able to debug it without the hassle, so here&#8217;s what I came up with: <span id="more-52"></span></p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.ServiceProcess;

public partial class DemoService : ServiceBase
{
    static void Main(string[] args)
    {
        DemoService service = new DemoService();

        if (Environment.UserInteractive)
        {
            service.OnStart(args);
            Console.WriteLine(&quot;Press any key to stop program&quot;);
            Console.Read();
            service.OnStop();
        }
        else
        {
            ServiceBase.Run(service);
        }

    }
    public DemoService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        // TODO: Add code here to start your service.
    }

    protected override void OnStop()
    {
        // TODO: Add code here to perform any tear-down
        //necessary to stop your service.
    }
}
</pre>
<p>This will allow you to use your program as either a normal console program or a windows service, with no special builds, #DEBUG directives, command line parameters or anything like that. What it does is in the Main method it checks the &#8216;Environment.UserInteractive&#8217; property. This will be true when it is run from Visual Studio, or when you just click on the .exe file, but false if it&#8217;s being run as a service. When it&#8217;s run from Visual Studio or as a standalone program it will keep running until you press a key, then it will call your OnStop method and then terminate.</p>
<p>Two things to watch out for:</p>
<ol>
<li>You&#8217;ll have to right click on your project in Visual Studio, choose Properties and select the Output type as &#8216;Console application&#8217; for this to work.</li>
<li>If your Main method is not in your service class, you&#8217;ll have to add public methods to your class that can start and stop it, for instance add a <strong>public void StartConsole(string[] args)</strong> that just calls your OnStart, since OnStart and OnStop are protected methods and as such not accessible from other classes.</li>
</ol>
<h3>UPDATE: 16.08.2007</h3>
<p>Reader <a href="http://theimes.com/">Anderson Imes</a> (who has a rather nice <a href="http://theimes.com/archive/2006/12/28/Debugging-Windows-Services-is-a-Pain.aspx">debugging solution of his own</a>) pointed out some things to fix. One thing is that a Windows Service can run many services in the same process, the ServiceBase.Run method can take an array of ServiceBase objects. I still think that the code above is the best way to do it if you have just a single service, just keep the Main method in the service class. But if you&#8217;ve got multiple service objects then that doesn&#8217;t make sense anymore, we want to put our Main method somewhere else. And then we have the problem of not being able to call OnStart in the service objects, since it&#8217;s a protected method. We could define a public StartConsole method in all of them that calls the OnStart method like I described above, but that will get tiresome if you have many objects. Well, there is another way to do it with Reflection which I´ve written here below. The new code is basically the same as the first version, except that it has an array of ServiceBase objects, called servicesToRun, and loops through it, calling each object&#8217;s OnStart method through some neat Reflection tricks. When the user presses a button it will stop all services by calling their Stop method, which in turn calls the OnStop method that all Services must define. </p>
<pre class="brush: csharp; title: ; notranslate">
using System.ServiceProcess;
using System;
using System.Reflection;

static class Program
{
    static void Main(string[] args)
    {
        ServiceBase[] servicesToRun = new ServiceBase[] { new Service1()
                                                        , new Service2()
                                                        , new Service3()};

        if (Environment.UserInteractive)
        {
            Type type = typeof(ServiceBase);
            BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
            MethodInfo method = type.GetMethod(&quot;OnStart&quot;, flags);

            foreach (ServiceBase service in servicesToRun)
            {
                method.Invoke(service, new object[] { args });
            }

            Console.WriteLine(&quot;Press any key to exit&quot;);
            Console.Read();

            foreach (ServiceBase service in servicesToRun)
            {
                service.Stop();
            }

        }
        else
        {
            ServiceBase.Run(servicesToRun);
        }
    }
}
</pre>
<p>While using this trick has worked perfectly well for my services, which have all been pretty simple, it might not work for everyone. I&#8217;m sure there are a few things different between Windows Services and console programs that I don&#8217;t know about, and might make the console version of the program behave strangely in some cases. Imes also pointed out that there was no way to test pause-and-resume in the console version. The best way I could think of to mimic service events like these would be to read in keypresses in the main thread and do the appropriate action depending on the key pressed. For instance, instead of the &#8220;Press any key to exit&#8221; message, we might have &#8220;Press p to pause, r to resume, s to stop&#8221; and then the result of Console.Read() could be used to determine which action to take and which methods to call on the Service objects. However, I don&#8217;t have the time and interest to do it right now, so implementing it is left as an exercise for the reader <img src='http://einaregilsson.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  .</p>
]]></content:encoded>
			<wfw:commentRss>http://einaregilsson.com/run-windows-service-as-a-console-program/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
	</channel>
</rss>

