<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" version="2.0">

<channel>
	<title>Farblondzshet in Code</title>
	
	<link>http://matthewmanela.com</link>
	<description>The life and work of Matthew Manela</description>
	<lastBuildDate>Thu, 29 Dec 2011 00:46:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Farblondzshet" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="farblondzshet" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>A Monadic Pratt Parser</title>
		<link>http://matthewmanela.com/blog/a-monadic-pratt-parser/</link>
		<comments>http://matthewmanela.com/blog/a-monadic-pratt-parser/#comments</comments>
		<pubDate>Wed, 28 Dec 2011 23:56:43 +0000</pubDate>
		<dc:creator>Matthew</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Parsing]]></category>

		<guid isPermaLink="false">http://matthewmanela.com/?p=1025</guid>
		<description><![CDATA[Introduction I recently read Beautiful Code which contains articles from several well known programmers about the code they consider beautiful.  In Top Down Operator Precedence, Douglas Crockford discusses the Pratt Parser (named after Vaughan Pratt who wrote the paper on &#8230; <a href="http://matthewmanela.com/blog/a-monadic-pratt-parser/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>I recently read <a href="http://www.amazon.com/Beautiful-Code-Leading-Programmers-Practice/dp/0596510047" target="_blank">Beautiful Code</a> which contains articles from several well known programmers about the code they consider beautiful.  In <a href="http://javascript.crockford.com/tdop/tdop.html" target="_blank">Top Down Operator Precedence</a>, Douglas Crockford discusses the <a href="http://dl.acm.org/citation.cfm?id=512931">Pratt Parser</a> (named after <a href="http://boole.stanford.edu/pratt.html">Vaughan Pratt</a> who wrote the paper on it), also known as the Top Down Operator Precedence parser.  What makes this parsing technique interesting is that the syntax is defined in terms of tokens instead of grammar rules, an interesting way to define a language parser. As an example, Crockford defines the multiplication operator in terms of <strong>*</strong> token:</p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:5d41b430-0623-4678-ae87-613178b5a5ad" class="wlWriterSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: fsharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: false;  width: 644px; height: 112px;" style="width: 644px; height: 112px; overflow: auto;">symbol("*", 60).led = function (left) {
    this.first = left;
    this.second = expression(60);
    this.arity = "binary";
    return this;
};</pre>
<p>&nbsp;</p>
</div>
<p>A Pratt parser works by reading through a stream of tokens and finding a symbol defined for the current token.  The symbol definition above for the <strong>*</strong> token defines how to build an abstract syntax tree (AST) node for that part of the token stream. The rest of the parser is defined similarly with symbols and functions for each significant piece of syntax in your language. I could go on about just how a Pratt parser works but <a href="http://eli.thegreenplace.net/2010/01/02/top-down-operator-precedence-parsing/" target="_blank">someone beat me to it</a>.</p>
<p>After reading about Pratt parsing I attempted my own implementation. I use F# which is a wonderful functional language supporting imperative style programming with mutable state. However, I feel a bit dirty using mutable state in a functional programming language (blame the hidden Haskell programmer in me) so I added the restriction that I will create my Pratt Parser in a pure functional manner.</p>
<h2>Monads + Pratt?</h2>
<p>Being purely functional meant fully embracing immutability. I manage the parser state by making use of the state monad which I <a href="http://matthewmanela.com/blog/functional-stateful-program-in-f/">have discussed previously</a> which makes use of the computation expression feature in F#. This creates very clean looking code since the state is being passed along in the background which makes it very easy to string functions together.</p>
<p>To create the monadic Pratt parser I define a few key types which are used throughout the code: <strong>Symbol&lt;’ex&gt;</strong> and <strong>InputState&lt;’ex&gt;.</strong></p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:259e9a79-7080-4f07-a9d9-ab05fb1bd529" class="wlWriterSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: fsharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: false;  width: 848px; height: 498px;" style="width: 848px; height: 498px; overflow: auto;">// Parser states consists of 'a which is the return type of any given parser combinator
// and 'ex which is the user defined type of the AST they are building
type Parser&lt;'a, 'ex&gt; = StateMonad&lt;InputState&lt;'ex&gt;,'a&gt;

// A symbol is the core component of the Pratt Parser. You define how the parsing works
// by defining symbols for operators/tokens
and Symbol&lt;'ex&gt; =
    {
        name : string;
        led : Token -&gt; 'ex -&gt; Parser&lt;'ex,'ex&gt;;
        nud : Token -&gt; int -&gt; Parser&lt;'ex,'ex&gt;;
        lbp : int;
    }

// The state type for the parser. Maintains the list of input tokens, the current token,
// the current symbol and the user defined mapping of tokens to symbols
and InputState&lt;'ex&gt; =
    {
        tokens : seq&lt;Token&gt;;
        token : Token option;
        symbol : Symbol&lt;'ex&gt; option;
        symbolMap : Map&lt;string, Symbol&lt;'ex&gt;&gt;
    }</pre>
<p>&nbsp;</p>
</div>
<p>The <strong>InputState&lt;’ex&gt; </strong>type defines all the state that is passed between the functions of the parser. It contains:</p>
<ul>
<li>Tokens: The sequence of tokens received from the <a href="http://matthewmanela.com/blog/regex-based-lexer-with-f-2/">lexer</a></li>
<li>SymbolMap: The user defined mapping from a token’s name or value to a parser symbol.</li>
<li>Token:  The current token that the parser is on</li>
<li>Symbol: The corresponding symbol for the current token</li>
</ul>
<p>The <strong>Symbol&lt;’ex&gt; </strong>type contain the user defined logic for how to parse the pieces of the language.It contains:</p>
<ul>
<li>Name: The symbol name matches either a token’s name or value</li>
<li>Lbp: The left binding power of this symbol. Determines if it will grab the previous expression.</li>
<li>Nud: The function called when this symbol is executed with no arguments</li>
<li>Led: The function called when this symbol is executed with the previous expression’s result.</li>
</ul>
<p>To parse a program you define several symbols and add them to InputState’s initial SymbolMap. The nud and led functions in these symbols will build up pieces of an AST. For example, given an AST defined by the Expression type:</p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:d4c1bb15-47f1-467e-aa61-ef90b486c624" class="wlWriterSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: fsharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: false;  width: 940px; height: 245px;" style="width: 940px; height: 245px; overflow: auto;">type Expression =
    | Call of Expression * Expression list
    | Cond of Expression * Expression * Expression
    | Let of Expression * Expression
    | Fun of Expression * Expression list * Expression
    | Id of String
    | Int of int
    | Float of float
    | Bool of bool</pre>
<p>&nbsp;</p>
</div>
<p>Here is a symbol which describes how to build an identifier node using the <strong>Id </strong>data constructor:</p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:9c44f29c-d4d1-4835-870c-3e0e3a588b75" class="wlWriterSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: fsharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: false;  width: 848px; height: 498px;" style="width: 848px; height: 498px; overflow: auto;">// Error function for symbols that don't define led
let errorLed token left =
    parser {
        return! error token "Symbol does not take a left argument"
    }

// The nud function for id which returns an Expression type using the Id data constructor
let idNud token rbp =
    parser {
      return Id token.text
    };

// A symbol for identifiers. Defines a nud function but not a
// led function since identifiers don't consume neighboring tokens
let idSymbol =
    {
        name = "ID";
        lbp = 0;
        nud = idNud;
        led = errorLed;
    }</pre>
<p>&nbsp;</p>
</div>
<p>Most symbols will follow a similar pattern so I created several helper methods to create symbols and build up the symbol map. I won’t go into each here (you can read the <a href="https://github.com/mmanela/Flango" target="_blank">source code</a>) but they let you build the symbol map in a declarative way. For example, this is the definition of a symbol map for a simple language:</p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:baeab68d-b02a-4d32-b5c0-f1ddc098ac40" class="wlWriterSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: fsharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: false;  width: 876px; height: 639px;" style="width: 876px; height: 639px; overflow: auto;">let languageSymbolMap = Map.empty |&gt;  

                        // Add empty symbols
                        // Will error if called
                        addEmptySymbol ")" |&gt;
                        addEmptySymbol "THEN" |&gt;
                        addEmptySymbol "ELSE" |&gt;

                        // Simple literal values
                        addLiteralSymbol "INT" Int int |&gt;
                        addLiteralSymbol "FLOAT" Float double |&gt;
                        addLiteralSymbol "BOOL" Bool bool  |&gt;

                        // Binary right associative symbols
                        addInfixR "=" 10 neLed |&gt;
                        addInfixR "!=" 10 neLed |&gt;
                        addInfixR "&amp;&amp;" 30 andLed |&gt;
                        addInfixR "||" 30 orLed |&gt;

                        // Binary left associative symbols
                        addInfixL "&gt;" 40 gtLed |&gt;
                        addInfixL "&gt;=" 40 gteLed |&gt;
                        addInfixL "&lt;" 40 ltLed |&gt;
                        addInfixL "&lt;=" 40 lteLed |&gt;
                        addInfixL "+"  50 plusLed |&gt;
                        addInfixL "-" 50 minusLed |&gt;
                        addInfixL "*" 60 timesLed |&gt;
                        addInfixL "/" 60 divideLed |&gt;
                        addInfixL "^" 70 powerLed|&gt;

                        // Custom symbols
                        addSymbol eqSymbol |&gt;
                        addSymbol idSymbol |&gt;
                        addSymbol leftParenSymbol |&gt;
                        addSymbol letSymbol |&gt;
                        addSymbol funSymbol |&gt;
                        addSymbol ifSymbol |&gt;
                        addSymbol endSymbol</pre>
<p>&nbsp;</p>
</div>
<h2>Expression Parsing</h2>
<p>The heart of the Pratt parser is the expression parsing code which calls the led and nud methods defined on the symbols.  My implementation follows the method in <a href="http://javascript.crockford.com/tdop/tdop.html">Crockford’s</a> article very closely except that I use recursion instead of a loop and I extend the definition of the nud function to accept a right binding power.</p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:eddac124-4326-4352-b909-187a5b563105" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: fsharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: false;  width: 669px; height: 370px;" style="width: 669px; height: 370px; overflow: auto;">let rec leftBoundExpression rbp token symbol left =
    parser {
        if (rbp &lt; symbol.lbp) then
            do! advance()
            let! newLeft = symbol.led token left
            let! newToken, newSymbol = current()
            return! leftBoundExpression rbp newToken newSymbol newLeft
        else
            return left
    }

let expression rbp =
    parser {
        let! token, symbol = current()
        do!  advance()
        let! left = symbol.nud token rbp
        let! nextToken, nextSymbol = current()
        return! leftBoundExpression rbp nextToken nextSymbol left
    }</pre>
<p>&nbsp;</p>
</div>
<p>Adding the right binding power (rbp) parameter to the nud function makes it possible to parse a call expression like the ones found in Haskell or F#</p>
<blockquote><p>someFunction arg1 arg2 arg2</p></blockquote>
<p>To parse this expression the nud method for an <em>someFunction </em>must match the multiple expressions that come after it. This creates an issue since an identifier can be matched in two different ways: as a function call with arguments or as a stand alone identifier. We need to ensure the nud function for <em>arg1</em> doesn’t try to grab <em>arg2</em>. Passing the right binding power to the nud method solves this since the nud for <em>someFunction </em>can indicate that it wants the next expressions with a high binding power. Below is an updated version of the identifier method’s nud function demonstrating this:</p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:659850de-2352-4546-86b4-7ba627d9548a" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: fsharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: false;  width: 761px; height: 385px;" style="width: 761px; height: 385px; overflow: auto;">let idNud token rbp =
    parser {
        if rbp &lt; 90 then
            let! args = manyExpressions 90
            if args.Length &gt; 0
            then return Call (token, args)
            else return Id token.text
        else
            return Id token.text
    };</pre>
<p>&nbsp;</p>
</div>
<h2>Parser Combinators</h2>
<p>In the code above you may have noticed the call to <strong>manyExpressions</strong>. This function will match as many expressions as it can and then returns them in a list.</p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:4578d205-b522-4abf-aa86-bb4943b04455" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: fsharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: false;  width: 807px; height: 295px;" style="width: 807px; height: 295px; overflow: auto;">let rec manyExpressions rbp =
    parser {
        let! exp = expression rbp
        let! rest =  (manyExpressions rbp)
        return exp :: rest
    } &lt;|&gt; parser.Return []</pre>
<p>&nbsp;</p>
</div>
<p>What is interesting about this function is its base case. It will keep recursing trying to match expressions until it finds a symbol that does not define the nud method which causes the parser to return an error. This is where the <em>&lt;|&gt; parser.Return []</em> expression takes over.  The &lt;|&gt; symbol is a function defined on the state monad which combines two monads/parsers into one. This kind of function is called a <a href="http://en.wikipedia.org/wiki/Parser_combinator" target="_blank">parser combinator</a>. The first parser given to it will execute and if it eventually errors the parsing will backtrack until if finds an alternative (the right argument to &lt;|&gt;) or unwinds the stack completely and returns the error. In the code above the second parser is defined by  <em>parser.Return []</em>  which returns an empty list when the first parser errors.</p>
<p>Those familiar with the Haskell parser combinator library called <a href="http://www.haskell.org/haskellwiki/Parsec" target="_blank">Parsec</a> may recognize the &lt;|&gt; combinator. In Parsec it is a predictive combinator and will only try the second alternative if the first didn’t consume input. This differs from my implementation which will try the second alternative even if the the first expression consumed hundreds of tokens before it errored.</p>
<p>Parser combinators offer great power since they can be used to effectively provide infinite look-ahead. They make it easy to parse ambiguous language constructs. I only use them in a limited way but there is much room to expand them.</p>
<h2>Conclusion</h2>
<p>I wasn’t sure at first what a monadic Pratt Parser would look and feel like. However, I am very pleased with how clear and readable it is. The use of computation expressions in F# enabled a simple and concise syntax. The melding of Pratt parsing with parser combinators creates really expressive and powerful parsers. I am interested in exploring this further to see what issues and pitfalls this kind of parser design may have.</p>
<p>All the code for my monadic Pratt parser can be found on this <a href="https://github.com/mmanela/Flango" target="_blank">github page</a>. This repository also contains an implementation of a simple functional language which demonstrates using the parser. The key files to look at are:</p>
<ul>
<li><strong><a href="https://github.com/mmanela/Flango/blob/master/Flango/Parser.fs" target="_blank">Parser.fs</a></strong>– The code for the monadic Pratt parser</li>
<li><strong><a href="https://github.com/mmanela/Flango/blob/master/Flango/StateMonad.fs" target="_blank">StateMonad.fs</a></strong>– The state monad implementation the parser is built on</li>
<li><strong><a href="https://github.com/mmanela/Flango/blob/master/Flango/FlangoParserDefs.fs" target="_blank">FlangoParserDefs.fs</a></strong>– The definition of a simple language using the parser</li>
<li><a href="https://github.com/mmanela/Flango/blob/master/Flango/Lexer.fs" target="_blank"><strong>Lexer.fs</strong></a> – The code for a <a href="http://matthewmanela.com/blog/regex-based-lexer-with-f-2/" target="_blank">regex based lexer</a><!--EndFragment--></li>
<li><a href="https://github.com/mmanela/Flango/blob/master/Flango/FlangoLexDefs.fs" target="_blank"><strong>FlangoLexDefs.fs</strong></a> – The definition of the tokens for the simple language</li>
</ul>
<div id="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://matthewmanela.com/blog/writing-a-regular-expression-parser-in-haskell-part-1/" rel="bookmark" class="crp_title">Writing a Regular Expression parser in Haskell: Part 1</a></li><li><a href="http://matthewmanela.com/blog/regex-based-lexer-with-f-2/" rel="bookmark" class="crp_title">Regex based Lexer with F#</a></li><li><a href="http://matthewmanela.com/blog/writing-a-regular-expression-parser-in-haskell-part-2/" rel="bookmark" class="crp_title">Writing a Regular Expression parser in Haskell: Part 2</a></li></ul></div><img src="http://feeds.feedburner.com/~r/Farblondzshet/~4/2pDm6z1c1W4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://matthewmanela.com/blog/a-monadic-pratt-parser/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Chutzpah 1.3.0 Released</title>
		<link>http://matthewmanela.com/blog/chutzpah-1-3-0-released/</link>
		<comments>http://matthewmanela.com/blog/chutzpah-1-3-0-released/#comments</comments>
		<pubDate>Sat, 19 Nov 2011 22:17:14 +0000</pubDate>
		<dc:creator>Matthew</dc:creator>
				<category><![CDATA[Chutzpah]]></category>
		<category><![CDATA[Codeplex]]></category>
		<category><![CDATA[NuGet]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Visual Studio Gallery]]></category>

		<guid isPermaLink="false">http://matthewmanela.com/blog/chutzpah-1-3-0-released/</guid>
		<description><![CDATA[A new version of Chutzpah is now live on Visual Studio Gallery, CodePlex and now NuGet. This release contains the following changes: Features 1. Chutzpah is now able to run Jasmine tests in addition to QUnit. This was a large &#8230; <a href="http://matthewmanela.com/blog/chutzpah-1-3-0-released/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A new version of Chutzpah is now live on <a href="http://visualstudiogallery.msdn.microsoft.com/71a4e9bd-f660-448f-bd92-f5a65d39b7f0">Visual Studio Gallery</a>, <a href="http://chutzpah.codeplex.com/">CodePlex</a> and now <a href="http://nuget.org/List/Packages/Chutzpah">NuGet</a>.</p>
<p>This release contains the following changes:</p>
<h3>Features</h3>
<p>1. Chutzpah is now able to run <a href="http://pivotal.github.com/jasmine/" target="_blank">Jasmine</a> tests in addition to <a href="http://docs.jquery.com/QUnit" target="_blank">QUnit</a>. This was a large feature and new Chutzpah contributor Ben (Qube) did an amazing job with it.</p>
<p>2. Added a new configuration option to set the timeout on a test file. By default this value is 3000ms but there are many cases when you may have long running tests where you need this to be longer. You can now set this timeout from the command line:</p>
<pre class="brush: plain; gutter: false; toolbar: false;">chutzpah.console.exe /timeoutMilliseconds 5000 mytest.js</pre>
<p>You can also set this inside of Visual Studio using the newly added options menu. You can find this menu under Tools-&gt;Options-&gt;Chutzpah.</p>
<p><a href="http://matthewmanela.com/wp-content/uploads/2011/11/image.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://matthewmanela.com/wp-content/uploads/2011/11/image_thumb.png" width="644" height="376"></a></p>
<p>&nbsp;</p>
<h3></h3>
<h3>Bug Fixes</h3>
<p>1. Chutzpah now copies over the text fixtures that you set in your html test harness.</p>
<p>2. Added missing doctype on the generated test harness.</p>
<p>3. Fixed bug where multiple references to qunit.js were copied into the generated test harness.</p>
<div id="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://matthewmanela.com/blog/chutzpah-1-2-0-released/" rel="bookmark" class="crp_title">Chutzpah 1.2.0 Released</a></li><li><a href="http://matthewmanela.com/blog/chutzpah-1-1-0-released/" rel="bookmark" class="crp_title">Chutzpah 1.1.0 Released</a></li><li><a href="http://matthewmanela.com/blog/chutzpah-a-javascript-test-runner-released/" rel="bookmark" class="crp_title">Chutzpah &#8211; A JavaScript Test Runner Released</a></li></ul></div><img src="http://feeds.feedburner.com/~r/Farblondzshet/~4/Qyi1hB-kAEU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://matthewmanela.com/blog/chutzpah-1-3-0-released/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Moving and renaming resource keys in a .resx file</title>
		<link>http://matthewmanela.com/blog/moving-and-renaming-resource-keys-in-a-resx-file/</link>
		<comments>http://matthewmanela.com/blog/moving-and-renaming-resource-keys-in-a-resx-file/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 19:19:06 +0000</pubDate>
		<dc:creator>Matthew</dc:creator>
				<category><![CDATA[Localization]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://matthewmanela.com/?p=1396</guid>
		<description><![CDATA[I work on websites where we have several resource files that are localized in many languages. This makes operations like renaming a resource key and moving a resource key to a different file annoying since you must do it across &#8230; <a href="http://matthewmanela.com/blog/moving-and-renaming-resource-keys-in-a-resx-file/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I work on websites where we have several resource files that are localized in many languages. This makes operations like renaming a resource key and moving a resource key to a different file annoying since you must do it across several languages. To help with this I created a couple of PowerShell scripts to automate this process.</p>
<p>These PowerShell scripts assume your .resx files live in a folder named “Resources” but this can be easily changed.</p>
<h3>RenameResource.ps1</h3>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:65641c80-0288-41d6-851d-ccf0e99475ee" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: ps; gutter: true; first-line: 1; tab-size: 4;  toolbar: false;  width: 710px; height: 372px;" style="width: 710px; height: 372px; overflow: auto;">param([String]$keyOld, [String]$keyNew)
if(-not $keyOld -or -not $keyOld) {
  echo "RenameResource.ps1 keyOld keyNew"
  return
}

$files=get-childitem Resources *.resx

foreach($file in $files) {
  $xml = [xml](Get-Content $file.FullName)
  $dataNode = $xml.root.data | Where-Object { $_.GetAttribute("name") -eq $keyOld }
  if ($dataNode -ne $null) {
    $dataNode.SetAttribute("name", $keyNew)
    $xml.Save($file.FullName)
  }
}</pre>
<p>&nbsp;</p>
</div>
<h3>MoveResource.ps1</h3>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:e57505e0-7453-4794-bf89-39f6ff068709" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: ps; gutter: true; first-line: 1; tab-size: 4;  toolbar: false;  width: 710px; height: 372px;" style="width: 710px; height: 372px; overflow: auto;">param([String]$resourceNameSource, [String]$resourceNameDestination, [string] $keyName)
if(-not $resourceNameSource -or -not $resourceNameDestination -or -not $keyName) {
  echo "MoveResource.ps1 resourceNameSource resourceNameDestination keyName"
  return
}

$sourceFiles = Get-ChildItem "Resources\$resourceNameSource*.resx"
$destFiles = Get-ChildItem "Resources\$resourceNameDestination*.resx"
$mapping = @{}

$sourceFiles | foreach {
  $parts = $_ -split "\."
  $list = New-Object "system.collections.arraylist"
  $list.Add($_) &gt; $null
  if($parts.Length -eq 2) {
    $mapping["en-us"] = $list
  }
  else {
    $mapping[$parts[1]] = $list
  }
}

$destFiles | foreach {
  $parts = $_ -split "\."
  if($parts.Length -eq 2) {
    $mapping["en-us"].Add($_ ) &gt; $null
  }
  else {
    $mapping[$parts[1]].Add($_ ) &gt; $null
  }
}

foreach($pair in $mapping.Values) {
  $sourcePath = $pair[0]
  $destPath = $pair[1]
  $source = [xml](Get-Content $sourcePath)
  $dest = [xml](Get-Content $destPath)

  $keyNodeSource = $source.root.data | Where-Object { $_.GetAttribute("name") -eq $keyName }
  $keyNodeDest = $dest.root.data | Where-Object { $_.GetAttribute("name") -eq $keyName }
  if ($keyNodeSource -eq $null) {
      echo "Key does not exist in source"
      return;
  }
  if($keyNodeDest -ne $null) {
    echo "Key already exists in destination"
    return;
  }
  try
  {
    $newNode = $dest.ImportNode($keyNodeSource.Clone(), $true)
    $source.root.RemoveChild($keyNodeSource) &gt; $null
    $dest.root.AppendChild($newNode) &gt; $null
    $dest.Save($destPath)
    $source.Save($sourcePath)
  }
  catch {
    Write-Host "Error text: " $_
    return
  }
}</pre>
<p>&nbsp;</p>
</div>
<h3>Usage</h3>
<p>Renaming a resource key:</p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:baacbc39-9326-4eb8-94d5-897e0d96a8e8" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: plain; gutter: false; first-line: 1; tab-size: 4;  toolbar: false;  width: 802px; height: 80px;" style="width: 802px; height: 80px; overflow: auto;">.\RenameResource.ps1 oldKey newKey</pre>
<p>&nbsp;</p>
</div>
<p>Moving a resource with key “keyName”  from a file named “ResourceFile1.resx” to “ResourceFile2.resx”:</p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:a950a9fb-9f0c-4290-aebd-a21d4e14d1c8" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: plain; gutter: false; first-line: 1; tab-size: 4;  toolbar: false;  width: 848px; height: 94px;" style="width: 848px; height: 94px; overflow: auto;">.\MoveResource.ps1 ResourceFile1 ResourceFile2 keyName</pre>
<p>&nbsp;</p>
</div>
<div id="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://matthewmanela.com/blog/making-an-executable-take-pipelined-input-in-powershell/" rel="bookmark" class="crp_title">Making an executable take pipelined input in PowerShell</a></li><li><a href="http://matthewmanela.com/blog/inheriting-base-type-mappings-with-automapper-extension/" rel="bookmark" class="crp_title">Inheriting base type mappings with AutoMapper</a></li><li><a href="http://matthewmanela.com/blog/a-simple-javascript-stubbing-function/" rel="bookmark" class="crp_title">A simple JavaScript stubbing function</a></li></ul></div><img src="http://feeds.feedburner.com/~r/Farblondzshet/~4/mO7hBkjqQ20" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://matthewmanela.com/blog/moving-and-renaming-resource-keys-in-a-resx-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Chutzpah 1.2.0 Released</title>
		<link>http://matthewmanela.com/blog/chutzpah-1-2-0-released/</link>
		<comments>http://matthewmanela.com/blog/chutzpah-1-2-0-released/#comments</comments>
		<pubDate>Mon, 12 Sep 2011 05:29:01 +0000</pubDate>
		<dc:creator>Matthew</dc:creator>
				<category><![CDATA[Chutzpah]]></category>
		<category><![CDATA[Codeplex]]></category>
		<category><![CDATA[NuGet]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Visual Studio Gallery]]></category>

		<guid isPermaLink="false">http://matthewmanela.com/?p=1388</guid>
		<description><![CDATA[A new version of Chutzpah is now live on Visual Studio Gallery, CodePlex and now NuGet. This release contains the following changes. 1. Added the Chutzpah console runner as a NuGet package. Once installed the Chutzpah.Console.exe file will be located &#8230; <a href="http://matthewmanela.com/blog/chutzpah-1-2-0-released/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A new version of Chutzpah is now live on <a href="http://visualstudiogallery.msdn.microsoft.com/71a4e9bd-f660-448f-bd92-f5a65d39b7f0">Visual Studio Gallery</a>, <a href="http://chutzpah.codeplex.com/">CodePlex</a> and now <a href="http://nuget.org/List/Packages/Chutzpah" target="_blank">NuGet</a>.</p>
<p>This release contains the following changes.</p>
<p>1. Added the Chutzpah console runner as a <a href="http://nuget.org/List/Packages/Chutzpah">NuGet package</a>. Once installed the Chutzpah.Console.exe file will be located in the Tools directory of the Chutzpah package.</p>
<p>2. Added ability from command line and Visual Studio to have Chutzpah scan for test files when you execute it on a folder. This helps alleviate a pain point that arises when you break your JavaScript tests into multiple files. Before this change you would have to specify each file individually in the call to the console runner. Now it can take a folder name instead of a file name.</p>
<pre class="brush: plain; gutter: false; toolbar: false;">chutzpah.console.exe someFolder/jsTests</pre>
<p>When Chutzpah sees that you provided a folder it will scan recursively within that folder for .js files and run any it believes are QUnit test files.</p>
<p>3. Fixed a bug that caused Chutzpah to error on read-only files. This can be quite common since many source control systems can put files in this state.</p>
<p>4. Added a command line flag /OpenInBrowser which makes Chutzpah open the test files in your default browser.  This can be helpful since it allows you to debug the tests more easily.</p>
<div id="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://matthewmanela.com/blog/chutzpah-1-3-0-released/" rel="bookmark" class="crp_title">Chutzpah 1.3.0 Released</a></li><li><a href="http://matthewmanela.com/blog/chutzpah-1-1-0-released/" rel="bookmark" class="crp_title">Chutzpah 1.1.0 Released</a></li><li><a href="http://matthewmanela.com/blog/chutzpah-a-javascript-test-runner-released/" rel="bookmark" class="crp_title">Chutzpah &#8211; A JavaScript Test Runner Released</a></li></ul></div><img src="http://feeds.feedburner.com/~r/Farblondzshet/~4/e1ncsH36QYs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://matthewmanela.com/blog/chutzpah-1-2-0-released/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Make your website faster with RequestReduce</title>
		<link>http://matthewmanela.com/blog/make-your-website-faster-with-requestreduce/</link>
		<comments>http://matthewmanela.com/blog/make-your-website-faster-with-requestreduce/#comments</comments>
		<pubDate>Sun, 11 Sep 2011 01:23:35 +0000</pubDate>
		<dc:creator>Matthew</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Open Source]]></category>

		<guid isPermaLink="false">http://matthewmanela.com/?p=1380</guid>
		<description><![CDATA[My co-worker Matt Wrock released an open source project on GitHub and Nuget called RequestReduce.&#160; It is a very quick and easy way to dramatically improve the performance of an ASP.NET website. We use this library for our sites at &#8230; <a href="http://matthewmanela.com/blog/make-your-website-faster-with-requestreduce/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>My co-worker <a href="http://www.mattwrock.com" target="_blank">Matt Wrock</a> released an open source project on <a href="https://github.com/mwrock/RequestReduce" target="_blank">GitHub</a> and <a href="http://nuget.org/List/Packages/RequestReduce" target="_blank">Nuget</a> called <a href="http://requestreduce.com" target="_blank">RequestReduce</a>.&nbsp; It is a very quick and easy way to dramatically improve the performance of an ASP.NET website. We use this library for our sites at work and after adding it we saw around an 18% improvement in global page load time.</p>
<p>RequestReduce works by examining the resources in an HTTP request and optimizes them before sending to the user. It will optimize them in the following ways (Matt Wrock’s <a href="http://www.mattwrock.com/post/2011/09/10/Adopt-RequestReduce-and-see-immediate-Yslow-and-Google-Page-Speed-score-improvements-not-to-mention-a-faster-site!.aspx" target="_blank">own words</a>):</p>
<blockquote><ul>
<li>Look for background images that it can sprite. This is the process of combining multiple images into a single image and using some CSS syntax to pull in specific images from that single file into a CSS class’s background.
<li>Merge these images into a single PNG that is quantized down to 256 colors and then run through optipng for lossless compression. Unsatisfied with the quality I was getting from the popular opensource quantizers, I created a quantizer based on the Wu quantization algorithm and have released that separately as <a href="http://nquant.codeplex.com/">nQuant</a> on codeplex. This often reduces the image size up to 3x smaller than the original.
<li>Merges all CSS in the head and minifies it.
<li>Manages the downloads of these CSS and image requests using ETag and expires headers to ensure optimal caching on the browser.</li>
</ul>
</blockquote>
<p>One of the nicest aspects of RequestReduce is how simple it is to start using. Just download the binaries to your website bin folder and add the following to your web.config:</p>
<pre class="brush: xml; gutter: false; toolbar: false;">&lt;system.webServer&gt;
 &lt;modules runAllManagedModulesForAllRequests="true"&gt;
  &lt;add name="RequestReduce" type="RequestReduce.Module.RequestReduceModule, RequestReduce, Version=1.0.0.0,
  Culture=neutral" /&gt;
 &lt;/modules&gt;
&lt;/system.webServer&gt;
</pre>
<p>If you are interested I would definitely head over to the <a href="http://requestreduce.com" target="_blank">RequestReduce</a> website to read the detailed documentation (including advanced configuration options) and the source code (yay for open source <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://matthewmanela.com/wp-content/uploads/2011/09/wlEmoticon-smile.png"> ).</p>
<div id="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://matthewmanela.com/blog/chutzpah-1-3-0-released/" rel="bookmark" class="crp_title">Chutzpah 1.3.0 Released</a></li><li><a href="http://matthewmanela.com/blog/diffplex-1-2-released/" rel="bookmark" class="crp_title">DiffPlex 1.2 Released</a></li><li><a href="http://matthewmanela.com/blog/chutzpah-1-2-0-released/" rel="bookmark" class="crp_title">Chutzpah 1.2.0 Released</a></li></ul></div><img src="http://feeds.feedburner.com/~r/Farblondzshet/~4/4P-8y4oWPsM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://matthewmanela.com/blog/make-your-website-faster-with-requestreduce/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Update on inheriting base type mappings with AutoMapper</title>
		<link>http://matthewmanela.com/blog/update-on-inheriting-base-type-mappings-with-automapper/</link>
		<comments>http://matthewmanela.com/blog/update-on-inheriting-base-type-mappings-with-automapper/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 16:45:04 +0000</pubDate>
		<dc:creator>Matthew</dc:creator>
				<category><![CDATA[AutoMapper]]></category>
		<category><![CDATA[github]]></category>

		<guid isPermaLink="false">http://matthewmanela.com/?p=1373</guid>
		<description><![CDATA[Several months ago I wrote this post which shows an extension method for inheriting the mappings on a base type for a child type in AutoMapper.&#160; Since then I have had a few comments on the post which led me &#8230; <a href="http://matthewmanela.com/blog/update-on-inheriting-base-type-mappings-with-automapper/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Several months ago I wrote <a href="http://matthewmanela.com/blog/inheriting-base-type-mappings-with-automapper-extension/" target="_blank">this post</a> which shows an extension method for inheriting the mappings on a base type for a child type in <a href="http://automapper.codeplex.com/" target="_blank">AutoMapper</a>.&nbsp; Since then I have had a few comments on the post which led me to make a small update. One of the assumptions I made in my implementation was that when inheriting base type mappings both of your mapping types will have their base types in the parent mapping. For example:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:df6587ce-ebd0-4d05-ae22-3c77071231f0" class="wlWriterEditableSmartContent">
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: false;  width: 925px; height: 131px;" style=" width: 925px; height: 131px;overflow: auto;">Mapper.CreateMap&lt;SourceBaseClass, DestBaseClass&gt;()
&#160;&#160;&#160;&#160;.ForMember(x =&gt; x.BasePropTwo, m =&gt; m.MapFrom(x =&gt; x.BaseProp2));
&#160;
Mapper.CreateMap&lt;SourceChildClass, DestChildClass&gt;()
&#160;&#160;&#160;&#160;.ForMember(x =&gt; x.ChildPropTwo, m =&gt; m.MapFrom(x =&gt; x.ChildProp2))
&#160;&#160;&#160;&#160;.InheritMappingFromBaseType();</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>However, there are scenarios where you may have one type that is mapping to both a parent and child type and would still want to inherit the parent mapping for the child mapping. If you try this with my previous code it would look like this but not work.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:04bda575-d8b6-43c6-8864-f8838ab37a0d" class="wlWriterEditableSmartContent">
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: false;  width: 925px; height: 148px;" style=" width: 925px; height: 148px;overflow: auto;">Mapper.CreateMap&lt;SourceClass, DestBaseClass&gt;()
&#160;&#160;&#160;&#160;.ForMember(x =&gt; x.BasePropTwo, m =&gt; m.MapFrom(x =&gt; x.BaseProp2));
&#160;
Mapper.CreateMap&lt;SourceClass, DestChildClass&gt;()
&#160;&#160;&#160;&#160;.ForMember(x =&gt; x.ChildPropTwo, m =&gt; m.MapFrom(x =&gt; x.ChildProp2))
&#160;&#160;&#160;&#160;.InheritMappingFromBaseType();</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>In order to support this scenario I updated the extension method to take an optional enum which specifies if you want to inherit a mapping that has a base type for the source type, destination type or both.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:2585aa6e-923e-4da0-b45b-4f46d6f7c497" class="wlWriterEditableSmartContent">
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: false;  width: 925px; height: 672px;" style=" width: 925px; height: 672px;overflow: auto;">public enum WithBaseFor
{
    Source,
    Destination,
    Both
}

public static class Inheritance
{
    public static void InheritMappingFromBaseType&lt;TSource, TDestination&gt;(this IMappingExpression&lt;TSource, TDestination&gt; mappingExpression,
                                                                         WithBaseFor baseFor = WithBaseFor.Both)
    {
        var sourceType = typeof (TSource);
        var destinationType = typeof (TDestination);
        var sourceParentType = baseFor == WithBaseFor.Both || baseFor == WithBaseFor.Source
                                   ? sourceType.BaseType
                                   : sourceType;

        var destinationParentType = baseFor == WithBaseFor.Both || baseFor == WithBaseFor.Destination
                                        ? destinationType.BaseType
                                        : destinationType;

        mappingExpression
            .BeforeMap((x, y) =&gt; Mapper.Map(x, y, sourceParentType, destinationParentType))
            .ForAllMembers(x =&gt; x.Condition(r =&gt; NotAlreadyMapped(sourceParentType, destinationParentType, r)));
    }

    private static bool NotAlreadyMapped(Type sourceType, Type desitnationType, ResolutionContext r)
    {
        return !r.IsSourceValueNull &amp;&amp;
               Mapper.FindTypeMapFor(sourceType, desitnationType).GetPropertyMaps().Where(
                   m =&gt; m.DestinationProperty.Name.Equals(r.MemberName)).Select(y =&gt; !y.IsMapped()).All(b =&gt; b);
    }
}</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Using this new code the above mapping becomes</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:5620bf5d-9a07-46db-b921-83688e7c40d7" class="wlWriterEditableSmartContent">
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: false;  width: 925px; height: 157px;" style=" width: 925px; height: 157px;overflow: auto;">Mapper.CreateMap&lt;SourceClass, DestBaseClass&gt;()
    .ForMember(x =&gt; x.BasePropTwo, m =&gt; m.MapFrom(x =&gt; x.BaseProp2));

Mapper.CreateMap&lt;SourceClass, DestChildClass&gt;()
    .ForMember(x =&gt; x.ChildPropTwo, m =&gt; m.MapFrom(x =&gt; x.ChildProp2))
    .InheritMappingFromBaseType(WithBaseFor.Destination);</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>There is one caveat to using my InheritMappingFromBaseType extension method that was discovered since my original post … it is not compatible with the <strong>Mapper.AssertConfigurationIsValid()</strong> call. It will cause this function to fail even though your mapping will work fine. I haven’t had a chance to figure out if there is a way around this but if anyone has an idea I would love to hear it.</p>
<p>I published the updated code and a sample project showing its use to the <a href="https://github.com/mmanela/InheritedAutoMapper" target="_blank">InheritedAutoMapper GitHub page</a>. Feel free to grab the code and fork it to your liking.</p>
<div id="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://matthewmanela.com/blog/inheriting-base-type-mappings-with-automapper-extension/" rel="bookmark" class="crp_title">Inheriting base type mappings with AutoMapper</a></li><li><a href="http://matthewmanela.com/blog/making-an-executable-take-pipelined-input-in-powershell/" rel="bookmark" class="crp_title">Making an executable take pipelined input in PowerShell</a></li><li><a href="http://matthewmanela.com/blog/return-type-overloading-in-haskell/" rel="bookmark" class="crp_title">Return type overloading in Haskell</a></li></ul></div><img src="http://feeds.feedburner.com/~r/Farblondzshet/~4/ErM7DWN-Ves" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://matthewmanela.com/blog/update-on-inheriting-base-type-mappings-with-automapper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Chutzpah 1.1.0 Released</title>
		<link>http://matthewmanela.com/blog/chutzpah-1-1-0-released/</link>
		<comments>http://matthewmanela.com/blog/chutzpah-1-1-0-released/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 13:26:32 +0000</pubDate>
		<dc:creator>Matthew</dc:creator>
				<category><![CDATA[Chutzpah]]></category>
		<category><![CDATA[Open Source]]></category>

		<guid isPermaLink="false">http://matthewmanela.com/?p=1371</guid>
		<description><![CDATA[A new version of Chutzpah is now live on Visual Studio Gallery and CodePlex. This release contains the following changes: Added a “Run JS Tests in Browser” menu option inside of Visual Studio. This will open your default browser and &#8230; <a href="http://matthewmanela.com/blog/chutzpah-1-1-0-released/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A new version of Chutzpah is now live on <a href="http://visualstudiogallery.msdn.microsoft.com/71a4e9bd-f660-448f-bd92-f5a65d39b7f0" target="_blank">Visual Studio Gallery</a> and <a href="http://chutzpah.codeplex.com/" target="_blank">CodePlex</a>.</p>
<p>This release contains the following changes:</p>
<ul>
<li>Added a “Run JS Tests in Browser” menu option inside of Visual Studio. This will open your default browser and run the selected QUnit test file.
<li>Automatically save the test file in Visual Studio when you choose “Run JS Tests”
<li>Added keyboard shortcut support for Visual Studio
<ul>
<li>Bind a shortcut to the <strong>ProjectAndSolutionsContextMenus.Project.RunJSTests</strong> command to run JS tests</li>
</ul>
<ul><!--EndFragment--></ul>
<li>Return line and column position for failed tests when you run a test JS file directly.
<li>Upgraded to <a href="http://www.phantomjs.org/" target="_blank">PhantomJS 1.2</a> </li>
</ul>
<div id="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://matthewmanela.com/blog/chutzpah-1-2-0-released/" rel="bookmark" class="crp_title">Chutzpah 1.2.0 Released</a></li><li><a href="http://matthewmanela.com/blog/chutzpah-1-3-0-released/" rel="bookmark" class="crp_title">Chutzpah 1.3.0 Released</a></li><li><a href="http://matthewmanela.com/blog/chutzpah-a-javascript-test-runner-released/" rel="bookmark" class="crp_title">Chutzpah &#8211; A JavaScript Test Runner Released</a></li></ul></div><img src="http://feeds.feedburner.com/~r/Farblondzshet/~4/qGPyfpye-84" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://matthewmanela.com/blog/chutzpah-1-1-0-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A combined Mercurial and Git PowerShell Prompt</title>
		<link>http://matthewmanela.com/blog/a-combined-mercurial-and-git-powershell-prompt/</link>
		<comments>http://matthewmanela.com/blog/a-combined-mercurial-and-git-powershell-prompt/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 22:56:00 +0000</pubDate>
		<dc:creator>Matthew</dc:creator>
				<category><![CDATA[Git]]></category>
		<category><![CDATA[Mercurial]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://matthewmanela.com/?p=1292</guid>
		<description><![CDATA[A while ago I posted the code I use to create a custom PowerShell prompt to show the status of my Mercurial repositories. Since then I have also started using Git so I updated my prompt to work for both. &#8230; <a href="http://matthewmanela.com/blog/a-combined-mercurial-and-git-powershell-prompt/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A <a href="http://matthewmanela.com/blog/a-mercurial-powershell-prompt/" target="_blank">while ago</a> I posted the code I use to create a custom PowerShell prompt to show the status of my Mercurial repositories. Since then I have also started using Git so I updated my prompt to work for both. I find this prompt very convenient since it quickly shows what branch you are in as well as what pending changes you have in your working directory.</p>
<p>Here is the updated code:</p>
<pre class="brush: ps; gutter: false; toolbar: false;">if (test-path function:\prompt) {
   $oldPrompt = ls function: | ? {$_.Name -eq "prompt"}
   remove-item -force function:\prompt
 }
 function prompt {
  function getGitStatus {
  $branch = git branch 2&gt;&amp;1
  if($branch.Exception -eq $null) {
    $status = "git"
    $branch | foreach {
      if ($_ -match "^\*(.*)"){
        $status += $matches[1]
      }
    }

    $untracked = 0
    $updates = 0
    $deletes = 0
    $addsIndex = 0
    $deletesIndex =0
    $updatesIndex = 0

    git status --porcelain | foreach {
      if($_ -match "^([\w?]|\s)([\w?])?\s*") {
        switch ($matches[1]) {
          "A" {$addsIndex++ }
          "M" {$updatesIndex++ }
          "D" {$deletesIndex++ }
          "?" {$untracked++ }
        }
        switch ($matches[2]) {
          "A" {$adds++ }
          "M" {$updates++ }
          "D" {$deletes++ }
         }
      }
    }
    $status += " a:" +$addsIndex
    if($adds -gt 0) {
      $status += "($adds)"
    }

    $status += " m:" +$updatesIndex
    if($updates -gt 0) {
      $status += "($updates)"
    }

    $status += " d:" +$deletesIndex
    if($deletes -gt 0) {
      $status += "($deletes)"
    }     

    $status += " ?:$untracked"
    return $status
  }
  else {
    return $false
  }
}

  function getHgStatus {
    $summary = hg summary 2&gt;&amp;1
    if($summary.Exception -eq $null) {
      $regex = "(?si)(parent:(?&lt;parent&gt;.*?)(\n|\r)+.*?)(branch:(?&lt;branch&gt;.*)\s)(commit:(?&lt;commit&gt;.*)\s)(update:(?&lt;update&gt;.*))";
      $summary = [System.String]::Join([System.Environment]::NewLine,$summary)
      $res = $summary -match $regex
      $status = "hg {0} c:{1}" -f $matches["branch"].Trim(), $matches["commit"].Trim()
      return $status
   }
   else {
    return $false
   }
  }

  $status = getGitStatus
  if(-not $status) {
      $status = getHgStatus
  }
  $host.ui.rawui.WindowTitle = (get-location).Path
  if($status) {
    write-host ($status) -NoNewLine -ForegroundColor Green
    write-host ("&gt;") -NoNewLine -ForegroundColor Green
  }
  else {
    &amp; $oldPrompt
  }
  return " "
}</pre>
<p>After adding this prompt to your <a href="http://technet.microsoft.com/en-us/library/ee692764.aspx">profile</a> when you are in a git repository you will see this:</p>
<p><a href="http://matthewmanela.com/wp-content/uploads/2011/07/gitPrompt1.png"><img class="alignnone size-full wp-image-1364" title="gitPrompt" src="http://matthewmanela.com/wp-content/uploads/2011/07/gitPrompt1.png" alt="" width="298" height="21" /></a></p>
<p>This is more complex than the Mercurial prompt since git has the concept of a staging area. The number not in parentheses is the &#8220;staged&#8221; value and the number in parentheses is the unstaged value. So in the prompt above the repository has 1 modification staged and one unstaged.</p>
<p>When you are in a Mercurial repository you will see this:</p>
<p><a href="http://matthewmanela.com/wp-content/uploads/2011/07/hgPrompt.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="hgPrompt" src="http://matthewmanela.com/wp-content/uploads/2011/07/hgPrompt_thumb.png" alt="hgPrompt" width="313" height="25" border="0" /></a></p>
<div id="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://matthewmanela.com/blog/a-mercurial-powershell-prompt/" rel="bookmark" class="crp_title">A Mercurial PowerShell Prompt</a></li><li><a href="http://matthewmanela.com/blog/launching-the-tortoisehg-log-more-conveniently-from-the-command-line/" rel="bookmark" class="crp_title">Launching the TortoiseHg log more conveniently from the command line</a></li><li><a href="http://matthewmanela.com/blog/regex-hero-free-online-regular-expression-tester/" rel="bookmark" class="crp_title">Regex Hero: Free online regular expression tester</a></li></ul></div><img src="http://feeds.feedburner.com/~r/Farblondzshet/~4/9ydAiGrxshc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://matthewmanela.com/blog/a-combined-mercurial-and-git-powershell-prompt/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making linking between anchors in an IFrame work in Firefox 4 and above</title>
		<link>http://matthewmanela.com/blog/making-linking-between-anchors-in-an-iframe-work-in-firefox-4-and-above/</link>
		<comments>http://matthewmanela.com/blog/making-linking-between-anchors-in-an-iframe-work-in-firefox-4-and-above/#comments</comments>
		<pubDate>Thu, 30 Jun 2011 18:47:58 +0000</pubDate>
		<dc:creator>Matthew</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://matthewmanela.com/?p=1278</guid>
		<description><![CDATA[In Firefox 4 a security fix was added which prevents linking between anchors within an IFrame that does not have scroll bars. This change breaks the scenario where you have an IFrame that has a “Go To Top” link (&#60;a &#8230; <a href="http://matthewmanela.com/blog/making-linking-between-anchors-in-an-iframe-work-in-firefox-4-and-above/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In Firefox 4 a <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=638598" target="_blank">security fix was added</a> which prevents linking between anchors within an IFrame that does not have scroll bars. This change breaks the scenario where you have an IFrame that has a “Go To Top” link (&lt;a href=”top”&gt;Go to top&lt;/a&gt;) which links to an anchor tag (&lt;a name=”#top” /&gt;) at the top of the IFrame.&nbsp; If this IFrame does not have scroll bars then clicking the link will scroll the parent page to bring the anchor into view. This can be a <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=638598#c11" target="_blank">security issue</a> which is why Firefox is the first browser to block it.&nbsp; However, I believe they should have added an exception for the case when the IFrame and the containing page satisfy the <a href="http://en.wikipedia.org/wiki/Same_origin_policy" target="_blank">Same Origin Policy</a>.</p>
<p>I worked around this limitation by adding the following code to my IFrame (my implementation uses jQuery) which will override the anchor link functionality and scroll the window programmatically. This code makes use of the <strong>window.parent</strong> property which means it is subject to the Same Origin Policy.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:8b91db61-7ff0-45b5-9d1a-02c4c5e59220" class="wlWriterEditableSmartContent">
<pre class="brush: jscript; gutter: true; first-line: 1; tab-size: 4;  toolbar: false;  width: 790px; height: 379px;" style=" width: 790px; height: 379px;overflow: auto;">$(function(){
  $(&quot;a&quot;).each(function (){
    var link = $(this);
    var href = link.attr(&quot;href&quot;);
    if(href &amp;&amp; href[0] == &quot;#&quot;)
    {
      var name = href.substring(1);
      $(this).click(function() {
        var nameElement = $(&quot;[name='&quot;+name+&quot;']&quot;);
        var idElement = $(&quot;#&quot;+name);
        var element = null;
        if(nameElement.length &gt; 0) {
          element = nameElement;
        } else if(idElement.length &gt; 0) {
          element = idElement;
        }

        if(element) {
          var offset = element.offset();
          window.parent.scrollTo(offset.left, offset.top);
        }

        return false;
      });
    }
  });
});</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<div id="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://matthewmanela.com/blog/the-nu-package-management-system-and-diffplex/" rel="bookmark" class="crp_title">The Nu package management system and DiffPlex</a></li><li><a href="http://matthewmanela.com/blog/updated-jquery-resizecomplete-method/" rel="bookmark" class="crp_title">Updated JQuery ResizeComplete method</a></li><li><a href="http://matthewmanela.com/blog/rough-draft-of-a-new-jquery-method/" rel="bookmark" class="crp_title">Rough draft of a new JQuery method</a></li></ul></div><img src="http://feeds.feedburner.com/~r/Farblondzshet/~4/mnUY5EaouJs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://matthewmanela.com/blog/making-linking-between-anchors-in-an-iframe-work-in-firefox-4-and-above/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Chutzpah – A JavaScript Test Runner Released</title>
		<link>http://matthewmanela.com/blog/chutzpah-a-javascript-test-runner-released/</link>
		<comments>http://matthewmanela.com/blog/chutzpah-a-javascript-test-runner-released/#comments</comments>
		<pubDate>Mon, 20 Jun 2011 05:25:58 +0000</pubDate>
		<dc:creator>Matthew</dc:creator>
				<category><![CDATA[Chutzpah]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://matthewmanela.com/?p=1261</guid>
		<description><![CDATA[I just released to CodePlex and the Visual Studio Gallery a new project called Chutzpah (hutz·pah). Chutzpah is an open source JavaScript unit test runner which helps you integrate JavaScript unit testing into your website. It enables you to run &#8230; <a href="http://matthewmanela.com/blog/chutzpah-a-javascript-test-runner-released/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I just released to <a href="http://chutzpah.codeplex.com" target="_blank">CodePlex</a> and the <a href="http://visualstudiogallery.msdn.microsoft.com/71a4e9bd-f660-448f-bd92-f5a65d39b7f0" target="_blank">Visual Studio Gallery</a> a new project called Chutzpah (<a href="http://www.thefreedictionary.com/chutzpah" target="_blank">hutz·pah</a>). Chutzpah is an open source JavaScript unit test runner which helps you integrate JavaScript unit testing into your website. It enables you to run JavaScript unit tests from the command line and from inside of Visual Studio. It also supports running in the TeamCity continuous integration server.</p>
<h2>Backstory</h2>
<p>About nine months ago I asked <a href="http://stackoverflow.com/questions/3827055/run-javascript-unit-tests-inside-of-visual-studio-2010" target="_blank">a question on StackOverflow</a> about whether there were any tools/extensions which integrated into Visual Studio to run JavaScript unit tests. At that time there were no good solutions provided which led me to investigate creating my own tool. I explored many options but eventually I found the <a href="http://www.phantomjs.org/" target="_blank">PhantomJS</a> headless browser to help drive the tests.  After a couple weeks of development Chutzpah was born.</p>
<h2>What does Chutzpah do?</h2>
<p>Chutzpah is both a Visual Studio extension and a command line utility.</p>
<p><strong>As a Visual Studio extension:</strong></p>
<blockquote><p>It allows you to run your JavaScript tests without leaving the IDE. It adds a context menu option to run tests directly from a source file.</p>
<p><a href="http://matthewmanela.com/wp-content/uploads/2011/06/RightMenu.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="RightMenu" src="http://matthewmanela.com/wp-content/uploads/2011/06/RightMenu_thumb.png" border="0" alt="RightMenu" width="644" height="209" /></a></p></blockquote>
<blockquote><p>It logs test results to both the Error list and the Output window.</p>
<p><a href="http://matthewmanela.com/wp-content/uploads/2011/06/errorWindow.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="errorWindow" src="http://matthewmanela.com/wp-content/uploads/2011/06/errorWindow_thumb.png" border="0" alt="errorWindow" width="644" height="113" /></a></p>
<p><a href="http://matthewmanela.com/wp-content/uploads/2011/06/outputWindow.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="outputWindow" src="http://matthewmanela.com/wp-content/uploads/2011/06/outputWindow_thumb.png" border="0" alt="outputWindow" width="644" height="152" /></a></p></blockquote>
<p><strong>As a command line utility:</strong></p>
<blockquote><p>It allows you to easily integrate test results into your build</p>
<p><a href="http://matthewmanela.com/wp-content/uploads/2011/06/commandLine.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="commandLine" src="http://matthewmanela.com/wp-content/uploads/2011/06/commandLine_thumb.png" border="0" alt="commandLine" width="644" height="302" /></a></p></blockquote>
<blockquote><p>It also has support for the <a href="http://www.jetbrains.com/teamcity/" target="_blank">TeamCity</a> continuous integration server so that you get detailed test output on every build.</p></blockquote>
<h2>How to use it?</h2>
<p>Chutzpah is really easy to use, given <a href="http://docs.jquery.com/QUnit" target="_blank">QUnit</a> tests (it only supports QUnit for now) you can run Chutzpah on the test harness HTML file and it will output the results. Chutzpah also supports running the tests directly from the JavaScript file as long as you add <a href="http://chutzpah.codeplex.com/wikipage?title=runTests&amp;referringTitle=Home#noHarness" target="_blank">reference comments</a> to the top of your test file.</p>
<p>For example given two files test.js (QUnit tests file) and code.js (implementation file).</p>
<p><strong>code.js</strong></p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:3f9b7b57-6c0b-4b4c-aa5f-ec8c8af3a2fd" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: false;  width: 789px; height: 106px;" style="width: 789px; height: 106px; overflow: auto;">var mathLib = {
    add5: function (a) {
        return a + 5;
    }
}</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></p>
</div>
<p><strong>test.js</strong></p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:c205b0a9-224f-4a97-b64f-45105a6a40a7" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: jscript; gutter: false; first-line: 1; tab-size: 4;  toolbar: false;  width: 789px; height: 157px;" style="width: 789px; height: 157px; overflow: auto;">/// &lt;reference path="code.js" /&gt;

test("will add 5 to number", function () {
    var res = mathLib.add5(10)

    equals(res, 15, "should add 5");
});</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></p>
</div>
<p>You can run the tests by right clicking and choosing “Run JS Test” if you are using the Visual Studio plugin, otherwise you can execute Chutzpah from the command line:</p>
<div id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:68cd1ab9-139c-4fd2-97d3-1db760bf6b89" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<pre class="brush: powershell; gutter: false; first-line: 1; tab-size: 4;  toolbar: false;  width: 789px; height: 54px;" style="width: 789px; height: 54px; overflow: auto;">.\chutzpah.console.exe test.js</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></p>
</div>
<h2>Community Support</h2>
<p>I am really excited about releasing Chutzpah as an open source project with the hope of garnering support from the community. I would love to get feedback, bug reports, feature requests and code contributions. If you are interested in working on Chutzpah fork the code and get hacking.</p>
<h2>Future <span style="text-decoration: line-through;">Plans</span> Ideas</h2>
<p>At this stage I have many ideas of what features should come next for Chutzpah but outside of bug fixes I have no solid plans yet. Here are several ideas floating around in my head…</p>
<ol>
<li>Support other JavaScript unit test frameworks besides QUnit</li>
<li>Expand past only using PhantomJS as the headless browser, possibly working with things like JsTestDriver or EnvJS.</li>
<li>Be able to run individual tests instead of just a whole file.</li>
<li>Add better IDE support like the <a href="http://blogs.jetbrains.com/dotnet/2011/03/resharper-6-introduces-support-for-javascript-unit-testing/" target="_blank">Resharper 6 QUnit functionality</a>.</li>
<li>Add scanning for test files within a whole project hierarchy</li>
<li>Support proxy servers</li>
<li>Capture more detailed information from each test</li>
<li>Integrate with existing test runners like MSTest or TestDriven.NET</li>
<li>Add NuGet support</li>
</ol>
<div id="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://matthewmanela.com/blog/chutzpah-1-3-0-released/" rel="bookmark" class="crp_title">Chutzpah 1.3.0 Released</a></li><li><a href="http://matthewmanela.com/blog/chutzpah-1-1-0-released/" rel="bookmark" class="crp_title">Chutzpah 1.1.0 Released</a></li><li><a href="http://matthewmanela.com/blog/chutzpah-1-2-0-released/" rel="bookmark" class="crp_title">Chutzpah 1.2.0 Released</a></li></ul></div><img src="http://feeds.feedburner.com/~r/Farblondzshet/~4/Xz4dYbaV6q0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://matthewmanela.com/blog/chutzpah-a-javascript-test-runner-released/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic (Feed is rejected)
Page Caching using disk: enhanced

Served from: matthewmanela.com @ 2012-01-28 21:22:55 -->

