<?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>James Gregory &#187; .Net</title>
	<atom:link href="http://jagregory.com/writings/category/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://jagregory.com</link>
	<description>Monkeying with the code</description>
	<lastBuildDate>Tue, 22 Jun 2010 11:07:25 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Preventing debugger property evaluation for side-effect laden properties</title>
		<link>http://jagregory.com/writings/preventing-debugger-property-evaluation-side-effects/</link>
		<comments>http://jagregory.com/writings/preventing-debugger-property-evaluation-side-effects/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 23:25:00 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[debugger]]></category>
		<category><![CDATA[fluent interface]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/?p=310</guid>
		<description><![CDATA[Property getters with side-effects, now there&#8217;s a controversial subject if ever I saw one. Don&#8217;t do it is the rule; as with any rule though, there&#8217;s generally an exception that proves it. If you&#8217;re in this situation and you genuinely do have a scenario that requires a property getter to have side-effects, then there&#8217;s a [...]]]></description>
			<content:encoded><![CDATA[<p>Property getters with side-effects, now there&#8217;s a controversial subject if ever I saw one. Don&#8217;t do it is the rule; as with any rule though, there&#8217;s generally an exception that proves it. If you&#8217;re in this situation and you genuinely do have a scenario that requires a property getter to have side-effects, then there&#8217;s a side-effect (ha!) that you should be aware of.</p>
<p><strong>The debugger evaluates property getters when showing it&#8217;s locals and autos windows.</strong> While this feature is indispensable in most cases, it plays havoc with our property-with-side-effects. What the debugger does is call the getter to present it&#8217;s value in the autos window, at the same time firing our code that has a side-effect. From there you have pretty confusing behavior with code seemingly running itself.</p>
<p>My exception to the rule is mutator properties in a fluent interface. You can often find properties in fluent interfaces that when touched alter the behavior of the next method called.</p>
<p>For example:</p>
<pre name="code" class="c-sharp">
string value = null;

Is.Null(value)      // returns true
Is.Not.Null(value)  // returns false
</pre>
<p>The Is class would contain a value tracking whether the next call would be inverted or not, and the Not property would flip that value when called.</p>
<p>Now assume this, you&#8217;re using <code>Is.Null(value)</code> and you set a breakpoint on it. Your autos window has expanded Is and shows the Not property, what&#8217;s just happened? The debugger has now called Not and altered your state! Undesirable.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsableattribute.aspx">DebuggerBrowsable attribute</a> to the rescue; this attribute when used with the DebuggerBrowsableState.Never parameter instructs Visual Studio to never inspect the property you apply it to. Your property won&#8217;t appear in the autos or locals window, and if you expand the tree of an instance containing the property it will show up with a Browsing Disabled message; you can then force it to evaluate the property, but at least it doesn&#8217;t do it automatically.</p>
<pre name="code" class="c-sharp">
private bool inverted = true;

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public Is Not
{
  get
  {
    inverted = !inverted;
    return this;
  }
}
</pre>
<p>Sticking the DebuggerBrowsable attribute on your Not property prevents the debugger from hitting it and inverting the switch.</p>
<p>So there you go, if your property-with-side-effects is being invoked by the debugger, you can use the DebuggerBrowsableAttribute to prevent it.</p>
<blockquote><p>By the way, I&#8217;m not advocating properties with side-effects&#8230;</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/preventing-debugger-property-evaluation-side-effects/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Git and command-line fear</title>
		<link>http://jagregory.com/writings/git-and-command-line-fear/</link>
		<comments>http://jagregory.com/writings/git-and-command-line-fear/#comments</comments>
		<pubDate>Mon, 20 Jul 2009 21:18:52 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[altdotnet]]></category>
		<category><![CDATA[Git]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/?p=304</guid>
		<description><![CDATA[Cross-posted to Los Techies

Git has been gaining a lot of traction lately, and rightly so. I&#8217;ve used it for a couple of years now, for all my projects (Fluent NHibernate and Docu being the prominent ones), but something that hasn&#8217;t changed is the tag-line of &#8220;but Windows support isn&#8217;t very good!&#8221;. What you quickly learn [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>Cross-posted to <a href="http://www.lostechies.com/blogs/jagregory/archive/2009/07/20/git-s-and-command-line-fear.aspx">Los Techies</a></p>
</blockquote>
<p><a href="http://git-scm.org">Git</a> has been gaining a lot of traction lately, and rightly so. I&#8217;ve used it for a couple of years now, for all my projects (<a href="http://fluentnhibernate.org">Fluent NHibernate</a> and <a href="http://docu.jagregory.com">Docu</a> being the prominent ones), but something that hasn&#8217;t changed is the tag-line of &#8220;but Windows support isn&#8217;t very good!&#8221;. What you quickly learn is that when people say that, they actually mean there isn&#8217;t a Visual Studio plug-in or some similar all-singing all-dancing GUI; this is a dire misrepresentation of Git, because it&#8217;s tooling on Windows is excellent if your definition of tooling includes the command-line.</p>
<p>It&#8217;s something ingrained in Windows developers, they hate the command-line. There&#8217;s a very good chance that if you encounter a Windows developer that does enjoy using the command-line it&#8217;s because they&#8217;ve also worked on another platform or in another environment that encourages command-line use (Rails is a good example). I&#8217;ve tried various ways of encouraging people to experiment, but very few work without being able to sit down and just show them something. It&#8217;s very much like R# adoption, nobody thinks it&#8217;ll speed them up until they see how fast someone else can be.</p>
<p>Back onto Git. If you don&#8217;t like what Git does, then that&#8217;s fine, but don&#8217;t label yourself as Alt.Net or a continuous improver if this sounds like you: &#8220;I define myself by choosing the best tool for each situation, but there&#8217;s no way you&#8217;ll get me using the command-line.&#8221; Way to go, oh open-minded one. Try it, you might like it.</p>
<p>The other techies have been posting some great <a href="http://www.lostechies.com/blogs/tags/git/default.aspx">Git posts</a> which can help you get up to speed. I hope to contribute, with less bile, soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/git-and-command-line-fear/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Introduction to static reflection</title>
		<link>http://jagregory.com/writings/introduction-to-static-reflection/</link>
		<comments>http://jagregory.com/writings/introduction-to-static-reflection/#comments</comments>
		<pubDate>Mon, 26 Jan 2009 23:34:41 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#3]]></category>
		<category><![CDATA[FluentInterface]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[StaticReflection]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/?p=232</guid>
		<description><![CDATA[This post could&#8217;ve also been called &#8220;Fluent NHibernate secrets exposed!&#8221; but it sounded a bit sensationalist.
You may have heard people mention static reflection recently, quite possibly because it&#8217;s used extensively in Fluent NHibernate, Rhino Mocks, and I believe Jimmy Bogard&#8217;s new AutoMapper also uses it; pretty much any of the new &#8220;fluent&#8221; interfaces use some [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>This post could&#8217;ve also been called &#8220;Fluent NHibernate secrets exposed!&#8221; but it sounded a bit sensationalist.</p></blockquote>
<p>You may have heard people mention static reflection recently, quite possibly because it&#8217;s used extensively in <a href='http://fluent-nhibernate.googlecode.com'>Fluent NHibernate</a>, <a href='http://ayende.com/projects/rhino-mocks.aspx'>Rhino Mocks</a>, and I believe <a href='http://www.lostechies.com/blogs/jimmy_bogard/'>Jimmy Bogard&#8217;s</a> new <a href='http://www.codeplex.com/AutoMapper'>AutoMapper</a> also uses it; pretty much any of the new &#8220;fluent&#8221; interfaces use some kind of static reflection.</p>
<p><strong>So what actually is static reflection?</strong> Well, it&#8217;s a statically compiled way of utilising the Reflection API.</p>
<p>Traditionally, if you wanted to use the Reflection API to interrogate your classes, you&#8217;d need to utilise strings to refer to properties and methods; this can make your design quite brittle, because you have to make sure these strings are kept up-to-date whenever you rename anything. What&#8217;s worse is that because reflection is late-bound, you aren&#8217;t aware of the problems until the code is actually executed, so this renaming could introduce hidden bugs that don&#8217;t appear until runtime. With the growing popularity of refactoring techniques, it&#8217;s becoming more important that we can use reflection without having to worry about this problem.</p>
<blockquote>
<p>It&#8217;s very true that tools like Resharper can certainly help with refactoring reflection-based code, but none of them are perfect and they only help the people that use them.</p>
</blockquote>
<p>In C# 3 we were introduced to lambda expressions and Linq, and with them came the <code>Func&lt;&gt;</code> and <code>Expression&lt;&gt;</code> classes; these are the key to static reflection. The <code>Func&lt;&gt;</code> set of classes allow you to use lambda expressions that return a value, while an <code>Expression&lt;&gt;</code> can be used to programatically access the contents of a delegate.</p>
<p>Combining <code>Func&lt;&gt;</code> and <code>Expression&lt;&gt;</code> can give us a very powerful way to statically retrieve <code>PropertyInfo</code> (and similar) instances from a lambda expression. For example <code>Expression&lt;Func&lt;Customer, object&gt;&gt;</code> represents an expression that contains a delegate that returns a value (of type object), with a <code>Customer</code> parameter; I&#8217;ll illustrate:</p>
<pre name="code" class="c-sharp">// method to receive an expression
public PropertyInfo GetProperty&lt;TEntity&gt;(Expression&lt;Func&lt;TEntity, object&gt;&gt; expression)

// usage
GetProperty&lt;Customer&gt;(customer =&gt; customer.Name);</pre>
<p>What this is actually doing is creating a lambda that returns a value, the value of <code>customer.Name</code> in this case. Here&#8217;s the trick, we don&#8217;t actually care about the value that&#8217;s returned! In-fact, we don&#8217;t even evaluate this expression at all.</p>
<blockquote>
<p>The reason we use <code>object</code> in the <code>Func</code> signature, rather than a more specific type, is because we want to allow <em>any</em> property to be used; however, if you were only interested in <code>string</code> properties, then you could restrict it by replacing this parameter.</p>
</blockquote>
<p>The <code>Expression</code> API itself is very in-depth, so I won&#8217;t go into the intricacies of it but here&#8217;s a very simple implementation of static reflection.</p>
<pre name="code" class="c-sharp">public PropertyInfo GetProperty&lt;TEntity&gt;(Expression&lt;Func&lt;TEntity, object&gt;&gt; expression)
{
  var memberExpression = expression.Body as MemberExpression;

  if (memberExpression == null)
    throw new InvalidOperationException(&quot;Not a member access.&quot;);

  return memberExpression.Member as PropertyInfo; // Should account for FieldInfo too
}</pre>
<p>Stepping through this code, we start by getting the body of the expression which we cast to a <code>MemberExpression</code>; this is us grabbing the <code>customer.Name</code> part of our expression. Now we can get the member itself and cast it to a <code>PropertyInfo</code>, this is the <code>Name</code> part of the expression body. That&#8217;s it! We&#8217;ve not evaluated the expression, but we&#8217;ve inspected it and retrieved the property.</p>
<blockquote>
<p>This example is for illustrative purposes, there are many different types of expressions which would be excluded by this. If you are to implement your own static reflection parser, you should cater for these other types of expressions.</p>
</blockquote>
<p>As this example shows, we&#8217;re able to use reflection without having to resort to strings. The great thing about this is that if you change the name of a member inside a lambda, you&#8217;ll get a compile error if you haven&#8217;t updated all the references! No more hidden bugs.</p>
<p>So that&#8217;s how the magic behind Fluent NHibernate (and others) works, simple when you know how!</p>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/introduction-to-static-reflection/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>The VB OSS debarkle</title>
		<link>http://jagregory.com/writings/the-vb-oss-debarkle/</link>
		<comments>http://jagregory.com/writings/the-vb-oss-debarkle/#comments</comments>
		<pubDate>Thu, 08 Jan 2009 09:28:01 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[rant]]></category>
		<category><![CDATA[vb]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/?p=180</guid>
		<description><![CDATA[Following a discussion last night between myself, several others, and Roy Osherove, which Jeremy Miller also commented on.
The problem was incorrectly stated. There isn&#8217;t a lack of OSS projects that VB programmers can use, there&#8217;s a wealth of projects out there. I&#8217;ve personally used IoC containers, ORM tools, unit testing tools, and build automation tools [...]]]></description>
			<content:encoded><![CDATA[<p>Following a discussion last night between myself, several others, and Roy Osherove, which Jeremy Miller <a href="http://codebetter.com/blogs/jeremy.miller/archive/2009/01/07/a-challenge-to-the-vb-net-community-at-large-on-oss.aspx">also commented on</a>.</p>
<p>The problem was incorrectly stated. There isn&#8217;t a lack of OSS projects that VB programmers can use, there&#8217;s a wealth of projects out there. <em>I&#8217;ve personally used IoC containers, ORM tools, unit testing tools, and build automation tools in VB with my most recent employer.</em> The issue is that more recent projects are using some language features of C# that the VB team hasn&#8217;t chose to implement. This has got Roy all up in arms because he feels that should be our problem (as the OSS developers).</p>
<blockquote><p><strong>On a side note</strong>, it was also mentioned that there are few VB OSS developers because they don&#8217;t have anything to cut their teeth on. Chicken and the egg, no VB OSS projects means no VB OSS developers.</p>
<p>The fact that there are plenty of OSS projects out there that VBers can use kinda makes the argument that VB developers don&#8217;t contribute to OSS because they don&#8217;t have anything to start with redundant; the whole chicken and the egg argument is flawed because OSS is already out there. It has been out there for years and yet there are still precious little contributions from VB developers.</p>
</blockquote>
<p>I think it all stems from a funny situation we&#8217;ve got ourselves into, one of unfounded expectations. C# and VB have always been pretty much the same language, just with different syntax. Everything you could do in C# you could do in VB. That&#8217;s no longer the case from .Net 3.5 onwards; however, it was only ever the case by coincidence due to their base in the CLI. If the CLI was never involved, they&#8217;d never have travelled the same path. When you take a step back and look at them for what they are, two completely distinct languages, this expectation for crossover appears less reasonable. I wouldn&#8217;t expect a Ruby developer to complain that they can&#8217;t use my C# project, so why should a VBer complain? VB is just as different a language as Ruby is to C#.</p>
<ul>
<li>If you want a framework for Ruby, you&#8217;d pick a Ruby framework.</li>
<li>If you want a framework for C#, you&#8217;d pick a C# framework.</li>
<li>So why if you want a framework for VB, do you pick a C# framework?</li>
</ul>
<blockquote><p>Regarding the conversation&#8230;
<p><strong>To those VB developers who responded with conspiracy:</strong> there is no conspiracy. Nobody is developing with C# out of spite, we do it because it&#8217;s our preferred language; nobody would accuse you of being spiteful if you chose to develop in VB, so don&#8217;t accuse us of doing it.</p>
<p><strong>To those VB developers that think we choose C# because it&#8217;s the &#8220;flavour of the week&#8221; </strong>versus the old workhorse of VB: that just shows how far behind you really are; if you genuinely believe the C# developers think it is en-vogue, then you&#8217;re sorely mistaken. I don&#8217;t think I know any C# developers that actually think C# is really awesome, just that it&#8217;s their preferred of the two .Net languages.</p>
</blockquote>
<p>I can&#8217;t believe I fell for a C# vs. VB argument.</p>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/the-vb-oss-debarkle/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>YaYAML: Yet another YAML parser</title>
		<link>http://jagregory.com/writings/yayaml-yet-another-yaml-parser/</link>
		<comments>http://jagregory.com/writings/yayaml-yet-another-yaml-parser/#comments</comments>
		<pubDate>Tue, 28 Oct 2008 22:07:02 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Hobby Projects]]></category>
		<category><![CDATA[OMeta]]></category>
		<category><![CDATA[Parsers]]></category>
		<category><![CDATA[YAML]]></category>
		<category><![CDATA[YaYAML]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/?p=145</guid>
		<description><![CDATA[I don&#8217;t want to make much ceremony around this, but I thought I&#8217;d mention it incase anybody else is interested.
As a part of a project I&#8217;m working on I needed a simple file to store some data in, and I didn&#8217;t want it to be XML (for no reason other than the verbosity). I could [...]]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t want to make much ceremony around this, but I thought I&#8217;d mention it incase anybody else is interested.</p>
<p>As a part of a project I&#8217;m working on I needed a simple file to store some data in, and I didn&#8217;t want it to be XML (for no reason other than the verbosity). I could have used my own format, but instead I&#8217;ve gone for <a href="http://yaml.net">YAML</a>. If you&#8217;ve worked with Ruby on Rails at all, then you&#8217;ll be familiar with YAML. It&#8217;s a human readable (and writable) text format.</p>
<p>Of course, I still needed to be able to parse my YAML document. There was a project announced 2 years ago to create a .Net parser, but like many things, it seems very much abandoned. So, after my <a href="http://blog.jagregory.com/2008/10/22/getting-started-with-ometa/">recent adventure with OMeta#</a>, I thought I&#8217;d hack on this too.</p>
<p><strong>Introducing YaYAML: Yet another YAML parser.</strong></p>
<p>Don&#8217;t get your hopes up, I&#8217;ve only implemented exactly what I needed out of the spec, which is very little indeed. However, it&#8217;s something I will carry on with when time permits. So what can you parse with YaYAML? Only documents containing a single flat sequence or mapping. <strong>No nesting, no multiple documents in a file, no variables.</strong></p>
<p>It&#8217;s possible to parse these two example files:</p>
<pre>
- a list
- of text
- strings
</pre>
<pre>
a: mapping
of: various
key: and
value: pairs
</pre>
<p>That&#8217;s it!</p>
<p>You can find the source in my <a href="http://github.com/jagregory/yayaml">YaYAML github repository</a>.</p>
<p><strong>Update:</strong><br />
I&#8217;ve since added support for sequences of maps, so this is supported too:</p>
<pre>
- name: James
  age: 23
- name: Peter
  age: 34
</pre>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/yayaml-yet-another-yaml-parser/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting started with OMeta#</title>
		<link>http://jagregory.com/writings/getting-started-with-ometa/</link>
		<comments>http://jagregory.com/writings/getting-started-with-ometa/#comments</comments>
		<pubDate>Wed, 22 Oct 2008 00:22:50 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[OMeta]]></category>
		<category><![CDATA[SharpDiff]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/?p=130</guid>
		<description><![CDATA[Notice: I&#8217;m a novice at OMeta, and as such, you shouldn&#8217;t take my advice as best-practice. This is based on my exploratory findings.
String parsing is hard. I don&#8217;t think anyone will deny that. You can parse it by hand, you can use regular expressions, you can walk it character by character. With SharpDiff, I needed [...]]]></description>
			<content:encoded><![CDATA[<p><em><strong>Notice:</strong> I&#8217;m a novice at OMeta, and as such, you shouldn&#8217;t take my advice as best-practice. This is based on my exploratory findings.</em></p>
<p>String parsing is hard. I don&#8217;t think anyone will deny that. You can parse it by hand, you can use regular expressions, you can walk it character by character. With <a href="http://blog.jagregory.com/2008/10/19/sharpdiff-diff-parsing-in-net/">SharpDiff</a>, I needed to parse some serious text, it was in an expected format, but there are numerous rules surrounding it. I did not fancy parsing it by hand, or with regular expressions.</p>
<p>I considered writing a parser for it, but dismissed that after my dealings with <a href="http://www.antlr.org">ANTLR</a> in <a href="http://www.codeplex.com/BooLangStudio">BooLangStudio</a>. It&#8217;s not so much that ANTLR is bad, it&#8217;s just long winded; it&#8217;s completely <a href="http://en.wikipedia.org/wiki/Visitor_pattern" title="Visitor Pattern">visitor</a>tastic.</p>
<p>Anyway, after 10 minutes down the path of parsing it myself, I cracked and decided to look into alternatives to ANTLR. I came across <a href="http://www.codeplex.com/ometasharp">OMeta#</a> and (with a reassuring nudge by Jeffery Olson) I went with it.</p>
<h3>So what is OMeta#?</h3>
<p>At it&#8217;s heart, <a href="http://www.cs.ucla.edu/~awarth/ometa/">OMeta</a> is just a really great string parser, and OMeta# is a .Net implementation of it. Combine that with a fairly decent definition language and codegen&#8217;d parser creation, and you&#8217;re onto a winner.</p>
<p>It allows you to write a syntax grammar and parse content with it, without having to worry about lexing, tokenizing and all that jazz. You only need to learn one language, OMeta.</p>
<p>While working on SharpDiff, I took a detour and implemented another very simple Git diff format. It&#8217;s a stat/metrics diff that just tells you which files have changed, and how many additions and removals have occurred in each. A pretty straight forward diff crying out to be used as an example.</p>
<h3>A basic OMeta-based parser</h3>
<p>Git has a diff format called stat (and it&#8217;s counter-part numstat, that we&#8217;ll be using). It produces output like so:</p>
<pre>1    0    myFile.txt
3    1    anotherFile.txt</pre>
<blockquote><p>If you&#8217;re following along at home, you&#8217;ll need to create yourself a new git repository. In there place a couple of text files, add some content to them and commit them. Then make some changes to those files, but don&#8217;t commit that. Now you can execute <code>git --numstat</code> to get the above output.</p></blockquote>
<p>The Git documentation is a wonderful thing, and it provides us with a nice outline of the numstat output.</p>
<blockquote><pre>1    2    README
3    1    arch/{i386 => x86}/Makefile</pre>
<p>That is, from left to right:</p>
<ol>
<li>the number of added lines;</li>
<li>a tab;</li>
<li>the number of deleted lines;</li>
<li>a tab;</li>
<li>pathname (possibly with rename/copy information);</li>
<li>a newline.</li>
</ol>
</blockquote>
<p>Before we get to the meat, there&#8217;s a couple of things we need to do. Firstly, (at the time of writing) there are no binaries available for OMeta#, so you&#8217;ll have to download the source and compile yourself. Once you&#8217;ve done that, you need to reference the OMetaSharp.dll and OMetaSharp.OMetaCS.dll.</p>
<p>Due to OMeta codegening our parser, it really needs to be built separately to our main project. If we don&#8217;t do that, we could get ourselves in a mess when we write an invalid grammar and generate some uncompiling code from it.</p>
<p>I won&#8217;t go over how to do this, but basically wrap the following code in a separate console app, changing the paths to point to where your code actually lives.</p>
<pre name="code" class="c-sharp">public void RebuildGitNumstatParser()
{
  var contents = File.ReadAllText(@&quot;..\..\..\SharpDiff\Parsers\GitNumstatParser.ometacs&quot;);
  var result = Grammars.ParseGrammarThenOptimizeThenTranslate
    &lt;OMetaParser, OMetaOptimizer, OMetaTranslator&gt;
    (contents,
     p =&gt; p.Grammar,
     o =&gt; o.OptimizeGrammar,
     t =&gt; t.Trans);

  File.WriteAllText(@&quot;..\..\..\SharpDiff\Parsers\GitNumstatParser.cs&quot;, result);
}</pre>
<p>That just gets OMeta to compile our grammar, then spit out a C# file.</p>
<p>One more thing, then we can get going. For this generation to work, we really need to give it a grammar and parser to begin with. So we&#8217;ll create an empty grammar and parser.</p>
<pre name="code" class="c-sharp">using OMetaSharp;

ometa GitNumstatParser : Parser {
}</pre>
<pre name="code" class="c-sharp">public class GitNumstatParser : Parser
{
}</pre>
<p>Now we can begin! One of the wonderful things about OMeta# is that it can be test driven very easily, which really surprised me.</p>
<p>So lets create our first test!</p>
<pre name="code" class="c-sharp">[Test]
public void ParsesNumber()
{
    var result = Parse&lt;int&gt;(&quot;1&quot;, x => x.Number);

    Assert.That(result, Is.EqualTo(1));
}</pre>
<p>In this test, we pass the Parse function a generic type parameter (int) which is our expected return type, then a string and an expression. The string is our input content, and the expression is the grammar rule to use for parsing.</p>
<p>I&#8217;m also using a shortcut method for parsing, which you can see below:</p>
<pre name="code" class="c-sharp">protected T Parse&lt;T&gt;(string text, Func&lt;GitNumstatParser, Rule&lt;char&gt;&gt; ruleFetcher)
{
    return Grammars.ParseWith(text, ruleFetcher).As&lt;T&gt;();
}</pre>
<p>When you run this test, it should pass. We didn&#8217;t do anything, I hear you say. That&#8217;s because we didn&#8217;t have to in this case. OMeta# comes with a few predefined rules that you can sometimes take advantage of (or override to give different meaning in your grammar). In this case, we&#8217;ve used the Number rule, which parses a string and returns an integer from it.</p>
<p>Onto the next test.</p>
<pre name="code" class="c-sharp">[Test]
public void ParsesAdditionsAndSubtractionValues()
{
    var result = Parse&lt;FileStats&gt;(&quot;3\t8\tmyFile.txt\r\n&quot;, x =&gt; x.Number);

    Assert.That(result.Additions, Is.EqualTo(3));
    Assert.That(result.Subtractions, Is.EqualTo(8));
}</pre>
<p>We need a class to represent our file statistics, I&#8217;ve created one called FileStats.</p>
<pre name="code" class="c-sharp">public class FileStats
{
  public FileStats(int additions, int subtractions)
  {
    Additions = additions;
    Subtractions = subtractions;
  }

  public int Additions { get; private set; }
  public int Subtractions { get; private set; }
}</pre>
<p>When you run this test, it will fail (and at the time of writing, fail with a nasty unhelpful OMeta exception). This is because we&#8217;re still trying to use the Number rule, so we need to create our FileStats rule.</p>
<p>Open up your ometacs file and follow along.</p>
<pre name="code" class="c-sharp">using SharpDiff.FileStructure.Numstat;
using OMetaSharp;

ometa GitNumstatParser : Parser {
  FileStats = Number:adds '\t' Number:subs
    -&gt; { new FileStats(adds.As&lt;int&gt;(), subs.As&lt;int&gt;()) }
}</pre>
<p>Right, that&#8217;s a bit of an overload, so lets go through it.</p>
<p>The line is made up from three parts:</p>
<ol>
<li>Rule name</li>
<li>Pattern to match</li>
<li>Code to produce</li>
</ol>
<p>For this line, we&#8217;re creating a rule called <code>FileStats</code>, which matches the <code>Number:adds '\t' Number:subs</code> pattern, and produces the code <code>new FileStats(adds.As&lt;int&gt;(), subs.As&lt;int&gt;())</code>.</p>
<p>Lets examine what the pattern is doing. Firstly, we&#8217;re using the Number rule that we used in our first test. The colon denotes an assignment to a variable, so we&#8217;re getting the match from the Number rule and putting that in an <code>adds</code> variable. We then match a single tab character (&#8216;\t&#8217;), and then another Number. Whitespace is ignored in the OMeta grammar, which means you can structure the file pretty much however you like.</p>
<p>Our pattern gives us two variables, adds and subs, we need to do something with them. The <code>-&gt;</code> operator designates the next curly brace surrounded region to be your desired C# code output. For this rule, we&#8217;re creating a new instance of our FileStats class, and passing our two variables into the constructor (converting them to ints at the same time).</p>
<p>At this point, run your side executable that recreates the generated parser. You should now be able to alter your test to use the FileStats rule instead of Number, and have it pass.</p>
<p>So what can we parse now? We&#8217;re able to get the additions and subtractions from a line such as <code>1    4    myFile.txt</code>.</p>
<p>We still need to be able to get the filename back though, so onto our next test.</p>
<pre name="code" class="c-sharp">[Test]
public void ParsesFilename()
{
  var result = Parse&lt;string&gt;(&quot;anotherFile.txt&quot;, x =&gt; x.Filename);

  Assert.That(result, Is.EqualTo(&quot;anotherFile.txt&quot;));
}</pre>
<p>This test won&#8217;t compile until we create our Filename rule, so off to the ometacs with us!</p>
<pre name="code" class="c-sharp">using SharpDiff.FileStructure.Numstat;
using OMetaSharp;

ometa GitNumstatParser : Parser {
  FileStats = Number:adds '\t' Number:subs
    -&gt; { new FileStats(adds.As&lt;int&gt;(), subs.As&lt;int&gt;()) },
  Filename = LetterOrDigit+:name '.' LetterOrDigit+:ext
    -&gt; { name.As&lt;string&gt;() + "." + ext.As&lt;string&gt;() }
}</pre>
<p>We&#8217;ve now got an extra rule at the end of the file, Filename. I can&#8217;t stress this enough, <strong>watch your commas</strong>; OMeta#s errors are poor, and something like that can trip you up.</p>
<p>Our new rule looks complex, but is pretty simple. It uses the built-in LetterOrDigit rule, which matches a single letter or digit. We suffix that call with a <code>+</code> which (like regex) matches one or more instances; that match is then stored in a <code>name</code> variable. Following that is a single full-stop. Finally, another LetterOrDigit+, which matches our extension. We then concatenate those strings in our C# output.</p>
<p>Again, recompile your parser. Now your test should pass. It simply matches any filename with an extension (room for improvement here!).</p>
<p>Now we can bring the two together, so we can parse a whole line. Next test!</p>
<pre name="code" class="c-sharp">[Test]
public void ParsesFullFileLine()
{
  var result = Parse&lt;FileStats&gt;(&quot;3\t8\tmyFile.txt\r\n&quot;, x =&gt; x.FileStats);

  Assert.That(result.Additions, Is.EqualTo(3));
  Assert.That(result.Subtractions, Is.EqualTo(8));
  Assert.That(result.Filename, Is.EqualTo(&quot;myFile.txt&quot;));
}</pre>
<p>We need to update our FileStats class so it supports the filename.</p>
<pre name="code" class="c-sharp">public class FileStats
{
  public FileStats(int additions, int subtractions, string filename)
  {
    Additions = additions;
    Subtractions = subtractions;
    Filename = filename;
  }

  public int Additions { get; private set; }
  public int Subtractions { get; private set; }
  public string Filename { get; private set; }
}</pre>
<p>Our grammar file is going to undergo a bit of refactoring too. We&#8217;re covered by tests, so why shouldn&#8217;t we? Our <code>FileStats</code> rule doesn&#8217;t really describe the whole line it should be matching. Really what we should have is a <code>LineStats</code> (that&#8217;s what our FileStats currently is) that just matches the numbers, then a FileStats that matches the numbers <strong>and</strong> the filename.</p>
<pre name="code" class="c-sharp">ometa GitNumstatParser : Parser {
  FileStats = LineStats:lines '\t' Filename:name NewLine
    -&gt; { new FileStats(
      lines[0].As&lt;int&gt;(),
      lines[1].As&lt;int&gt;(),
      name.As&lt;string&gt;()) },
  LineStats = Number:adds '\t' Number:subs
    -&gt; { adds, subs },
  Filename = LetterOrDigit+:name '.' LetterOrDigit+:ext
    -&gt; { name.As&lt;string&gt;() + &quot;.&quot; + ext.As&lt;string&gt;() },
  NewLine = '\r' '\n'
}</pre>
<p>So what we&#8217;ve done here is redo our FileStats rule as LineStats, which instead of creating an instance of the FileStats class, just returns an array of it&#8217;s two matches <code>{ adds, subs }</code>; this encapsulates that particular bit of behavior. Next we&#8217;ve created our new FileStats rule, which calls our LineStats rule and captures the matches. It then matches a single tab, and the filename using our Filename rule, followed by a NewLine; these are then combined and pushed into the constructor for our FileStats class. We&#8217;ve defined NewLine at the end, and it simply matches the \r\n characters.</p>
<p>Rebuilding and running that test should now give success. We&#8217;re now able to completely parse a diff line. Only one thing left to do, parse multiple lines together.</p>
<pre name="code" class="c-sharp">[Test]
public void CanParseMultipleLines()
{
  var result = ParseList&lt;FileStats&gt;(
    &quot;3\t8\tfile.txt\r\n&quot; +
    &quot;5\t1\tanotherFile.txt\r\n&quot;, x =&gt; x.FullFile);

  Assert.That(result.Count, Is.EqualTo(2));
  Assert.That(result[0].Filename, Is.EqualTo(&quot;file.txt&quot;));
  Assert.That(result[0].Additions, Is.EqualTo(3));
  Assert.That(result[0].Subtractions, Is.EqualTo(8));
  Assert.That(result[1].Filename, Is.EqualTo(&quot;anotherFile.txt&quot;));
  Assert.That(result[1].Additions, Is.EqualTo(5));
  Assert.That(result[1].Subtractions, Is.EqualTo(1));
}</pre>
<p>Our final test is a bit longer than the others, but it&#8217;s simple. We pass in some multiline input, and then assert that we have two FileStat objects, and that they&#8217;re correctly formed.</p>
<p>For this test we&#8217;re using another helper method, which returns a list of rule matches.</p>
<pre name="code" class="c-sharp">protected IList&lt;T&gt; ParseList&lt;T&gt;(string text, Func&lt;GitNumstatParser, Rule&lt;char&gt;&gt; ruleFetcher)
{
  return new List&lt;T&gt;(Grammars.ParseWith(text, ruleFetcher).ToIEnumerable&lt;T&gt;());
}</pre>
<p>Again, this test will fail because we haven&#8217;t defined the FullFile rule. So again to the ometacs file.</p>
<pre name="code" class="c-sharp">FullFile = FileStats+:files -&gt; { files },</pre>
<p>All we do this time is add this rule to the top, which uses the <code>+</code> operator to match multiple FileStats rules. They&#8217;re then returned as they are so we can convert them to an enumerable.</p>
<p>That&#8217;s it, recompile and run, you should now be parsing full diff outputs with ease!</p>
<p>As you can see OMeta# is pretty easy, and it&#8217;s very easy to test drive. There are a few quirks to doing it that way (such as having to create the compiled grammar before your test will run), but it&#8217;s a lot smoother than I expected. The grammars are quite simple too, and there are some shortcuts you can take which help make things easier. The SharpDiff grammar currently stands at just 49 lines, and it&#8217;s capable of parsing 90% of the standard git output, not bad!</p>
<p>I&#8217;ll just introduce you to another little bit of syntax that can make things simpler. Our Filename rule matches filenames with extensions, but it doesn&#8217;t match filenames without! That could be a problem; however, instead of creating a new rule for this, you can create multiple patterns for a rule. Each pattern will get evaluated if the one before it fails.</p>
<p>So we can update our Filename rule to the following, which tries to match a filename with an extension, and if it can&#8217;t do that, it then tries without an extension.</p>
<pre name="code" class="c-sharp">Filename = LetterOrDigit+:name '.' LetterOrDigit+:ext
  -&gt; { name.As&lt;string&gt;() + &quot;.&quot; + ext.As&lt;string&gt;() }
         | LetterOrDigit+:name
  -&gt; { name.As&lt;string&gt;() },</pre>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/getting-started-with-ometa/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>SharpDiff &#8211; Diff Parsing in .NET</title>
		<link>http://jagregory.com/writings/sharpdiff-diff-parsing-in-net/</link>
		<comments>http://jagregory.com/writings/sharpdiff-diff-parsing-in-net/#comments</comments>
		<pubDate>Sun, 19 Oct 2008 01:34:01 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Hobby Projects]]></category>
		<category><![CDATA[Diff]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[OMeta]]></category>
		<category><![CDATA[SharpDiff]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/?p=122</guid>
		<description><![CDATA[About SharpDiff
SharpDiff is a library for parsing the output of various diffing tools. It&#8217;s primary purpose is to reduce the time spent by SCM UI developers in handing diff output.
Why SharpDiff
I&#8217;ve got a few tools in mind that require parsing of diff files. I figure it&#8217;s a pretty common thing for SCM UI developers to [...]]]></description>
			<content:encoded><![CDATA[<h3>About SharpDiff</h3>
<p>SharpDiff is a library for parsing the output of various diffing tools. It&#8217;s primary purpose is to reduce the time spent by SCM UI developers in handing diff output.</p>
<h3>Why SharpDiff</h3>
<p>I&#8217;ve got a few tools in mind that require parsing of diff files. I figure it&#8217;s a pretty common thing for SCM UI developers to have to do, so I thought i&#8217;d put it out for others to use.</p>
<h3>Parsing your first diff</h3>
<p>The implementation is not concrete yet, but the current (easiest) way to parse a diff file is as follows.</p>
<p><script src="http://gist.github.com/17761.js"></script><br />
<noscript></p>
<pre>
string diffContent = File.ReadAllText("MyDiffFile.diff");

Diff diff = Diff.CreateFrom(diffContent);
</pre>
<p></noscript></p>
<p>From there you have a compiled version of your diff document. Intellisense will be your friend here, but basically you have a Chunks collection, and a Files collection.</p>
<p>The Wikipedia <a href="http://en.wikipedia.org/wiki/Diff">article on Diffs</a> is worth a read if you&#8217;re interested. In short though, chunks are formed as a chunk header containing the affected lines, and the lines themselves.</p>
<p><script src="http://gist.github.com/17762.js"></script><br />
<noscript></p>
<pre>
@@ -1,3 +1,6 @@
This is a small text file
+that I quite like,
 with a few lines of text
-inside, nothing much.
</pre>
<p></noscript></p>
<p>The chunk header is <strong>@@ -1,3 +1,6 @@</strong>. The -1,3 describes the affected lines in the original file, the first number (ignoring the minus) is the start line, and the second number is the total of context lines plus subtraction lines. The second range (+1,6) is in the new file, and that starts on the first line, and has six affected lines; in this case it&#8217;s all the context lines plus all addition lines.</p>
<p>All the other lines are the actual changes themselves. A line prefixed with a + is an addition line, a line prefixed with a &#8211; is a subtraction line, and lines prefixed with a space are context lines. Context lines are used for aligning the changes in the document. They&#8217;re also useful for determining if the document has changed since the diff was created.</p>
<p>In the context of SharpDiff, your Chunks collection contains an instance of a Chunk for every part in the diff that resembles the above. Each chunk has the range info for the original and new file, and a Lines collection of each line.</p>
<h3>Early Days</h3>
<p><strong>WARNING:</strong> SharpDiff is still in early development. I wouldn&#8217;t recommend using it in production code yet, as the parser is severely limited, and there&#8217;s next to no error handling.</p>
<p>The biggest flaw is that it only supports the standard git-diff output, and doesn&#8217;t handle many special circumstances.</p>
<p>It does support:</p>
<ul>
<li>Standard git-diff header</li>
<li>Index extended header</li>
<li>Chunk header</li>
<li>Chunk lines (added, removed, and contextual)</li>
<li>No newline at end of file</li>
<li>Multiple chunks per diff</li>
<li>Multiple diff per input string</li>
</ul>
<p>It doesn&#8217;t support:</p>
<ul>
<li>Other extended headers</li>
<li>Formats other than git-diff</li>
</ul>
<h3>Example</h3>
<p>As quick example of what you could use this library for, here&#8217;s a screenshot of a git-diff application:</p>
<p><a href="http://blog.jagregory.com/wp-content/uploads/2008/10/picture-6.png"><img src="http://blog.jagregory.com/wp-content/uploads/2008/10/picture-6-300x140.png" alt="" title="picture-6" width="300" height="140" class="alignnone size-medium wp-image-123" /></a></p>
<h3>Get Involved</h3>
<p>You can find the source on my github account, in the <a href="http://github.com/jagregory/sharpdiff/tree/master">sharpdiff repository</a>.</p>
<p>If you&#8217;re interested in helping with SharpDiff, then let me know. All comments, suggestions, and contributions are welcome. Feel free to contact me either through github, or my e-mail.</p>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/sharpdiff-diff-parsing-in-net/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Smart Indentation for Visual Studio Extensibility projects</title>
		<link>http://jagregory.com/writings/smart-indentation-for-visual-studio-extensibility-projects/</link>
		<comments>http://jagregory.com/writings/smart-indentation-for-visual-studio-extensibility-projects/#comments</comments>
		<pubDate>Sun, 19 Oct 2008 00:20:28 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Boo]]></category>
		<category><![CDATA[BooLangStudio]]></category>
		<category><![CDATA[Visual Studio Extensibility]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/?p=112</guid>
		<description><![CDATA[I said previously in my Brace Matching post that I want to try to document some of my findings while working on BooLangStudio. Well this is my second post on the subject.
When you&#8217;re implementing a custom language in Visual Studio, there&#8217;s a very good chance that you&#8217;re going to want to handle indentation slightly differently [...]]]></description>
			<content:encoded><![CDATA[<p>I said previously in my <a href="http://blog.jagregory.com/2008/09/02/brace-matching-and-your-language-service/">Brace Matching post</a> that I want to try to document some of my findings while working on <a href="http://www.codeplex.com/BooLangStudio/Thread/List.aspx">BooLangStudio</a>. Well this is my second post on the subject.</p>
<p>When you&#8217;re implementing a custom language in Visual Studio, there&#8217;s a very good chance that you&#8217;re going to want to handle indentation slightly differently to the defaults. Every language has it&#8217;s own rules, after all.</p>
<p>Most of the resources I found online we&#8217;re pretty poor for how to get this working. Most people we&#8217;re pointing to overriding <code>OnCommand</code> in your derived <code>Source</code> class, or implementing some interop interface (i.e. <code>IVsLanguageLineIndent</code>). I could get none of these working. <code>OnCommand</code> never got raised, and the interfaces we&#8217;re useless.</p>
<p>I tried a few different methods for handling indentation, but none of them worked very well. I tried capturing the enter key press, but that didn&#8217;t work. Then I tried capturing alterations to the document, but those also got fired for navigating the document, so you&#8217;d press the up key and add a new line!</p>
<p>It ended up being pretty simple to implement, once I finally found the correct way to do it. I&#8217;ll cover how I did this for BooLangStudio below.</p>
<p>In your <code>LanguageService</code>, there&#8217;s a method you can override called <code>CreateViewFilter</code> which sets everything in motion.</p>
<p>Create yourself a class that derives from <code>ViewFilter</code>, and then return an instance of it from the overridden <code>CreateViewFilter</code> method in your language service.</p>
<p><script src="http://gist.github.com/17751.js"></script></p>
<blockquote><p><strong>Note:</strong> You need to make sure your project is configured to use Smart Indentation. If your project is complete enough to allow the user to customise this, then you&#8217;re fine. However, if not you can hard code this value yourself. In your language service there&#8217;s a <code>GetLanguagePreferences</code> method that returns all the preferences for your project. In that method you can set <code>languagePreferences.IndentStyle = IdentingStyle.Smart</code>, which is what I&#8217;ve done in BooLangStudio.</p></blockquote>
<p>You&#8217;ll kick yourself for how easy this is. Now override the <code>HandleSmartIndent</code> method in your derived <code>ViewFilter</code>. That&#8217;s it really, in there you can access the <code>Source</code> object and do as you wish with smart indentation.</p>
<p>Taking BooLangStudio as an example, you can see in our <a href="http://github.com/jagregory/boolangstudio/tree/443929113ca77ae3c4613691f06f043f9d8f8d77/Source/BooLangService/BooViewFilter.cs">BooViewFilter.cs</a> that I delegate the work to a <code>HandleSmartIndentAction</code>. This is to make testing easier by having as little dependencies on Visual Studio as possible.</p>
<p>The <code>Execute</code> method of our <a href="http://github.com/jagregory/boolangstudio/tree/443929113ca77ae3c4613691f06f043f9d8f8d77/Source/BooLangService/HandleSmartIndentAction.cs">HandleSmartIndentAction.cs</a> class gets the caret location and passes it to an instance of a <a href="http://github.com/jagregory/boolangstudio/tree/443929113ca77ae3c4613691f06f043f9d8f8d77/Source/BooLangService/LineIndenter.cs">LineIndenter</a> class, which determines (based on the previous line to the caret) whether the next line should be indented, or outdented.</p>
<p><script src="http://gist.github.com/17754.js"></script></p>
<p>So that&#8217;s how to implement Smart Indentation in your Visual Studio Extensibility project, and a little bit of implementation details of BooLangStudio.</p>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/smart-indentation-for-visual-studio-extensibility-projects/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Console colours wrapper</title>
		<link>http://jagregory.com/writings/console-colours-wrapper/</link>
		<comments>http://jagregory.com/writings/console-colours-wrapper/#comments</comments>
		<pubDate>Tue, 07 Oct 2008 19:56:04 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Nuggets]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/?p=109</guid>
		<description><![CDATA[Continuing on from my post about an alternative syntax for the non-disposable using statements, here&#8217;s a class I&#8217;ve been using lately. It serves as a wrapper around changing the colours in a console window. It&#8217;s not a difficult thing to do, it&#8217;s just a bit awkward because you have to maintain the original colour in [...]]]></description>
			<content:encoded><![CDATA[<p>Continuing on from my post about an <a href="http://blog.jagregory.com/2008/10/07/alternative-to-abusing-using/">alternative syntax for the non-disposable using statements</a>, here&#8217;s a class I&#8217;ve been using lately. It serves as a wrapper around changing the colours in a console window. It&#8217;s not a difficult thing to do, it&#8217;s just a bit awkward because you have to maintain the original colour in a variable while you do your business.</p>
<pre name="code" class="c-sharp">
Console.WriteLine("Start...")

var originalColour = Console.ForegroundColor;
Console.ForegroundColour = ConsoleColor.Red;

Console.WriteLine("WARNING!");

Console.ForegroundColour = originalColour;
</pre>
<p>It&#8217;s not too bad when you&#8217;re only doing it once, but when you start swapping colours all over the place, then it can become very noisy. So this is where my class comes into play. Using the same syntax I described in my previous post, I&#8217;ve wrapped up the colour changing in a helper method that takes an Action delegate. This allows you to write much more intention revealing code.</p>
<pre name="code" class="c-sharp">
ConsoleColours.Foreground(ConsoleColor.Yellow, () =>
{
  Console.WriteLine("Different text");
});
</pre>
<p>I find this much cleaner and the blocks gives my console code some much needed separation.</p>
<p>Here&#8217;s the full class code:</p>
<pre name="code" class="c-sharp">
public class ConsoleColours
{
  public static void Foreground(ConsoleColor colour, Action action)
  {
    var original = Console.ForegroundColor;
    Console.ForegroundColor = colour;

    action();

    Console.ForegroundColor = original;
  }

  public static void Background(ConsoleColor colour, Action action)
  {
    var original = Console.BackgroundColor;
    Console.BackgroundColor = colour;

    action();

    Console.BackgroundColor = original;
  }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/console-colours-wrapper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Alternative to abusing using</title>
		<link>http://jagregory.com/writings/alternative-to-abusing-using/</link>
		<comments>http://jagregory.com/writings/alternative-to-abusing-using/#comments</comments>
		<pubDate>Tue, 07 Oct 2008 19:26:24 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Nuggets]]></category>
		<category><![CDATA[Opinion]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/?p=107</guid>
		<description><![CDATA[There&#8217;s been a bit of discussion of late about using statements, and how they&#8217;re more often being used for purposes other than just releasing resources. As always, there are those people who think it&#8217;s a flagrant abuse of a feature and shouldn&#8217;t be done, then there are those that like it. I&#8217;m in between. I [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s been a bit of discussion of late about using statements, and how they&#8217;re more often being used for purposes other than just releasing resources. As always, there are those people who think it&#8217;s a flagrant abuse of a feature and shouldn&#8217;t be done, then there are those that like it. I&#8217;m in between. I do like what the using statement gives us, but I also think it is a bit of an abuse.</p>
<p>The &#8220;traditional&#8221; usage of the using statement can be found quite often in the land of files and streams. Take the following example, which opens a file and then closes it when it drops out of the using scope.</p>
<pre name="code" class="c-sharp">
using (var stream = File.OpenRead("myFile.txt"))
{
  // do something with the file
}
</pre>
<p>Examples of the alternative usage can be found all over the place, but Rhino Mocks is one that&#8217;s close to my heart. Here&#8217;s from the record/replay syntax, anything in the scope of the using is recorded, and once it drops out of scope it&#8217;s no longer in record mode.</p>
<pre name="code" class="c-sharp">
using (mocks.Record())
{
  Expect.Call(customer.Address)
    .Return("123 Rester St");
}
</pre>
<p>Again, I do like what the using statement gives us outside of releasing resources (I&#8217;m not disputing it&#8217;s usefulness there). However, I think the using keyword itself adds noise and clouds intention.</p>
<p>With the adoption of 3.5, I&#8217;ve started using an alternative syntax instead of usings. Actions and anonymous methods to the rescue.</p>
<pre name="code" class="c-sharp">
Scope(() =>
{
  // do something within this scope
});
</pre>
<p>It&#8217;s a little bit more noisy in the compiler satisfying department, but because you have full control over naming, you can reveal intention more. No more unclear &#8220;using&#8221;.</p>
<p>So how does it work? Simple really, the method takes an Action delegate, which it the executes almost immediately. I say almost, because you can execute code before and after the execution. That gives you the benefits of the using statements wrapping ability.</p>
<pre name="code" class="c-sharp">
public void Scope(Action action)
{
  // do something before
  action();
  // do something after
}
</pre>
<p>Some more examples:</p>
<pre name="code" class="c-sharp">
File.OpenRead("myFile.txt", file =>
{
  // do something with the file
});
</pre>
<pre name="code" class="c-sharp">
mocks.Record(() =>
{
  Expect.Call(customer.Address)
    .Return("123 Rester St");
});
</pre>
<p>I prefer this syntax over the using statement. Of course, it&#8217;s only valid for 3.5 projects.</p>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/alternative-to-abusing-using/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
