<?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>Storm Blog &#187; Code</title>
	<atom:link href="http://www.storm-consultancy.com/tag/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.storm-consultancy.com</link>
	<description>Web Design News &#38; Tutorials</description>
	<lastBuildDate>Mon, 30 Jan 2012 14:13:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>JQuery &amp; HTML5 Drag n Drop Uploads with ASP.NET MVC3</title>
		<link>http://www.storm-consultancy.com/development/tools-plugins/jquery-html5-drag-n-drop-uploads-with-asp-net-mvc3/</link>
		<comments>http://www.storm-consultancy.com/development/tools-plugins/jquery-html5-drag-n-drop-uploads-with-asp-net-mvc3/#comments</comments>
		<pubDate>Tue, 10 Jan 2012 10:00:56 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Tools & Plugins]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://blog2.storm-consultancy.com/blog/?p=703</guid>
		<description><![CDATA[I recently came across this incredibly funky jQuery library to do Drag &#8216;n&#8217; Drop uploads using the new HTML5 File API.  After reading about it and playing with the demo I just had to try it out, so I&#8217;ve knocked up a sample ASP.NET MVC 3 app that handles the uploads.  It currently works in Chrome and [...]]]></description>
			<content:encoded><![CDATA[<p>I recently came across this incredibly funky <a href="http://www.igloolab.com/jquery-html5-uploader/">jQuery library to do Drag &#8216;n&#8217; Drop uploads</a> using the new HTML5 File API.  After reading about it and playing with the demo I just had to try it out, so I&#8217;ve knocked up a sample ASP.NET MVC 3 app that handles the uploads.  It currently works in Chrome and Firefox.</p>
<p>You can grab the code for this demo from <a href="https://github.com/stormuk/ASP.NET-MVC3-HTML5-Upload-Demo">GitHub</a>.</p>
<p><span id="more-703"></span></p>
<p>There&#8217;s not a lot to say that the demo doesn&#8217;t show, it&#8217;s all terribly easy to set up.  A minimal example requires a droppable area, e.g. a &lt;div&gt; tag to be on the page with the following JavaScript.</p>
<pre class="brush:javascript">$("#dropbox").html5Uploader({
    name: "myfile",
    postUrl: "/Home/Upload"
}</pre>
<p>The options specify the name of the form field when it&#8217;s POSTed and the URL of the script to POST to. From there you can extend the funkyness by listening for the wide range of events that get bubbled up.  These let you show previews of the files you&#8217;re uploading, show progress bars, let people know when the upload is complete or provide helpful errors when things go wrong.</p>
<p>All in all, it&#8217;s super sexy and really easy to get started with!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/development/tools-plugins/jquery-html5-drag-n-drop-uploads-with-asp-net-mvc3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Things Storm bookmarked this week / 26-10-11</title>
		<link>http://www.storm-consultancy.com/misc-web-stuff/things-storm-bookmarked-this-week-26-10-11/</link>
		<comments>http://www.storm-consultancy.com/misc-web-stuff/things-storm-bookmarked-this-week-26-10-11/#comments</comments>
		<pubDate>Wed, 26 Oct 2011 16:07:54 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Misc Web Stuff]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[coffeescript]]></category>
		<category><![CDATA[gem]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[music]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.storm-consultancy.com/?p=914</guid>
		<description><![CDATA[This week&#8230; Dave pointed me to the fact that Google have given their App Store a bit of a facelift. As he points out &#8211; &#8220;to say that it had a &#8216;hint of iTunes app store&#8217; is possibly an understatement&#8221; &#8211; but he&#8217;s also right, it&#8217;s pretty well put together and always worth spending a [...]]]></description>
			<content:encoded><![CDATA[<p>This week&#8230;</p>
<p>Dave pointed me to the fact that Google have given their <a href="https://chrome.google.com/webstore/category/home">App Store</a> a bit of a facelift. As he points out &#8211; &#8220;to say that it had a &#8216;hint of iTunes app store&#8217; is possibly an understatement&#8221; &#8211; but he&#8217;s also right, it&#8217;s pretty well put together and always worth spending a bit of time poking around..</p>
<p>From Adam &#8211; a <a href="https://github.com/javan/whenever">neat little Gem</a> which implements scheduled background tasks in Ruby. &#8220;It provides a simple way to specify any number of jobs on easily customisable schedules. It can call into other Ruby functions in your code, perform rake tasks or execute arbitrary command line commands.&#8221;</p>
<p>Liam &#8220;Apple&#8221; Gladdy gave me this: a sexy little <a href="http://demo.tutorialzine.com/2011/10/ios-homescreen-coffeescript/">iOS-app-screen-like web GUI in coffeescript</a> - Now I find I need to go and look up what &#8220;coffeescript&#8221; is&#8230;</p>
<p>And from me &#8211; this utterly awesome video/sound piece: &#8220;<a href="http://createdigitalmusic.com/2011/10/entire-musical-compositions-made-from-just-one-line-of-code-are-glitchy-but-musical/">Entire Musical Compositions Made from Just One Line of Code</a>&#8220;. Totally tremendous on sooo many levels :-)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/misc-web-stuff/things-storm-bookmarked-this-week-26-10-11/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating code coverage metrics for a Ruby on Rails project with simplecov</title>
		<link>http://www.storm-consultancy.com/development/tools-plugins/generating-code-coverage-metrics-for-a-ruby-on-rails-project-with-simplecov/</link>
		<comments>http://www.storm-consultancy.com/development/tools-plugins/generating-code-coverage-metrics-for-a-ruby-on-rails-project-with-simplecov/#comments</comments>
		<pubDate>Mon, 19 Sep 2011 14:44:15 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Tools & Plugins]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Code Coverage]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[RSpec]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[SimpleCov]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog2.storm-consultancy.com/blog/?p=733</guid>
		<description><![CDATA[As part of my dive into unit testing Rails applications I was keen to set up a tool to give me code coverage stats.  Code coverage represents the % of your source code that your unit tests exercise.  100% code coverage is a good goal to have and the earlier you hit it, the more [...]]]></description>
			<content:encoded><![CDATA[<p>As part of my dive into unit testing Rails applications I was keen to set up a tool to give me code coverage stats.  Code coverage represents the % of your source code that your unit tests exercise.  100% code coverage is a good goal to have and the earlier you hit it, the more likely you&#8217;ll find testing a worthwhile endeavour.  Whilst 100% coverage doesn&#8217;t guarantee that you&#8217;ve tested every permutation in your app, not having 100% coverage guarantees there are bits where daemons may be lurking.</p>
<h2><span id="more-733"></span>Setting up code coverage reports with Simplecov</h2>
<p>I first looked at <a href="https://github.com/relevance/rcov">rcov</a>, however, as soon as you run it, you get a lovely warning telling you that Ruby 1.9 support is experimental and that the results aren&#8217;t guaranteed to be correct! So I quickly moved on and found <a href="https://github.com/colszowka/simplecov">simplecov</a> which has full support for 1.9.</p>
<p>To get started, add the gem to your gemfile:</p>
<pre class="brush:ruby">gem 'simplecov'</pre>
<p>Then run a &#8216;bundle install&#8217; to grab the gem and set stuff up.  Next we need to hook simplecov into our tests.  Simplecov works with a range of test frameworks, so, depending on your framework of choice, the next instruction varies slightly.  If you&#8217;re using RSpec like me you need to open spec_helper.rb, if you&#8217;re running the default Rails test tools find test_helper.rb or if you&#8217;re using Cucumber find env.rb (other frameworks will have a similar initialization file).</p>
<p>At the very top of your helper file, enter</p>
<pre class="brush:ruby">require 'simplecov'
SimpleCov.start do
end</pre>
<p>Now, whenever you run your test suite, code coverage will be calculated and a fancy report will be available to view in coverage/index.html.  How easy was that!</p>
<p>We&#8217;re not done quite yet though, there are a few tweaks we can make to improve things further.  First up, we don&#8217;t want to include all of the stuff around the edge of a Rails app, for example, the config dir.  We can filter these bits out by adding some rules inside the initialisation block.</p>
<pre class="brush:ruby">require 'simplecov'
SimpleCov.start do
  add_filter '/spec/'
  add_filter '/config/'
  add_filter '/lib/'
  add_filter '/vendor/'
end</pre>
<p>I&#8217;ve included the /spec/ folder to be clear that I dont want coverage metrics run on my tests. If you re-run your test suite you should now see slightly cleaner results. simplecov has a powerful filtering engine that lets you define far more complex rules than these. For example, you can exclude short files that only have a couple of lines.</p>
<p>Our next tweak will be to make use of simplecov groups. Groups let you group together similar file types so that you can view them separately. In the example below you can see how I&#8217;ve set up groups for Models, Controllers, Views, Mailers and Helpers.</p>
<pre class="brush:ruby">require 'simplecov'
SimpleCov.start do
  add_filter '/spec/'
  add_filter '/config/'
  add_filter '/lib/'
  add_filter '/vendor/'

  add_group 'Controllers', 'app/controllers'
  add_group 'Models', 'app/models'
  add_group 'Helpers', 'app/helpers'
  add_group 'Mailers', 'app/mailers'
  add_group 'Views', 'app/views'
end</pre>
<p>Again, this only touches the surface of what you can do with simplecov. You can create far more complex rules to slice and dice your codebase as you wish.</p>
<p>There is one final tweak which you may find helpful, especially as your codebase grows. Running coverage metrics is SLOW! Much slower than just executing the test suite. So, you might not want to always run your coverage analysis &#8211; especially if you&#8217;re using a tool like autotest to re-run the tests every time the file system changes.</p>
<p>To make running coverage conditional, we&#8217;ll check for an environment variable before initialising simplecov.</p>
<pre class="brush:ruby;">SimpleCov.start do
  # rules here
end if ENV["COVERAGE"]</pre>
<p>Now I can run coverage on demand by specifying the COVERAGE environment variable</p>
<pre>$ COVERAGE=true bundle exec rake spec</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/development/tools-plugins/generating-code-coverage-metrics-for-a-ruby-on-rails-project-with-simplecov/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stop autotest continuously re-running your Rails tests</title>
		<link>http://www.storm-consultancy.com/development/tips-tricks/stop-autotest-continuously-re-running-your-rails-tests/</link>
		<comments>http://www.storm-consultancy.com/development/tips-tricks/stop-autotest-continuously-re-running-your-rails-tests/#comments</comments>
		<pubDate>Fri, 16 Sep 2011 13:30:11 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Gowl]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[RSpec]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog2.storm-consultancy.com/blog/?p=730</guid>
		<description><![CDATA[I&#8217;ve been getting up to speed with writing unit tests for Rails applications today.  My setup currently consists of RSpec tests being automatically run by autotest when I save a file.  This is a really nice workflow as you get instant feedback on failing tests.  Couple that with the autotest-growl gem to receive Growl notifications [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been getting up to speed with writing unit tests for Rails applications today.  My setup currently consists of <a href="http://rspec.info/">RSpec</a> tests being automatically run by <a href="https://github.com/grosser/autotest">autotest</a> when I save a file.  This is a really nice workflow as you get instant feedback on failing tests.  Couple that with the <a href="https://github.com/svoop/autotest-growl">autotest-growl</a> gem to receive <a href="http://growl.info/">Growl</a> notifications on failure and you&#8217;ve got a pretty funky setup.</p>
<p>However, autotest decided it wanted to re-run my tests over and over again, even if I hand&#8217;t saved a file in my project.  This had me very confused for quite a while until some Googling led me to &#8216;autotest -v&#8217; which shows you which files had changed.  The culprit: test.log.</p>
<p><span id="more-730"></span></p>
<h2>Excluding log files from autotest</h2>
<p>The workaround for this is pretty simple.  In your project root directory create a .autotest file.  Inside, put</p>
<pre class="brush:ruby">Autotest.add_hook :initialize do |autotest|
  %w{.git .svn .hg .DS_Store ._* vendor tmp log doc}.each do |exception|
    autotest.add_exception(exception)
  end
end

require "autotest/growl"
require "autotest/fsevent"</pre>
<p>That little snippet will exclude a bunch of files that you don&#8217;t want autotest to care about. The two requires at the bottom are needed for the awesome Growl integration :)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/development/tips-tricks/stop-autotest-continuously-re-running-your-rails-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using curly braces in a C# String.Format format pattern</title>
		<link>http://www.storm-consultancy.com/development/code-snippets/using-curly-braces-in-a-c-string-format-format-pattern/</link>
		<comments>http://www.storm-consultancy.com/development/code-snippets/using-curly-braces-in-a-c-string-format-format-pattern/#comments</comments>
		<pubDate>Sat, 15 Jan 2011 20:18:51 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.storm-consultancy.com/blog/development/?p=644</guid>
		<description><![CDATA[This is a gotcha which caught me out and after banging my head against my desk to 10 minutes was easily solved by reading the documentation.  I was trying to use StringBuilder.AppendFormat to build up a JavaScript function and kept getting hit with a FormatException when trying to do this: sb.AppendFormat("function {0}(args) { return false; [...]]]></description>
			<content:encoded><![CDATA[<p>This is a <em>gotcha</em> which caught me out and after banging my head against my desk to 10 minutes was easily solved by reading the documentation.  I was trying to use StringBuilder.AppendFormat to build up a JavaScript function and kept getting hit with a FormatException when trying to do this:</p>
<pre class="brush:csharp">sb.AppendFormat("function {0}(args) { return false; }", someVariable);</pre>
<p><span id="more-645"></span></p>
<p>The problem, of course, is that you can&#8217;t use the characters { or } inside a format string for String.Format() as they are special characters used to identify variables, as I have done in the example with the use of {0}.</p>
<p>The solution is actually fairly straightforward but not immediately obvious.  My first thought was to escape the special characters using the standard &#8220;\&#8221; , for example:</p>
<pre class="brush:csharp">sb.AppendFormat("function {0}(args) \{ return false; \}", someVariable);</pre>
<p>But that code generated the same FormatException.  After a little while I gave up and read the documentation (remember kids, always <a class="zem_slink" title="RTFM" rel="wikipedia" href="http://en.wikipedia.org/wiki/RTFM">RTFM</a>!) for the answer.  The code I wanted was:</p>
<pre class="brush:csharp">sb.AppendFormat("function {0}(args) {{ return false; }}", someVariable);</pre>
<p>Instead of using &#8220;\&#8221; as an escape character, you double up the special characters {{ or }}.  Easy.  When you know how.<br />
<a href="http://xkcd.com/293/"><img class="aligncenter" title="Life is too short for man pages, but occasionally much too short without them." src="http://imgs.xkcd.com/comics/rtfm.png" alt="Life is too short for man pages, but occasionally much too short without them." width="350" height="434" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/development/code-snippets/using-curly-braces-in-a-c-string-format-format-pattern/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>URL Re-Writing in ASP.NET Requires Form Action to be Re-written</title>
		<link>http://www.storm-consultancy.com/development/code-snippets/url-re-writing-in-asp-net-requires-form-action-to-be-re-written/</link>
		<comments>http://www.storm-consultancy.com/development/code-snippets/url-re-writing-in-asp-net-requires-form-action-to-be-re-written/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 13:16:50 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.storm-consultancy.com/blog/development/?p=417</guid>
		<description><![CDATA[On a project I was working on recently we ran into a problem where the combination of URL re-writing and  postbacks caused the page to post back to the wrong URL.  When you create an ASP.NET page with a &#60;form runat="server"&#62; tag, ASP.NET will automatically output the action attribute to be the URL of the current page.  However, the URL that is used is not the original URL of the request, but instead the real URL of the page.  For example, when you are on the page "/services/web-design" the real request might be to "/services.aspx?service=web-design".  When you do a postback, you will be returned to the ugly URL.]]></description>
			<content:encoded><![CDATA[<p>On a project I was working on recently we ran into a problem where the combination of URL re-writing and  postbacks caused the page to post back to the wrong URL.  When you create an ASP.NET page with a &lt;form runat=&#8221;server&#8221;&gt; tag, ASP.NET will automatically output the action attribute to be the URL of the current page.  However, the URL that is used is not the original URL of the request, but instead the real URL of the page.  For example, when you are on the page &#8220;/services/web-design&#8221; the real request might be to &#8220;/services.aspx?service=web-design&#8221;.  When you do a postback, you will be returned to the ugly URL.</p>
<h3>Re-Writing the ASP.NET PostBack URL</h3>
<p>So, what do we do about this?  We use the ASP.NET Control Adapter framework to change the way the action attribute of our &lt;form&gt; tag is rendered.  This doesn&#8217;t require you to change any code on any pages, we are simply overriding a part of the standard ASP.NET page rendering pipeline which serves all pages.</p>
<p>To get started we need two things:</p>
<ol>
<li>A .browser file in the /App_Browsers directory of your application</li>
<li>A class which inherits ControlAdapter to do the work.</li>
</ol>
<p>First up, lets look at the contents of the browser file.  I&#8217;m calling mine Form.browser.</p>
<pre class="brush:xml">&lt;browsers&gt;
    &lt;browser refID="Default"&gt;
        &lt;controlAdapters&gt;
            &lt;adapter controlType="System.Web.UI.HtmlControls.HtmlForm"
                     adapterType="Storm.ControlAdapters.FormRewriteControlAdapter" /&gt;
        &lt;/controlAdapters&gt;
    &lt;/browser&gt;
&lt;/browsers&gt;</pre>
<p>In this file we are registering a new control adapter for the <code>HtmlForm</code> Control.  My adapter is in Storm&#8217;s common library for easy reuse across projects.</p>
<p>Next, lets take a look at the FormRewriteControlAdapter</p>
<pre class="brush:csharp">    using System.Web;
    using System.Web.UI;

    /// &lt;summary&gt;
    /// Used to rewrite the form action attribute when using URL re-writing to the
    /// RawUrl so we don't get in a big mess!
    /// &lt;/summary&gt;
    public class FormRewriteControlAdapter : System.Web.UI.Adapters.ControlAdapter
    {
        /// &lt;summary&gt;
        /// Override the render method
        /// &lt;/summary&gt;
        /// &lt;param name="writer"&gt;The text writer&lt;/param&gt;
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(new RewriteFormHtmlTextWriter(writer));
        }
    }</pre>
<p>There&#8217;s nothing terribly exciting here &#8211; we are inheriting <code>System.Web.UI.Adapters.ControlAdapter</code> and then simply call the base <code>Render</code> method with a custom <code>TextWriter</code> implementation.  So let&#8217;s move on and take a look inside the <code>TextWriter</code> and see how the magic happens:</p>
<pre class="brush:csharp">    /// &lt;summary&gt;
    /// The internal text writer to use in FormRewriteControlAdapter
    /// &lt;/summary&gt;
    public class RewriteFormHtmlTextWriter : HtmlTextWriter
    {
        /// &lt;summary&gt;
        /// Initializes a new instance of the RewriteFormHtmlTextWriter class
        /// &lt;/summary&gt;
        /// &lt;param name="writer"&gt;Html text writer&lt;/param&gt;
        public RewriteFormHtmlTextWriter(HtmlTextWriter writer)
            : base(writer)
        {
            this.InnerWriter = writer.InnerWriter;
        }

        /// &lt;summary&gt;
        /// Initializes a new instance of the RewriteFormHtmlTextWriter class
        /// &lt;/summary&gt;
        /// &lt;param name="writer"&gt;An IO text writer&lt;/param&gt;
        public RewriteFormHtmlTextWriter(System.IO.TextWriter writer)
            : base(writer)
        {
            this.InnerWriter = writer;
        }

        /// &lt;summary&gt;
        /// Do the actual attribute writing of the action attribute
        /// &lt;/summary&gt;
        /// &lt;param name="name"&gt;The name of the attribute&lt;/param&gt;
        /// &lt;param name="value"&gt;The value of the attribute&lt;/param&gt;
        /// &lt;param name="fEncode"&gt;Dont know&lt;/param&gt;
        public override void WriteAttribute(string name, string value, bool fEncode)
        {
            if (name.Equals("action"))
            {
                var context = HttpContext.Current;

                if (context.Items["ActionAlreadyWritten"] == null)
                {
                    // Set the action to the raw url
                    value = context.Request.RawUrl;
                    context.Items["ActionAlreadyWritten"] = true;
                }
            }

            base.WriteAttribute(name, value, fEncode);
        }
    }</pre>
<p>The key part here is the <code>WriteAttribute</code> method.  This is called for each attribute that appears on the &lt;form&gt; tag.  First we check to see if we are working on the &#8216;action&#8217; attribute and then check that we haven&#8217;t already written it.  Now we get to the good part.  We grab the <code>RawUrl</code> of the request &#8211; this should contain the Url that was first requested by the browser (i.e. our nice, clean re-written Url) &#8211; and overwrite the <code>value</code> parameter.  We then call the base WriteAttribute method with the new value and the ASP.NET rendering pipeline takes care of the rest.</p>
<p>Thanks to <a href="http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx" target="_blank">Scott Guthrie</a> for getting me started fixing this!  If you&#8217;re working in VB.NET, <a href="http://www.scottgu.com/blogposts/urlrewrite/UrlRewrite_HttpModule1.zip" target="_blank">Scott provided a sample project</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/development/code-snippets/url-re-writing-in-asp-net-requires-form-action-to-be-re-written/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>The Haversine Formula in C# and SQL: Distance between two points</title>
		<link>http://www.storm-consultancy.com/development/code-snippets/the-haversine-formula-in-c-and-sql/</link>
		<comments>http://www.storm-consultancy.com/development/code-snippets/the-haversine-formula-in-c-and-sql/#comments</comments>
		<pubDate>Mon, 17 May 2010 15:27:44 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Geolocation]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.storm-consultancy.com/blog/development/?p=399</guid>
		<description><![CDATA[Storm was recently asked to create a local office finder for a client.  We used the Google Maps API to geo-locate the offices, storing their lat/lng co-ordinates in a database. Each time a customer performs a search for their town or post code we use the same process to their lat/lng co-ordinates as well.  Now we have the information we need, but how you find out which offices is closest to the customer?  We use the <a href="http://en.wikipedia.org/wiki/Haversine_formula" target="_blank">Haversine Formula</a>.]]></description>
			<content:encoded><![CDATA[<p>Storm was recently asked to create a local office finder for a client.  We used the <a href="http://www.storm-consultancy.com/blog/development/code-snippets/using-google-maps-api-to-get-latitude-longitude-co-ordinates-from-postcode-or-address" target="_blank">Google Maps API to geo-locate the offices</a>, storing their lat/lng co-ordinates in a database.  Each time a customer performs a search for their town or post code we use the same process to their lat/lng co-ordinates as well.  Now we have the information we need, but how you find out which offices is closest to the customer?  We use the <a href="http://en.wikipedia.org/wiki/Haversine_formula" target="_blank">Haversine Formula</a>.</p>
<p>As you can see if you visit the WikiPedia page, it&#8217;s not a simple formula!  However, it is beautifully elegant and a very fast solution to the problem.</p>
<p>During the course of development we worked on two versions of the code. Our first iteration had the office co-ordinates stored in an SQL Server database, later we moved to keeping them in an in-memory List&lt;T&gt;.  Below are both versions of the code to calculate the Haversine distance.</p>
<h3>MS SQL Server</h3>
<pre class="brush: sql">SELECT TOP 1 *, ( 3960 * acos( cos( radians( @custLat ) ) *
  cos( radians( Lat ) ) * cos( radians(  Lng  ) - radians( @custLng ) ) +
  sin( radians( @custLat ) ) * sin( radians(  Lat  ) ) ) ) AS Distance
FROM Offices
ORDER BY Distance ASC</pre>
<p>@custLat and @custLng are the variable co-ordinates of the customer.  Lat and Lng are the fields of the database table in which we have stored the office co-ordinates.  The above code calculates the distance in miles, if you want the answer in kilometers you need to replace <strong>3960</strong> with <strong>6371</strong>.  This could be parameterised in a Stored Procedure if you were feeling adventurous &#8211; there are plenty of example of this on the web already.</p>
<h3>C#</h3>
<p>In the following C# example, we use a simple enum to specify the unit of distance.  We also need to convert the latitude and longitude from degrees to radians. We created a simple <a href="http://www.storm-consultancy.com/blog/development/code-snippets/convert-an-angle-in-degrees-to-radians-in-c/" target="_blank">extension method</a> for the double type to do this conversion.</p>
<pre class="brush: csharp">    /// &lt;summary&gt;
    /// Returns the distance in miles or kilometers of any two
    /// latitude / longitude points.
    /// &lt;/summary&gt;
    /// &lt;param name="pos1"&gt;Location 1&lt;/param&gt;
    /// &lt;param name="pos2"&gt;Location 2&lt;/param&gt;
    /// &lt;param name="unit"&gt;Miles or Kilometers&lt;/param&gt;
    /// &lt;returns&gt;Distance in the requested unit&lt;/returns&gt;
    public double HaversineDistance(LatLng pos1, LatLng pos2, DistanceUnit unit)
    {
        double R = (unit == DistanceUnit.Miles) ? 3960 : 6371;
        var lat = (pos2.Latitude - pos1.Latitude).ToRadians();
        var lng = (pos2.Longitude - pos1.Longitude).ToRadians();
        var h1 = Math.Sin(lat / 2) * Math.Sin(lat / 2) +
                      Math.Cos(pos1.Latitude.ToRadians()) * Math.Cos(pos2.Latitude.ToRadians()) *
                      Math.Sin(lng / 2) * Math.Sin(lng / 2);
        var h2 = 2 * Math.Asin(Math.Min(1, Math.Sqrt(h1)));
        return R * h2;
    }

    public enum DistanceUnit { Miles, Kilometers };</pre>
<p>A simple helper class is used to pass around Longitude / Latitude co-ordinates:</p>
<pre class="brush: csharp">    /// &lt;summary&gt;
    /// Specifies a Latitude / Longitude point.
    /// &lt;/summary&gt;
    public class LatLng
    {
        public double Latitude { get; set; }
        public double Longitude { get; set; }

        public LatLng(){
        }

        public LatLng(double lat, double lng)
        {
            this.Latitude = lat;
            this.Longitude = lng;
        }
    }</pre>
<p>To use the function to perform the search we grab an array of offices, loop over them calculating the distance to the customer and use LINQ to select the closest office.</p>
<pre class="brush: csharp">    var Offices = GetMyOfficeList();
    for(int i = 0; i&lt; Offices.Count; i++)
    {
        Offices[i].Distance = HaversineDistance(
                                coord,
                                new LatLng(Offices[i].Lat, Offices[i].Lng),
                                DistanceUnit.Miles);
    }

    var closestOffice = Offices.OrderBy(x =&gt; x.Distance).Take(1).Single();</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/development/code-snippets/the-haversine-formula-in-c-and-sql/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using the Google Maps API to get long/lat co-ordinates from a postcode or address</title>
		<link>http://www.storm-consultancy.com/development/code-snippets/using-google-maps-api-to-get-latitude-longitude-co-ordinates-from-postcode-or-address/</link>
		<comments>http://www.storm-consultancy.com/development/code-snippets/using-google-maps-api-to-get-latitude-longitude-co-ordinates-from-postcode-or-address/#comments</comments>
		<pubDate>Mon, 17 May 2010 15:27:41 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Geolocation]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.storm-consultancy.com/blog/development/?p=398</guid>
		<description><![CDATA[Storm were recently asked to create a local office finder for franchised business VoIP provider, <a href="http://www.datasharp.co.uk/Local-Offices" target="_blank">Datasharp</a>. The client requested that the user should be able to enter their postcode or town/city and be informed where their nearest branch was. To make this possible we would need the latitude and longitude co-ordinates for each office and the customer, but how do you get the co-ordinates from the address?]]></description>
			<content:encoded><![CDATA[<p>Storm were recently asked to create a local office finder for franchised business VoIP provider, <a href="http://www.datasharp.co.uk/Local-Offices" target="_blank">Datasharp</a>.  The client requested that the user should be able to enter their postcode or town/city and be informed where their nearest branch was.  To make this possible we would need the latitude and longitude co-ordinates for each office and the customer, but how do you get the co-ordinates from the address?</p>
<h3>Using the Google Maps API</h3>
<p><strong>Note:</strong> To make use of the example in the post you will need to sign-up for a free <a href="http://code.google.com/apis/maps/signup.html" target="_blank">Google Maps API Key</a>.</p>
<p>The following example is written in C#, but it can be converted to any language fairly trivially as we are actually only making an HTTP request and parsing the result.</p>
<p>We use a little helper class to hold a latitude/longitude co-ordinate.</p>
<pre class="brush: csharp">public class LatLng
{
    public double Latitude {get;set;}
    public double Longitude {get;set;

    public LatLng(){
    }

    public LatLng(double lat, double lng)
    {
        this.Latitude = lat;
        this.Longitude = lng;
    }
}</pre>
<p>We&#8217;ve packaged the function to get the co-ordinates in a helper class so that we can add extra Google Maps functionality if required.  It also allows us to reuse the code across multiple projects as the API key is not hard coded.</p>
<pre class="brush: csharp">    using System;
    using System.IO;
    using System.Net;
    using System.Web;
    using Storm.Common.Utils.Extensions;

    public class GoogleMaps
    {
        private string API_KEY = string.Empty;

        public GoogleMaps(string api_key)
        {
            this.API_KEY = api_key;
        }

        public void SetApiKey(string key)
        {
            if (key.IsNullOrEmpty())
            {
                throw new ArgumentException("API Key is invalid");
            }

            this.API_KEY = key;
        }

        /// &lt;summary&gt;
        /// Perform a geocode lookup of an address
        /// &lt;/summary&gt;
        /// &lt;param name="addr"&gt;The address in CSV form line1, line2, postcode&lt;/param&gt;
        /// &lt;param name="output"&gt;CSV or XML&lt;/param&gt;
        /// &lt;returns&gt;LatLng object&lt;/returns&gt;
        public LatLng GetLatLng(string addr)
        {
            var url = "http://maps.google.co.uk/maps/geo?output=csv&amp;key=" +
                       this.API_KEY + "&amp;q=" + HttpContext.Current.Server.UrlEncode(addr);

            var request = WebRequest.Create(url);
            var response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {

                var ms = new MemoryStream();
                var responseStream = response.GetResponseStream();

                var buffer = new Byte[2048];
                int count = responseStream.Read(buffer, 0, buffer.Length);

                while (count &gt; 0)
                {
                    ms.Write(buffer, 0, count);
                    count = responseStream.Read(buffer, 0, buffer.Length);
                }

                responseStream.Close();
                ms.Close();

                var responseBytes = ms.ToArray();
                var encoding = new System.Text.ASCIIEncoding();

                var coords = encoding.GetString(responseBytes);
                var parts = coords.Split(",");

                return new LatLng(
                              Convert.ToDouble(parts[2]),
                              Convert.ToDouble(parts[3]));
            }

            return null;
        }
    }</pre>
<p>Let&#8217;s talk through whats going on.  First up, the boring bit:</p>
<pre class="brush: csharp">        private string API_KEY = string.Empty;

        public GoogleMaps(string api_key)
        {
            this.API_KEY = api_key;
        }

        public void SetApiKey(string key)
        {
            if (key.IsNullOrEmpty())
            {
                throw new ArgumentException("API Key is invalid");
            }

            this.API_KEY = key;
        }</pre>
<p>Here we have a private field to store the Maps API key required to issue a request.  The key can be set either through the constructor or by using the SetApiKey() function.</p>
<p>Now lets see how we use this in the lookup function.</p>
<pre class="brush: csharp">            var url = "http://maps.google.co.uk/maps/geo?output=csv&amp;key=" +
                       this.API_KEY + "&amp;q=" + HttpContext.Current.Server.UrlEncode(addr);

            var request = WebRequest.Create(url);
            var response = (HttpWebResponse)request.GetResponse();</pre>
<p>First, we build the a URL which represents the request we want to make.  The output param sets the format Google will return the results, here we have chosen CSV but you can also get JSON if you wish.  Next we include our API key to identify ourselves.  Finally, we pass the address we are searching for.</p>
<p>Using this URL we create a WebRequest and call GetResponse to fetch the page contents.  Before we go any further we check that the result was returned successfully:</p>
<pre class="brush: csharp">if (response.StatusCode == HttpStatusCode.OK)</pre>
<p>Now we have another boring bit which reads the result of the web request into a byte array and converts the result into an ASCII encoded string</p>
<pre class="brush: csharp">                var ms = new MemoryStream();
                var responseStream = response.GetResponseStream();

                var buffer = new Byte[2048];
                int count = responseStream.Read(buffer, 0, buffer.Length);

                while (count &gt; 0)
                {
                    ms.Write(buffer, 0, count);
                    count = responseStream.Read(buffer, 0, buffer.Length);
                }

                responseStream.Close();
                ms.Close();

                var responseBytes = ms.ToArray();
                var encoding = new System.Text.ASCIIEncoding();

                var coords = encoding.GetString(responseBytes);</pre>
<p>This string should look something like:</p>
<pre>200,5,51.2268219,-2.4646913</pre>
<p>We are interested in the 3rd and 4th values &#8211; the latitude and longitude. So, we split the string at the comma separator, create a new LatLng object and return the result:</p>
<pre class="brush: csharp">        var parts = coords.Split(",");
        return new LatLng(Convert.ToDouble(parts[2]), Convert.ToDouble(parts[3]));</pre>
<p>I hope this tutorial has proven useful and that you can go away and develop some cool apps!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/development/code-snippets/using-google-maps-api-to-get-latitude-longitude-co-ordinates-from-postcode-or-address/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Convert an angle in Degrees to Radians in C#</title>
		<link>http://www.storm-consultancy.com/development/code-snippets/convert-an-angle-in-degrees-to-radians-in-c/</link>
		<comments>http://www.storm-consultancy.com/development/code-snippets/convert-an-angle-in-degrees-to-radians-in-c/#comments</comments>
		<pubDate>Mon, 17 May 2010 15:27:40 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Maths]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.storm-consultancy.com/blog/development/?p=397</guid>
		<description><![CDATA[I was recently using <a href="http://www.storm-consultancy.com/blog/development/code-snippets/using-google-maps-api-to-get-latitude-longitude-co-ordinates-from-postcode-or-address" target="_blank">Google Maps API geo-location lookups to get the longitude and latitude</a> of an address entered by the user.  I wanted to find the distance between a two co-ordinates using the <a href="http://www.storm-consultancy.com/blog/development/code-snippets/the-haversine-formula-in-c-and-sql" target="_blank">Haversine Formula</a>.  To do this I needed to convert my lat/lng co-ordinates into radians.  This seemed like an excellent opportunity to create a new extension method to add to <a href="http://www.storm-consultancy.com" target="_blank">Storm</a>'s library of re-usable code.]]></description>
			<content:encoded><![CDATA[<p>I was recently using <a href="http://www.storm-consultancy.com/blog/development/code-snippets/using-google-maps-api-to-get-latitude-longitude-co-ordinates-from-postcode-or-address" target="_blank">Google Maps API geo-location lookups to get the longitude and latitude</a> of an address entered by the user.  I wanted to find the distance between a two co-ordinates using the <a href="http://www.storm-consultancy.com/blog/development/code-snippets/the-haversine-formula-in-c-and-sql" target="_blank">Haversine Formula</a>.  To do this I needed to convert my lat/lng co-ordinates into radians.  This seemed like an excellent opportunity to create a new extension method to add to <a href="http://www.storm-consultancy.com" target="_blank">Storm</a>&#8216;s library of re-usable code.</p>
<p>The maths to convert an angle from degrees to radians is really quite simple:</p>
<pre>(pi / 180) * angle</pre>
<p>We can take this simple equation and create either a simple function, or a convenient extension method.</p>
<h3>C# Function</h3>
<pre class="brush: csharp">    public double ConvertToRadians(double angle)
    {
        return (Math.PI / 180) * angle;
    }</pre>
<h3>C# Extension Method</h3>
<pre class="brush: csharp">    /// &lt;summary&gt;
    /// Convert to Radians.
    /// &lt;/summary&gt;
    /// &lt;param name="val"&gt;The value to convert to radians&lt;/param&gt;
    /// &lt;returns&gt;The value in radians&lt;/returns&gt;
    public static class NumericExtensions
    {
        public static double ToRadians(this double val)
        {
            return (Math.PI / 180) * val;
        }
    }</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/development/code-snippets/convert-an-angle-in-degrees-to-radians-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Archive of Related Entries with Movable Type</title>
		<link>http://www.storm-consultancy.com/development/code-snippets/archive-of-related-entries-with-movable-type/</link>
		<comments>http://www.storm-consultancy.com/development/code-snippets/archive-of-related-entries-with-movable-type/#comments</comments>
		<pubDate>Tue, 26 Feb 2008 14:40:25 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.izonedesign.co.uk/blog/movable-type/archive-of-related-entries-with-movable-type/</guid>
		<description><![CDATA[Recently, I have been working on a Movable Type based website for monthly research data. We found that we needed to create a sidebar module displaying monthly entries grouped by year. After some head scratching I came up with the following MT4 code. &#60;MTSetVarBlock name="category"&#62;&#60;MTEntryCategory&#62;&#60;/MTSetVarBlock&#62; &#60;h3&#62;Historic Data&#60;/h3&#62; &#60;$MTSetVar name="year" value="0"$&#62; &#60;MTEntries sort_order="descend" category="$category"&#62; &#60;MTIfNotEqual a="[MTEntryDate [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I have been working on a Movable Type based website for monthly research data.  We found that we needed to create a sidebar module displaying monthly entries grouped by year.  After some head scratching I came up with the following MT4 code.</p>
<p><span id="more-25"></span></p>
<pre class="brush: plain">&lt;MTSetVarBlock name="category"&gt;&lt;MTEntryCategory&gt;&lt;/MTSetVarBlock&gt;

&lt;h3&gt;Historic Data&lt;/h3&gt;

&lt;$MTSetVar name="year" value="0"$&gt;

&lt;MTEntries sort_order="descend" category="$category"&gt;

&lt;MTIfNotEqual a="[MTEntryDate format='%Y']" b="[MTGetVar name='year']"&gt;
  &lt;MTIfNotEqual a="[MTGetVar name='year']" b="0"&gt;&lt;/ul&gt;&lt;/MTIfNotEqual&gt;
  &lt;h4&gt;&lt;$MTEntryDate format="%Y"$&gt;&lt;/h4&gt;&lt;ul&gt;
  &lt;MTSetVarBlock name="year"&gt;&lt;$MTEntryDate format="%Y"$&gt;&lt;/MTSetVarBlock&gt;
&lt;/MTIfNotEqual&gt;

&lt;li&gt;&lt;a href="&lt;$MTEntryPermalink$&gt;"&gt;&lt;$MTEntryTitle$&gt;&lt;/a&gt;&lt;/li&gt;

&lt;/MTEntries&gt;</pre>
<p>This code sets a variable, $category, containing the name of the category associated with the current entry.  It then selects all the entries in this category in descending date order.  A $year variable then tracks the year of the last entry, printing out a heading when the year changes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/development/code-snippets/archive-of-related-entries-with-movable-type/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

