<?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 Development Blog &#187; Code Snippets</title>
	<atom:link href="http://www.storm-consultancy.com/blog/development/category/code-snippets/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.storm-consultancy.com/blog/development</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Fri, 18 Jun 2010 09:00:38 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Scroll an element into view programmatically with JavaScript</title>
		<link>http://www.storm-consultancy.com/blog/development/code-snippets/scroll-an-element-into-view-programmatically-with-javascript/</link>
		<comments>http://www.storm-consultancy.com/blog/development/code-snippets/scroll-an-element-into-view-programmatically-with-javascript/#comments</comments>
		<pubDate>Mon, 14 Jun 2010 15:53:23 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.storm-consultancy.com/blog/development/?p=396</guid>
		<description><![CDATA[<p>I've just finished building an FAQ section for one of <a href="http://www.storm-consultancy.com" target="_blank">Storm</a>'s clients. The client requested that a list of questions be shown at the top of the page and the user be scrolled to the appropriate answer when they clicked the question. The site was using a URL re-writing scheme that meant using traditional #anchor links was impossible. We got around this by using a very simple piece of JavaScript.</p>
]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just finished building an FAQ section for one of <a href="http://www.storm-consultancy.com" target="_blank">Storm</a>&#8217;s clients.  The client requested that a list of questions be shown at the top of the page and the user be scrolled to the appropriate answer when they clicked the question.  The site was using a URL re-writing scheme that meant using traditional #anchor links was impossible. We got around this by using a very simple piece of JavaScript.</p>
<pre class="brush:js">document.getElementById('MyID').scrollIntoView(true);</pre>
<p>This method will jump you straight to the top of the element with Id <code>MyID</code>.  If you want to animate the scroll down the page, then a simple little bit of <a title="JQuery" rel="homepage" href="http://jquery.com/" target="_blank">jQuery</a> will give the right effect.</p>
<pre class="brush:js">$("#my-link-id").click(
    function()
    {
        $('html:not(:animated), body:not(:animated)').animate({
            scrollTop: $("#scrollToHere").offset().top
        }, 2000);
    }
);</pre>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"></div>


<div class="taggington"><p><!--<img src="/blog/wp-content/themes/stormblog/images/tag.gif" alt="tag"/>&nbsp; -->Tagged in: &nbsp;<a href="http://www.storm-consultancy.com/blog/development/tag/javascript/" rel="tag">JavaScript</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/jquery/" rel="tag">JQuery</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/tutorials/" rel="tag">Tutorials</a></p></div><div class="relatedpostplugin">
<h3>You may also be interested in...</h3>
<div class="relatedlinks">
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/execute-javascript-when-an-updatepanel-is-updated/" rel="bookmark" title="Execute JavaScript when an UpdatePanel is updated">Execute JavaScript when an UpdatePa...</a><!-- (8.0298)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/sending-email-with-gmail-smtp-server-in-asp-net/" rel="bookmark" title="Sending email with GMail&#8217;s SMTP server in ASP.NET">Sending email with GMail&#8217;s SM...</a><!-- (4.57414)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/convert-an-angle-in-degrees-to-radians-in-c/" rel="bookmark" title="Convert an angle in Degrees to Radians in C#">Convert an angle in Degrees to Radi...</a><!-- (4.02695)--></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/blog/development/code-snippets/scroll-an-element-into-view-programmatically-with-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Prevent a C# or VB.NET Console Application from closing when it finishes</title>
		<link>http://www.storm-consultancy.com/blog/development/code-snippets/prevent-a-c-or-vb-net-console-application-from-closing-when-it-finishes/</link>
		<comments>http://www.storm-consultancy.com/blog/development/code-snippets/prevent-a-c-or-vb-net-console-application-from-closing-when-it-finishes/#comments</comments>
		<pubDate>Tue, 08 Jun 2010 10:17:51 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.storm-consultancy.com/blog/development/?p=586</guid>
		<description><![CDATA[I'm working on a little console application to run a scheduled data import task.  During the debugging of the application I wanted the console window to remain open after the program had finished executing - by default it closes when the application finishes.  There seem to be two common answers to this problem.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working on a little console application to run a scheduled data import task.  During the debugging of the application I wanted the console window to remain open after the program had finished executing &#8211; by default it closes when the application finishes.  There seem to be two common answers to this problem.</p>
<p>The first solution is to run the application without debugging by using Ctrl+F5 instead of just F5.  The console window will remain open when the program has finished.  The disadvantage of this is that you lose Visual Studio&#8217;s debug information.</p>
<p>The second solution is to add a couple lines of code to the end of your <code>Main()</code> method which halts the application until the user presses a key.  This allows you to run in Visual Studio&#8217;s Debug mode but requires a change to the code that you might not want in a production environment.</p>
<pre class="brush:csharp">Console.WriteLine("Press any key to close");
Console.ReadKey();</pre>
<p>Neither solution is perfect, but they both solve the problem well enough to let me get on with development.</p>


<div class="taggington"><p><!--<img src="/blog/wp-content/themes/stormblog/images/tag.gif" alt="tag"/>&nbsp; -->Tagged in: &nbsp;<a href="http://www.storm-consultancy.com/blog/development/tag/c/" rel="tag">C#</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/visual-studio/" rel="tag">Visual Studio</a></p></div><div class="relatedpostplugin">
<h3>You may also be interested in...</h3>
<div class="relatedlinks">
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/perl-print-internal-server-errors-to-the-browser/" rel="bookmark" title="Perl: Print Internal Server Errors to the Browser">Perl: Print Internal Server Errors ...</a><!-- (7.92545)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/tutorials/secure-your-contact-form-against-spam-email-header-injection/" rel="bookmark" title="Prevent Contact Form Spam Email Header Injection">Prevent Contact Form Spam Email Hea...</a><!-- (4.25181)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/sending-email-with-gmail-smtp-server-in-asp-net/" rel="bookmark" title="Sending email with GMail&#8217;s SMTP server in ASP.NET">Sending email with GMail&#8217;s SM...</a><!-- (3.71988)--></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/blog/development/code-snippets/prevent-a-c-or-vb-net-console-application-from-closing-when-it-finishes/feed/</wfw:commentRss>
		<slash:comments>4</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/blog/development/code-snippets/url-re-writing-in-asp-net-requires-form-action-to-be-re-written/</link>
		<comments>http://www.storm-consultancy.com/blog/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>


<div class="taggington"><p><!--<img src="/blog/wp-content/themes/stormblog/images/tag.gif" alt="tag"/>&nbsp; -->Tagged in: &nbsp;<a href="http://www.storm-consultancy.com/blog/development/tag/asp-net/" rel="tag">ASP.NET</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/code/" rel="tag">Code</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/tutorials/" rel="tag">Tutorials</a></p></div><div class="relatedpostplugin">
<h3>You may also be interested in...</h3>
<div class="relatedlinks">
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/sending-email-with-gmail-smtp-server-in-asp-net/" rel="bookmark" title="Sending email with GMail&#8217;s SMTP server in ASP.NET">Sending email with GMail&#8217;s SM...</a><!-- (7.98375)--><br /> 
<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/" rel="bookmark" title="Using the Google Maps API to get long/lat co-ordinates from a postcode or address">Using the Google Maps API to get lo...</a><!-- (7.44935)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/tools-plugins/getting-started-with-elmah-asp-net-error-logging-and-reporting/" rel="bookmark" title="Getting started with ELMAH: ASP.NET Error Logging and Reporting">Getting started with ELMAH: ASP.NET...</a><!-- (7.22703)--></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/blog/development/code-snippets/url-re-writing-in-asp-net-requires-form-action-to-be-re-written/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Execute JavaScript when an UpdatePanel is updated</title>
		<link>http://www.storm-consultancy.com/blog/development/code-snippets/execute-javascript-when-an-updatepanel-is-updated/</link>
		<comments>http://www.storm-consultancy.com/blog/development/code-snippets/execute-javascript-when-an-updatepanel-is-updated/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 12:18:07 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.storm-consultancy.com/blog/development/?p=487</guid>
		<description><![CDATA[I've just spent a few hours banging my head against a wall trying to get ASP.NET to execute a JavaScript function each time an UpdatePanel is updated. Simply putting the script within the ContentTemplate tags does not work.  Instead, to get the JavaScript to execute on PostBack you need to use <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerstartupscript.aspx" target="_blank">ScriptManager.RegisterStartupScript</a> to register the script to be run.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just spent a few hours banging my head against a wall trying to get ASP.NET to execute a JavaScript function each time an UpdatePanel is updated. Simply putting the script within the ContentTemplate tags does not work.  Instead, to get the JavaScript to execute on PostBack you need to use <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerstartupscript.aspx" target="_blank">ScriptManager.RegisterStartupScript</a> to register the script to be run.</p>
<p>Let&#8217;s look at the code we need:</p>
<pre class="brush:csharp">protected void Page_Load(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(
                        upPanel,
                        this.GetType(),
                        "MyAction",
                        "doMyAction();",
                        true);
}</pre>
<p><code>RegisterStartupScript</code> is a static method on the <code>ScriptManager</code> class.  You do not need to have an actual <code>ScriptManager</code> in scope to call this function (for example, you might be coding within a UserControl and have the ScriptManager on the Page).</p>
<p>The first parameter is the UpdatePanel you want to associate the script with.  The second parameter is a type parameter, we&#8217;ll just use the type of the current object for this.  Now we get to the interesting bits.  The third parameter, &#8220;MyAction&#8221;, is a key to identify the script, allowing you to reference or update it in the future if you wish.  Next we have the script itself.  This can be a block of inline JavaScript but I prefer to wrap everything I want to happen in a function and call that instead.   The final parameter is a flag to indicate whether the ScriptManager should wrap your code in script tags.   You can do this manually if you want, but I prefer to set this flag to true and let somebody else worry about it.</p>
<p>ASP.NET will output the following code at the bottom of your page and execute it on PostBack. Provided you have defined the function doMyAction() somewhere everything should work as you expect.</p>
<pre class="brush: js">&lt;script type="text/javascript"&gt;
    doMyAction();
&lt;/script&gt;</pre>
<p>If you set the final parameter to false you would get the following:</p>
<pre class="brush: js">    doMyAction();</pre>
<p>You can pass variables from your C# code to your JavaScript by including them in your function call:</p>
<pre class="brush:csharp">protected void Page_Load(object sender, EventArgs e)
{
    int myVar = 5;
    ScriptManager.RegisterStartupScript(
                        upPanel,
                        this.GetType(),
                        "MyAction",
                        "doMyAction(" + myVar + ");",
                        true);
}</pre>
<p>We&#8217;d then get the following output:</p>
<pre class="brush: js">&lt;script type="text/javascript"&gt;
    doMyAction(5);
&lt;/script&gt;</pre>


<div class="taggington"><p><!--<img src="/blog/wp-content/themes/stormblog/images/tag.gif" alt="tag"/>&nbsp; -->Tagged in: &nbsp;<a href="http://www.storm-consultancy.com/blog/development/tag/asp-net/" rel="tag">ASP.NET</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/asp-net-ajax/" rel="tag">ASP.NET AJAX</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/javascript/" rel="tag">JavaScript</a></p></div><div class="relatedpostplugin">
<h3>You may also be interested in...</h3>
<div class="relatedlinks">
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/scroll-an-element-into-view-programmatically-with-javascript/" rel="bookmark" title="Scroll an element into view programmatically with JavaScript">Scroll an element into view program...</a><!-- (7.20792)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/tutorials/overriding-maintainscrollpositiononpostback-with-gridview-pager-links/" rel="bookmark" title="Overriding maintainScrollPositionOnPostBack with GridView Pager links">Overriding maintainScrollPositionOn...</a><!-- (4.5562)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/url-re-writing-in-asp-net-requires-form-action-to-be-re-written/" rel="bookmark" title="URL Re-Writing in ASP.NET Requires Form Action to be Re-written">URL Re-Writing in ASP.NET Requires ...</a><!-- (4.36693)--></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/blog/development/code-snippets/execute-javascript-when-an-updatepanel-is-updated/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using SQLite with NHibernate for Unit Testing</title>
		<link>http://www.storm-consultancy.com/blog/development/code-snippets/using-sqlite-with-nhibernate-for-unit-testing/</link>
		<comments>http://www.storm-consultancy.com/blog/development/code-snippets/using-sqlite-with-nhibernate-for-unit-testing/#comments</comments>
		<pubDate>Wed, 26 May 2010 10:23:16 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[SQLite]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://www.storm-consultancy.com/blog/development/?p=521</guid>
		<description><![CDATA[<img class="alignleft" title="SQLite Logo" src="http://upload.wikimedia.org/wikipedia/commons/thumb/c/cc/SQLite_Logo.svg/300px-SQLite_Logo.svg.png" alt="SQLite Logo, SVG version" width="200" height="59" />Fast, automated <a title="Unit testing" rel="wikipedia" href="http://en.wikipedia.org/wiki/Unit_testing" target="_blank">unit testing</a> is a vital component of any development project.  At Storm we use <a title="NUnit" rel="homepage" href="http://www.nunit.org/" target="_blank">NUnit</a> with <a href="http://www.testdriven.net/" target="_blank">TestDriven.NET</a> from within Visual Studio to run our test suites as we develop.  We also use <a title="NHibernate" rel="homepage" href="http://www.nhforge.org/" target="_blank">NHibernate</a> with SQL Server for the data access layer of our applications.  To ensure each of our unit tests is atomic it is necessary to setup and teardown a new copy of the database for each test or series of tests.  With an SQL Server instance of a seperate box, this can be painfully slow once your test library reaches even a moderate size.  To speed things up, we've moved to in-memory <a title="SQLite" rel="homepage" href="http://sqlite.org/" target="_blank">SQLite</a>.  Here's how!]]></description>
			<content:encoded><![CDATA[<p>Fast, automated <a title="Unit testing" rel="wikipedia" href="http://en.wikipedia.org/wiki/Unit_testing" target="_blank">unit testing</a> is a vital component of any development project.  At Storm we use <a title="NUnit" rel="homepage" href="http://www.nunit.org/" target="_blank">NUnit</a> with <a href="http://www.testdriven.net/" target="_blank">TestDriven.NET</a> from within Visual Studio to run our test suites as we develop.  We also use <a title="NHibernate" rel="homepage" href="http://www.nhforge.org/" target="_blank">NHibernate</a> with SQL Server for the data access layer of our applications.  To ensure each of our unit tests is atomic it is necessary to setup and teardown a new copy of the database for each test or series of tests.  With an SQL Server instance of a seperate box, this can be painfully slow once your test library reaches even a moderate size.  To speed things up, we&#8217;ve moved to in-memory <a title="SQLite" rel="homepage" href="http://sqlite.org/" target="_blank">SQLite</a>.  Here&#8217;s how!</p>
<h3>Configuring hibernate.cfg.xml for SQLite</h3>
<p>You need to change your <strong>connection.driver_class</strong>, <strong>connection.connection_string</strong> and <strong>dialect </strong>to the SQLite specific values shown below.</p>
<pre class="brush:xml">&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" &gt;
  &lt;session-factory&gt;
    &lt;property name="connection.provider"&gt;
      NHibernate.Connection.DriverConnectionProvider
    &lt;/property&gt;
    &lt;property name="connection.driver_class"&gt;
      NHibernate.Driver.SQLite20Driver
    &lt;/property&gt;
    &lt;property name="connection.connection_string"&gt;
      Data Source=:memory:;Version=3;New=True;Pooling=True;Max Pool Size=1;
    &lt;/property&gt;    
    &lt;property name="adonet.batch_size"&gt;10&lt;/property&gt;
    &lt;property name="show_sql"&gt;true&lt;/property&gt;
    &lt;property name="dialect"&gt;NHibernate.Dialect.SQLiteDialect&lt;/property&gt;
    &lt;property name="use_outer_join"&gt;true&lt;/property&gt;
    &lt;property name="command_timeout"&gt;60&lt;/property&gt;
    &lt;property name="query.substitutions"&gt;true 1, false 0, yes 'Y', no 'N'&lt;/property&gt;
    &lt;property name="proxyfactory.factory_class"&gt;
      NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
    &lt;/property&gt;
  &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;</pre>
<p>That should be that.  Just make sure that you have System.Data.SQLite added as a reference to your test assembly.  You can download the compiled binary from <a href="http://sourceforge.net/projects/sqlite-dotnet2/files/" target="_blank">SourceForge</a>.  Make sure you select the correct version, x86 or x64!</p>
<p><strong>Warning: </strong>The first example I found on the net had the following driver_class:</p>
<pre>&lt;property name="connection.driver_class"&gt;NHibernate.Driver.SQLiteDriver&lt;/property&gt;</pre>
<p>This does not work with the lastest version of SQLite.  You need to use <strong>NHibernate.Driver.SQLite20Driver </strong>else you will get an exception similar to:</p>
<pre class="brush:xml">NHibernate.HibernateException : Could not create the driver from NHibernate.Driver.SQLiteDriver.  
----&gt; System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.  
----&gt; NHibernate.HibernateException : The IDbCommand and IDbConnection implementation in the assembly SQLite.NET
      could not be found. Ensure that the assembly SQLite.NET is located in the application directory or in the Global
      Assembly Cache. If the assembly is in the GAC, use &lt;qualifyAssembly/&gt; element in the application configuration file
      to specify the full name of the assembly.</pre>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"></div>


<div class="taggington"><p><!--<img src="/blog/wp-content/themes/stormblog/images/tag.gif" alt="tag"/>&nbsp; -->Tagged in: &nbsp;<a href="http://www.storm-consultancy.com/blog/development/tag/nhibernate/" rel="tag">NHibernate</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/sqlite/" rel="tag">SQLite</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/tutorials/" rel="tag">Tutorials</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/unit-testing/" rel="tag">Unit Testing</a></p></div><div class="relatedpostplugin">
<h3>You may also be interested in...</h3>
<div class="relatedlinks">
<a href="http://www.storm-consultancy.com/blog/development/tutorials/perl-basic-unit-testing/" rel="bookmark" title="Perl: Basic Unit Testing">Perl: Basic Unit Testing</a><!-- (9.40432)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/tools-plugins/getting-started-with-elmah-asp-net-error-logging-and-reporting/" rel="bookmark" title="Getting started with ELMAH: ASP.NET Error Logging and Reporting">Getting started with ELMAH: ASP.NET...</a><!-- (5.63378)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/perl-sorting-an-array-of-hashes/" rel="bookmark" title="Perl: Sorting an Array of Hashes">Perl: Sorting an Array of Hashes</a><!-- (4.83798)--></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/blog/development/code-snippets/using-sqlite-with-nhibernate-for-unit-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sending email with GMail&#8217;s SMTP server in ASP.NET</title>
		<link>http://www.storm-consultancy.com/blog/development/code-snippets/sending-email-with-gmail-smtp-server-in-asp-net/</link>
		<comments>http://www.storm-consultancy.com/blog/development/code-snippets/sending-email-with-gmail-smtp-server-in-asp-net/#comments</comments>
		<pubDate>Tue, 18 May 2010 20:30:03 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Mail]]></category>

		<guid isPermaLink="false">http://www.storm-consultancy.com/blog/development/?p=400</guid>
		<description><![CDATA[Sending email via SMTP in ASP.NET is a really painless experience.  However, there are a couple of hoops to jump through if you want to use Google's GMail SMTP servers.  The example in this post shows a really simple function to get the job done.]]></description>
			<content:encoded><![CDATA[<p>Sending email via SMTP in ASP.NET is a really painless experience.  However, there are a couple of hoops to jump through if you want to use Google&#8217;s GMail SMTP servers.  The following example shows a really simple function to get the job done.</p>
<p>The <a href="http://mail.google.com/support/bin/answer.py?hl=en&amp;answer=13287" target="_blank">Google support page</a> for configuring a mail client gives us a good starting point.  We can see that we need to use the host smtp.gmail.com on port 587.  We can also see that we must transmit over a secure connection and that we need to use our GMail username and password to authenticate with the server.</p>
<pre class="brush: csharp">using System.Net.Mail;

public class GMailSMTP
{
    public void Send(string to, string subject, string message, bool isHtml)
    {
            // Create a new message
            var mail = new MailMessage();

            // Set the to and from addresses.
            // The from address must be your GMail account
            mail.From = new MailAddress("example@gmail.com");
            mail.To.Add(new MailAddress(to));

            // Define the message
            mail.Subject = subject;
            mail.IsBodyHtml = isHtml;
            mail.Body = message;

            // Create a new Smpt Client using Google's servers
            var mailclient = new SmtpClient();
            mailclient.Host = "smtp.gmail.com";
            mailclient.Port = 587;

            // This is the critical part, you must enable SSL
            mailclient.EnableSsl = true;

            // Specify your authentication details
            mailclient.Credentials = new System.Net.NetworkCredential(
                                             "YOUR GMAIL USERNAME",
                                             "YOUR GMAIL PASSWORD");
            mailclient.Send(mail);
    }
}</pre>
<pre class="brush: csharp">That's all there is to it!</pre>


<div class="taggington"><p><!--<img src="/blog/wp-content/themes/stormblog/images/tag.gif" alt="tag"/>&nbsp; -->Tagged in: &nbsp;<a href="http://www.storm-consultancy.com/blog/development/tag/asp-net/" rel="tag">ASP.NET</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/c/" rel="tag">C#</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/mail/" rel="tag">Mail</a></p></div><div class="relatedpostplugin">
<h3>You may also be interested in...</h3>
<div class="relatedlinks">
<a href="http://www.storm-consultancy.com/blog/development/tools-plugins/setup-email-alerts-from-elmah-when-exceptions-are-raised/" rel="bookmark" title="Setup email alerts from ELMAH when exceptions are raised">Setup email alerts from ELMAH when ...</a><!-- (13.7482)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/tutorials/secure-your-contact-form-against-spam-email-header-injection/" rel="bookmark" title="Prevent Contact Form Spam Email Header Injection">Prevent Contact Form Spam Email Hea...</a><!-- (9.27887)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/url-re-writing-in-asp-net-requires-form-action-to-be-re-written/" rel="bookmark" title="URL Re-Writing in ASP.NET Requires Form Action to be Re-written">URL Re-Writing in ASP.NET Requires ...</a><!-- (8.08655)--></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/blog/development/code-snippets/sending-email-with-gmail-smtp-server-in-asp-net/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>The Haversine Formula in C# and SQL: Distance between two points</title>
		<link>http://www.storm-consultancy.com/blog/development/code-snippets/the-haversine-formula-in-c-and-sql/</link>
		<comments>http://www.storm-consultancy.com/blog/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>


<div class="taggington"><p><!--<img src="/blog/wp-content/themes/stormblog/images/tag.gif" alt="tag"/>&nbsp; -->Tagged in: &nbsp;<a href="http://www.storm-consultancy.com/blog/development/tag/c/" rel="tag">C#</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/code/" rel="tag">Code</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/geolocation/" rel="tag">Geolocation</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/tutorials/" rel="tag">Tutorials</a></p></div><div class="relatedpostplugin">
<h3>You may also be interested in...</h3>
<div class="relatedlinks">
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/convert-an-angle-in-degrees-to-radians-in-c/" rel="bookmark" title="Convert an angle in Degrees to Radians in C#">Convert an angle in Degrees to Radi...</a><!-- (18.7679)--><br /> 
<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/" rel="bookmark" title="Using the Google Maps API to get long/lat co-ordinates from a postcode or address">Using the Google Maps API to get lo...</a><!-- (15.6918)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/url-re-writing-in-asp-net-requires-form-action-to-be-re-written/" rel="bookmark" title="URL Re-Writing in ASP.NET Requires Form Action to be Re-written">URL Re-Writing in ASP.NET Requires ...</a><!-- (5.52104)--></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/blog/development/code-snippets/the-haversine-formula-in-c-and-sql/feed/</wfw:commentRss>
		<slash:comments>1</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/blog/development/code-snippets/using-google-maps-api-to-get-latitude-longitude-co-ordinates-from-postcode-or-address/</link>
		<comments>http://www.storm-consultancy.com/blog/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>


<div class="taggington"><p><!--<img src="/blog/wp-content/themes/stormblog/images/tag.gif" alt="tag"/>&nbsp; -->Tagged in: &nbsp;<a href="http://www.storm-consultancy.com/blog/development/tag/c/" rel="tag">C#</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/code/" rel="tag">Code</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/geolocation/" rel="tag">Geolocation</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/tutorials/" rel="tag">Tutorials</a></p></div><div class="relatedpostplugin">
<h3>You may also be interested in...</h3>
<div class="relatedlinks">
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/the-haversine-formula-in-c-and-sql/" rel="bookmark" title="The Haversine Formula in C# and SQL: Distance between two points">The Haversine Formula in C# and SQL...</a><!-- (14.3555)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/convert-an-angle-in-degrees-to-radians-in-c/" rel="bookmark" title="Convert an angle in Degrees to Radians in C#">Convert an angle in Degrees to Radi...</a><!-- (10.7486)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/url-re-writing-in-asp-net-requires-form-action-to-be-re-written/" rel="bookmark" title="URL Re-Writing in ASP.NET Requires Form Action to be Re-written">URL Re-Writing in ASP.NET Requires ...</a><!-- (9.70076)--></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/blog/development/code-snippets/using-google-maps-api-to-get-latitude-longitude-co-ordinates-from-postcode-or-address/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Convert an angle in Degrees to Radians in C#</title>
		<link>http://www.storm-consultancy.com/blog/development/code-snippets/convert-an-angle-in-degrees-to-radians-in-c/</link>
		<comments>http://www.storm-consultancy.com/blog/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>&#8217;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>


<div class="taggington"><p><!--<img src="/blog/wp-content/themes/stormblog/images/tag.gif" alt="tag"/>&nbsp; -->Tagged in: &nbsp;<a href="http://www.storm-consultancy.com/blog/development/tag/c/" rel="tag">C#</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/code/" rel="tag">Code</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/maths/" rel="tag">Maths</a>&nbsp;&nbsp; <a href="http://www.storm-consultancy.com/blog/development/tag/tutorials/" rel="tag">Tutorials</a></p></div><div class="relatedpostplugin">
<h3>You may also be interested in...</h3>
<div class="relatedlinks">
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/the-haversine-formula-in-c-and-sql/" rel="bookmark" title="The Haversine Formula in C# and SQL: Distance between two points">The Haversine Formula in C# and SQL...</a><!-- (16.5099)--><br /> 
<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/" rel="bookmark" title="Using the Google Maps API to get long/lat co-ordinates from a postcode or address">Using the Google Maps API to get lo...</a><!-- (10.1343)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/url-re-writing-in-asp-net-requires-form-action-to-be-re-written/" rel="bookmark" title="URL Re-Writing in ASP.NET Requires Form Action to be Re-written">URL Re-Writing in ASP.NET Requires ...</a><!-- (7.60927)--></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/blog/development/code-snippets/convert-an-angle-in-degrees-to-radians-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generic HashTable in C#</title>
		<link>http://www.storm-consultancy.com/blog/development/code-snippets/generic-hashtable-in-c/</link>
		<comments>http://www.storm-consultancy.com/blog/development/code-snippets/generic-hashtable-in-c/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 18:13:34 +0000</pubDate>
		<dc:creator>Adam Pope</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.izonedesign.co.uk/blog/?p=81</guid>
		<description><![CDATA[I had a bit of a brain fail earlier and couldn't remember how to create a &#60;strong&#62;HashTable&#60;/strong&#62; with generic type arguments. There was a Hashtable and a HashSet&#60;&#62; but neither were what I was looking for.]]></description>
			<content:encoded><![CDATA[<p>I had a bit of a brain fail earlier and couldn&#8217;t remember how to create a <strong>HashTable</strong> with generic type arguments. There was a Hashtable and a HashSet&lt;&gt; but neither were what I was looking for.  The answer was a <strong>Dictionary</strong>:</p>
<pre class="brush: csharp"> var myHashTable = new Dictionary&lt;TKey, TValue&gt;
</pre>
<p>Where TKey is the type of your key (possibly an int to represent the Id of your object or string for a username) and TValue is the type of the value. I hope that saves you some time!</p>


<div class="taggington"><p><!--<img src="/blog/wp-content/themes/stormblog/images/tag.gif" alt="tag"/>&nbsp; -->Tagged in: &nbsp;<a href="http://www.storm-consultancy.com/blog/development/tag/c/" rel="tag">C#</a></p></div><div class="relatedpostplugin">
<h3>You may also be interested in...</h3>
<div class="relatedlinks">
<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/" rel="bookmark" title="Using the Google Maps API to get long/lat co-ordinates from a postcode or address">Using the Google Maps API to get lo...</a><!-- (7.89256)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/sending-email-with-gmail-smtp-server-in-asp-net/" rel="bookmark" title="Sending email with GMail&#8217;s SMTP server in ASP.NET">Sending email with GMail&#8217;s SM...</a><!-- (6.88241)--><br /> 
<a href="http://www.storm-consultancy.com/blog/development/code-snippets/execute-javascript-when-an-updatepanel-is-updated/" rel="bookmark" title="Execute JavaScript when an UpdatePanel is updated">Execute JavaScript when an UpdatePa...</a><!-- (4.22053)--></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.storm-consultancy.com/blog/development/code-snippets/generic-hashtable-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
