<?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>Jayway Team Blog &#187; Cloud</title>
	<atom:link href="http://blog.jayway.com/category/cloud/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +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>WinRM w/ self-signed certificate in 4 steps</title>
		<link>http://blog.jayway.com/2011/11/21/winrm-w-self-signed-certificate-in-4-steps/</link>
		<comments>http://blog.jayway.com/2011/11/21/winrm-w-self-signed-certificate-in-4-steps/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 16:36:07 +0000</pubDate>
		<dc:creator>Henrik Feldt</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[devops]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11003</guid>
		<description><![CDATA[Targeted environment: Windows Server 2008 or Windows Server 2008 R2 You'll be self-signing with makecert from the Windows 7.1 SDK. The certificate tool is a single executable, specifically at %PROGRAMFILES%\Microsoft SDKs\Windows\v7.1\Bin\makecert.exe, per default. You'll need it - copy it to the server unless you already have the SDK installed on it. Secondly, you've got a [...]]]></description>
			<content:encoded><![CDATA[<p><em>Targeted environment: Windows Server 2008 or Windows Server 2008 R2</em></p>
<p>You'll be self-signing with <code>makecert</code> from the <a href="http://www.microsoft.com/download/en/details.aspx?id=8279" title="Download the 7.1 SDK for Windows">Windows 7.1 SDK</a>. The certificate tool is a single executable, specifically at <code>%PROGRAMFILES%\Microsoft SDKs\Windows\v7.1\Bin\makecert.exe</code>, per default.  You'll need it - copy it to the server unless you already have the SDK installed on it.</p>
<p>Secondly, you've got a domain name, <em>mydomain.com</em>. Otherwise, just substitute the IP in the following instructions.</p>
<p>Without further ado; on the <strong>SERVER</strong>:</p>
<ol>
<li>
<p>First, create the self-signed certificate with the regular cmd.exe:</p>
<p><code>makecert -sk "<strong title="This is the FQDN that you are securing">mydomain.com</strong>" -ss My -sr localMachine -r -n "CN=<strong title="This is who is the subject certificate name, the domain to secure">mydomain.com</strong>, O=<strong title="Fill out your company for O (Organisation)">Jayway Stockholm AB</strong>, L=<strong title="This is some real-world address of you, your company or your dog.">Drottninggatan 108 Stockholm</strong>" -a sha1 -eku "1.3.6.1.5.5.7.3.1"</code><br /><a href="http://msdn.microsoft.com/en-us/library/bfsktky3%28VS.80%29.aspx">(flags ref)</a></p>
<p>Substituting your own values.</p>
<p title="You can verify this visually by running mmc, then: CTRL+M &gt; Certificates &gt; Computer Account &gt; Personal &gt; Certificates &gt; mydomain.com in list.">This command will create a certificate for <em>Server Authentication</em> and save it in the certificate store for the local machine.</p>
<p>With powershell, get the thumbprint is for the generated certificate<code></p>
<p>ls cert:\LocalMachine\my</code></p>
<p>It'll look like this: <code>87B1C1818F1828958524A598B4131757EBAF4D35</code></p>
</li>
<li>
<p>Now, configure winrm (PowerShell needs escaping, so use cmd.exe):</p>
<p><code>winrm create winrm/config/listener?Address=IP:<strong title="Btw... don't use that IP, it's google's DNS-server ;)">8.8.8.8</strong>+Transport=HTTPS @{Hostname="<strong>mydomain.com</strong>";CertificateThumbprint="<strong title="The hash from above">87B1C1818F1828958524A598B4131757EBAF4D35</strong>";Port="5986"}</code></p>
<p>Again, substitute your variables.</p>
</li>
<li>
<p>Open port <b title="the previous is for HTTP by default">5986</b>, inbound TCP for all programs (and potentially restricted to your CI-server by IP), by going to Start &gt; Administrative Tools &gt; Windows Firewall with Advanced Security</p>
</li>
<li>Now, from the <strong>CLIENT</strong>, PowerShell:
<pre><code>$so = New-PsSessionOption -SkipCACheck
etsn -cn mydomain.com -Credential MyMachineName\YourUserName -UseSSL -SessionOption $so</code></pre>
<p>Answer the password dialog box, and you're in! Try running "whoami" to see the user name</li>
</ol>
<p>That's it. Congratulations. If you stay at this for a small-scale deployment you have OK security on your communication with WinRM! However, do check out some more details:</p>
<h2>More details</h2>
<p>On <code>makecert</code> and how to switch certificate for one signed by a trusted certificate authority.</p>
<h3><code>makecert</code> switches</h3>
<ol>
<li>
<p><code>-sk</code> says what the <em>Subject Key</em> name should be. This is like the 'user name for keys, i.e. a uniquely identifiable name for your key in the key store.</p>
</li>
<li>
<p><code>-ss</code> is the store's name. It's most often either <code>My</code> or <code>Root</code> depending on what you're using your certificate for.</p>
</li>
<li>
<p><code>-sr</code> is really just if it's a user-local store or the machine store that you are saving the key to. Has either value <em>currentUser</em> or <em>localMachine</em>.</p>
<li>
<p><code>-r</code> is for self-signing which is what we want.</p>
</li>
<li>
<p><code>-sn</code> stands for <em>Subject Name</em> and in this case our subject (what we want to authenticate and encrypt access to) is our domain.</p>
</li>
<li>
<p><code>-a</code> stands for <em>Algorithm</em> - default is md5 which is not much more secure than a 4-digit pin code on a post-it taped to an old man's wallet. <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/Attacking-MD5.pdf'>Ref: Attacking MD5</a>, <a href="https://www.google.com/search?hl=en&q=cuda%20amazon%20hash&aq=f&aqi=">ref 2</a></p>
</li>
</ol>
<h3>Changing Certificates</h3>
<p>Let's discuss what you do when you get a trusted-CA-signed certificate</p>
<h4>Justification</h4>
<p>So this works nicely for a while, until someone captures you laptop because you forgot it on the tube. Suddenly you can't revoke the certificate and you're in a world of pain of managing your keys (to be honest, this has never happened to me and this is already 1000x better than no authentication or basic unencrypted authentication!). Also, you grew a bit and have a few more servers to manage. Fine, let's upgrade WinRM's HTTPS certificate.</p>
<p>First, get the new one. I am personally involved in StartSSL.org, since I like the idea of free, community-driven crypto over the default server-taxation style type of certificates - this will also integrate finely with browser-based X.509 certificates if you're planning on adding an STS to your infrastructure and authenticating users with certificates rather than username/password combos</p>
<p>However, the world is a harsh place and we want <em title="You didn't think you were paying for a real person to do work, did you?">real humans in front of bots</em> to verify our identity for ultra security. We've used geotrust previously and have no real complaints.</p>
<h4>Too long, didn't read</h4>
<p>Use <a href="http://technet.microsoft.com/en-us/library/cc725793%28WS.10%29.aspx">certreq.exe</a> to generate the request, and install it on the server.</p>
<p>Once installed and visible through <code>ls cert://localmachine/my</code> in PowerShell, copy its thumbprint.</p>
<p>Then, you update the listener's binding (<strong>SERVER</strong>):</p>
<p><code>winrm set winrm/config/listener?Address=IP:<strong>8.8.8.8</strong>+Transport=HTTPS @{Hostname="<strong>mydomain.com</strong>";CertificateThumbprint="<strong>CB7434F35E3EA11D49D209F41BB16E96B472D30E</strong>";Port="5986"}</code></p>
<p>The <em>set</em> operation idempotently changes the listener's configuration to the hash presented inside the <code>@{}</code> hash syntax.</p>
<p>Now try it out (<strong>CLIENT</strong>):</p>
<p><code>etsn -cn mydomain.com -Credential MyMachineName\YourUserName -UseSSL</code></p>
<h3>What on earth is <code>etsn</code>?</h3>
<p>See for yourself! <code>Get-Alias etsn</code> in PowerShell</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/21/winrm-w-self-signed-certificate-in-4-steps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Azure Blob Storage &#8211; a simple example</title>
		<link>http://blog.jayway.com/2011/10/18/azure-blob-storage-a-simple-example/</link>
		<comments>http://blog.jayway.com/2011/10/18/azure-blob-storage-a-simple-example/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 05:22:00 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[azure]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10023</guid>
		<description><![CDATA[This is for all of you that just want a simple, up to date, example/how-to/tutorial of how to use Azure Blob Storage. You won’t see any screen shots or a lengthy guide on how to get started from scratch. Instead I will just focus on writing some code examples for general stuff that you might [...]]]></description>
			<content:encoded><![CDATA[<p>This is for all of you that just want a simple, up to date, example/how-to/tutorial of how to use Azure Blob Storage. You won’t see any screen shots or a lengthy guide on how to get started from scratch. Instead I will just focus on writing some code examples for general stuff that you might like to do. I will keep this simple and avoid getting into more advanced scenarios such as page blobs, VHD and leases. I’ll cover those in posts later on.</p>
<p>All examples below assume that we have already instantiated <a href="http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storageclient.cloudblobclient.aspx"><em>CloudBlobClient</em></a><em> cloudBlobClient</em>. It can be done using the code. </p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">var account = CloudStorageAccount.FromConfigurationSetting(&quot;DataConnectionString&quot;);
var cloudBlobClient = account.CreateCloudBlobClient();</pre>
<h2>Upload a Blob from a string</h2>
<p>First example, upload a string as a text file. We, for example, use this to upload crash logs to blob storage and then mail a link to the support team. </p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public Uri UploadBlob(string path, string fileName, string content)
{
    var cloudBlobContainer = cloudBlobClient.GetContainerReference(path);
    cloudBlobContainer.CreateIfNotExist();

    var blob = cloudBlobContainer.GetBlobReference(fileName);
    blob.UploadText(content);

    return blob.Uri;
}</pre>
<p>So if we would call this method using the following parameters. </p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">var uri = UploadBlob(&quot;folder&quot;, &quot;file.txt&quot;, &quot;text in file&quot;);</pre>
<p>We would get a link pointing at <a href="http://yourstorageaccount.blob.core.windows.net/folder/file.txt">http://yourstorageaccount.blob.core.windows.net/folder/file.txt</a> containing the text – “text in file”. Please note that this call is made synchronously. </p>
<h2>Upload a Blob from a stream</h2>
<p>You will recognize this from the previous example. The difference is that we are using a <a href="http://msdn.microsoft.com/en-us/library/system.io.stream.aspx">stream</a> instead of a string and that the call is made asynchronously. </p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public void UploadBlob(string path, string fileName, Stream stream)
{
    var cloudBlobContainer = cloudBlobClient.GetContainerReference(path);
    cloudBlobContainer.CreateIfNotExist();

    var blob = cloudBlobContainer.GetBlobReference(fileName);
    blob.BeginUploadFromStream(stream, UploadFinished, blob.Uri);
}

private void UploadFinished(IAsyncResult asyncResult)
{
    // do something
}</pre>
<h2>List all Blobs in a container</h2>
<p>This will give a list of links to all blobs stored in a container. </p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public IEnumerable&lt;Uri&gt; ListAllBlobs(string folder)
{
    var cloudBlobContainer = cloudBlobClient.GetContainerReference(folder);
    var listBlobItems = cloudBlobContainer.ListBlobs();

    return listBlobItems.Select(b =&gt; b.Uri);
}</pre>
<p>Simple enough. Once you got the setup right, Azure Blob Storage is actually quite easy to use. If you would like to list blobs in subfolders as well then use the overloaded method for <a href="http://msdn.microsoft.com/en-us/library/ee758385.aspx">ListBlobs</a> and send in BlobRequestOptions { UseFlatBlobListing = true }<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/blob-storage2.png" rel="lightbox">.</a></p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px; padding-top: 0px" title="Azure Blob Storage" border="0" alt="blob storage" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/blob-storage_thumb2.png" width="412" height="354" /></p>
<h2>&#160;</h2>
<h2>Download content from a Blob</h2>
<p>Very similar to uploading data, it works the same way with other data types than string.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public string DownloadBlob(string folder, string fileName)
{
    var cloudBlobContainer = cloudBlobClient.GetContainerReference(folder);
    var blob = cloudBlobContainer.GetBlobReference(fileName);

    return blob.DownloadText();
}</pre>
<p>But, before downloading a blob, you might want to see if it exists…</p>
<h2>See if a Blob exists</h2>
<p>The only way that I have found for doing this (and please correct me if I’m wrong here) is to do a little peek and catch the resulting exception.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">private bool BlobExists(CloudBlob blob)
{
    try
    {
        blob.FetchAttributes();
        return true;
    }
    catch (StorageClientException e)
    {
        if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
        {
            return false;
        }
        throw;
    }
}</pre>
<p>Thanks to <a href="http://blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob">Steve Marx</a> for the solution. <a href="http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storageclient.cloudblob.fetchattributes.aspx">FetchAttributes()</a> is used simply because it will be a small amount of data transferred or a 404. So even if I call BlobExists() on a 4Mb block blob it won’t be any different from doing the same call on a 2Kb blob.</p>
<h2>Some tips and tricks</h2>
<p>Well, first of all. Azure Blob storage can be used for much more than just file storage. Scalability is built in so if you, for example, have a static html page, you can easily upload it to Azure blob storage and then link to it. It is a good way to take away load from your WebRole.</p>
<p>All methods that I showed you have a Begin/End method as well. So you should be able to do most of the work asynchronously, as I did when I uploaded a blob from a stream.</p>
<p>If an Azure Queue message risk becoming bigger than 8Kb the recommended solution is to upload the message as a blob and then store the URI as the message on the queue. You won’t get charged for the extra data traffic as long as it’s done within the same data center. </p>
<p>Happy blobbing.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/18/azure-blob-storage-a-simple-example/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Create Azure Tables at startup</title>
		<link>http://blog.jayway.com/2011/10/04/create-azure-tables-at-startup/</link>
		<comments>http://blog.jayway.com/2011/10/04/create-azure-tables-at-startup/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 05:28:00 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[azure]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9789</guid>
		<description><![CDATA[You know that thing you need to do before accessing your azure table for the first time? Yes, I’m looking at you CreateTableIfNotExist(string tableName). You need to do this before persisting you first entity or writing you first query. This annoys me. Mostly because I tend to forget about it and then get reminded by [...]]]></description>
			<content:encoded><![CDATA[<p>You know that thing you need to do before accessing your azure table for the first time? Yes, I’m looking at you <em>CreateTableIfNotExist(string tableName)</em>. You need to do this before persisting you first entity or writing you first query.</p>
<p>This annoys me. Mostly because I tend to forget about it and then get reminded by an exception. So here’s what I did in order to never ever run into the same issue again (right…).</p>
<h2>Reflection?</h2>
<p>Yes, reflection! As I usually organize my Azure projects I have a folder called Entities where I have all… well entities that I can read and write from/to Azure Table Storage. Illustrated below.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/projectstructure.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="projectstructure" border="0" alt="projectstructure" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/projectstructure_thumb.png" width="413" height="243" /></a></p>
<p>To be honest, I would probably put the entities in a separate project, but this will do as an example.</p>
<p>So, the idea is, if I know the namespace where I <u>always</u> put my entities, then I should also be able to find all my entities by looking into that namespace using reflection.</p>
<h2>But reflection is quite bad for performance…</h2>
<p>Yes… yes, it is. Therefore I prefer only using it when I need it and when my application won’t suffer from it. For example – at startup.</p>
<p>Now, before proceeding I recommend that you take a look at a previous blog post – <a href="http://blog.jayway.com/2011/02/20/making-the-most-out-of-your-workerroles/">Making the most out of your WorkerRoles</a>. What I did there was basically to create worker that implemented IWorker and then using an IoC container I looped over all implementations in the Run method. We will do the same thing here, but instead of an IWorker we will create an IStartupTask.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public interface IStartupTask
{
    void Start();
}</pre>
<p>Now we can get started. What we’ll need to do is:</p>
<ul>
<li>Find a way to programmatically find all Entities </li>
<li>Implement IStartupTask </li>
<li>Make sure that all (one at the moment) startup tasks are executed in the OnStart method of the WorkerRole </li>
</ul>
<h4>Finding the entities</h4>
<p align="left">So reflection is not one of my strongest .NET skills. Luckily, others such as <a href="http://stackoverflow.com/users/93623/fredrik-mork" target="_blank">Fredrik Mörk</a> are more competent in the area. So I used <a href="http://stackoverflow.com/questions/949246/how-to-get-all-classes-within-namespace">his</a> solution.</p>
<h4>Implement IStartupTask</h4>
<p>Here we go.</p>
<pre style="width: 653px; height: 518px" class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public class InitiateAzureStorage : IStartupTask
{
    public void Start()
    {
        var entityNames = GetTypesInNamespace(&quot;Awesome.WorkerRole.Entities&quot;);
        entityNames.ForEach(CreateTable);
    }

    private List&lt;string&gt; GetTypesInNamespace(string nameSpace)
    {
        return Assembly.GetCallingAssembly()
                       .GetTypes()
                       .Where(t =&gt; String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal))
                       .Select(t =&gt; t.Name)
                       .ToList();
    }

    private void CreateTable(string tableName)
    {
        var storageAccount = CloudStorageAccount.FromConfigurationSetting(&quot;DataConnectionString&quot;);
        var cloudTableClient = storageAccount.CreateCloudTableClient();
        cloudTableClient.CreateTableIfNotExist(tableName);
    }
}</pre>
<p>Neat.</p>
<h4>Execute the task in the OnStart method</h4>
<p>Same procedure as in the <a href="http://blog.jayway.com/2011/02/20/making-the-most-out-of-your-workerroles/">previous blog post</a> I mentioned above. We will just loop through all instances of IStartupTask, that is registered in our IoC container, and then start them.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public override bool OnStart()
{
    SetConfigurationListener();
    IoC.Initialize(); //Register instances in the IoC container

    var startupTasks = ObjectFactory.GetAllInstances&lt;IStartupTask&gt;();
    foreach (var startupTask in startupTasks)
    {
        startupTask.Start();
    }

    return base.OnStart();
}</pre>
<p>That’s it really.</p>
<h2>What happens now?</h2>
<p>Basically once our WorkerRoles starts we will make sure that all of our Azure tables exists. If not, we will create them. No more exceptions telling us that the table does not exist. Ever.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/worker.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="worker" border="0" alt="worker" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/worker_thumb.png" width="387" height="339" /></a></p>
<p>Each and every time we add a new entity it will automatically get sucked in by our startup task and then create the table. You could use a similar approach to Azure Queues if you for example serialize objects onto the queue.</p>
<p>But now when you have a nice infrastructure for startup task you can use them for so much more. We (that is Jayway), for example, use them to set up a socket that another server use to push in data. The sky's is the limit.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/04/create-azure-tables-at-startup/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using s3cmd to Backup your WordPress Installation</title>
		<link>http://blog.jayway.com/2011/10/02/using-s3cmd-to-backup-your-wordpress-data/</link>
		<comments>http://blog.jayway.com/2011/10/02/using-s3cmd-to-backup-your-wordpress-data/#comments</comments>
		<pubDate>Sun, 02 Oct 2011 21:05:18 +0000</pubDate>
		<dc:creator>Henrik Bernström</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[backupwordpress]]></category>
		<category><![CDATA[cron]]></category>
		<category><![CDATA[crontab]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[s3]]></category>
		<category><![CDATA[s3cmd]]></category>
		<category><![CDATA[shell scripting]]></category>
		<category><![CDATA[ubuntu]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9849</guid>
		<description><![CDATA[This article will explain, in a few short steps, how to backup your WordPress installation to Amazon S3 service. It will deal with Ubuntu as operating system and Amazon EC2 for hosting but is not limited to such an environment. Prerequisits are an Amazon account for the S3 service, a WordPress installation and knowledge of [...]]]></description>
			<content:encoded><![CDATA[<p>This article will explain, in a few short steps, how to backup your WordPress installation to Amazon S3 service. It will deal with Ubuntu as operating system and Amazon EC2 for hosting but is not limited to such an environment. Prerequisits are an Amazon account for the S3 service, a WordPress installation and knowledge of these products.</p>
<h2>How to backup WordPress</h2>
<p>There are numerous plugins for WordPress when it comes to backup. I have learnt to appreciate the plugin BackUpWordPress as it not only backs up your database but also all the files within the installation. </p>
<p><a href="http://hmn.md/backupwordpress/" title="BackUpWordPress">http://hmn.md/backupwordpress/</a></p>
<p>There are a few number (though quite complete) of configuration options like</p>
<p>- manual or daily scheduled backups<br />
- number of backups to keep<br />
- whether to include files or database or both</p>
<p>The backups are stored on disk on the path of your choice and could also be attempted to be emailed. Having this kind of backup data makes it very comfortable to restore your WordPress installation.</p>
<p>But what if your complete machine/instance is failing? On, for example Amazon EC2 one should take snapshots of instances when the setup of these change but this does not apply to content changes. Restoring from a snapshot does not bring back newly created or updated content from, for example WordPress. That is, moving those WordPress backup files to a safer place becomes vital. So, s3cmd to the rescue.</p>
<h2>What is s3cmd?</h2>
<p>Extracted from its' homepage:</p>
<p><em>"S3cmd is a command line tool for uploading, retrieving and managing data in Amazon S3. It is best suited for power users who don't fear command line. It is also ideal for scripts, automated backups triggered from cron, etc."</em></p>
<p><a href="http://s3tools.org/s3cmd" title="s3cmd">http://s3tools.org/s3cmd</a></p>
<p>At the time of writing s3cmd requires Python 2.4 or newer and some pretty common Python modules. Installing it is merely a matter of running:</p>
<pre class="brush: shell; ruler: true; auto-links: false; smart-tabs: false;">sudo apt-get install s3cmd</pre>
<p>To configure it run</p>
<pre class="brush: shell; ruler: true; auto-links: false; smart-tabs: false;">s3cmd --configure</pre>
<p>You will be asked for the two keys of your Amazon account - copy and paste them from your confirmation email or from your Amazon account page.</p>
<p>To list all your buckets run</p>
<pre class="brush: shell; ruler: true; auto-links: false; smart-tabs: false;">s3cmd ls</pre>
<p>and to list the content of a bucket run</p>
<pre class="brush: shell; ruler: true; auto-links: false; smart-tabs: false;">s3cmd ls s3://[bucket name]</pre>
<p>Now, you could use 's3cmd put' to upload and 's3cmd remove' to remotely remove specific files but then you would have to do some scripting to select these specific files and to keep the bucket contents to an acceptable size. There is another option that simply syncs the content of your local directory to the remote bucket, doing the removal automatically, namely 's3cmd sync'.</p>
<pre class="brush: shell; ruler: true; auto-links: false; smart-tabs: false;">s3cmd sync --delete-removed [source directory] s3://[bucket name]</pre>
<p>The source directory is naturally replaced with the directory of where you put your WordPress backups. </p>
<h2>Scheduling it</h2>
<p>To make it a little easier to schedule via crontab you preferrably put the sync command in a shell script, for example 'sync-wp-backups.sh'</p>
<pre class="brush: bash/shell; ruler: true; auto-links: false; smart-tabs: false;">#!/bin/bash

/usr/bin/s3cmd sync --delete-removed [source directory] s3://[bucket name]</pre>
<p>To schedule this script run</p>
<pre class="brush: bash/shell; ruler: true; auto-links: false; smart-tabs: false;">crontab -e</pre>
<p>which brings you into editing the cron job with the editor of your choice. For example you could edit the crontab file to schedule it to run daily at 23:30 (11:30 PM)</p>
<pre class="brush: bash/shell; ruler: true; auto-links: false; smart-tabs: false;">30 23 * * * /home/ubuntu/sync-wp-backups.sh >> /home/ubuntu/s3-backup.log</pre>
<p>which logs the output to file (s3-backup.log).</p>
<p>That's it! Now I have a number of days of backup automatically synced from the Amazon instance running WordPress to a more fail safe S3 bucket. At least I sleep a lot better with this in place.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/02/using-s3cmd-to-backup-your-wordpress-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An example of a testable Azure Table Storage</title>
		<link>http://blog.jayway.com/2011/09/29/an-example-of-a-testable-azure-table-storage/</link>
		<comments>http://blog.jayway.com/2011/09/29/an-example-of-a-testable-azure-table-storage/#comments</comments>
		<pubDate>Thu, 29 Sep 2011 11:11:00 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9771</guid>
		<description><![CDATA[Testability and the means to abstract away your persistence layer in Windows Azure - two things that you don’t get for free. But you can get it really cheap, you just need some generics, interfaces. an IoC container and ~10 minutes. While coding for this post I used StructureMap (can be downloaded from NuGet) and [...]]]></description>
			<content:encoded><![CDATA[<p>Testability and the means to abstract away your persistence layer in Windows Azure - two things that you don’t get for free. But you can get it really cheap, you just need some generics, interfaces. an IoC container and ~10 minutes. </p>
<p>While coding for this post I used <a href="http://structuremap.net/structuremap/">StructureMap</a> (can be downloaded from NuGet) and <a href="http://www.microsoft.com/windowsazure/sdk/">Windows Azure SDK 1.5</a>. Should work just fine with an older version of the SDK though.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/sheep.jpg" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="Get it? Sorry, long week..." border="0" alt="Really cheap" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/sheep_thumb.jpg" width="339" height="243" /></a></p>
<h2>Wrapping up TableServiceContext</h2>
<p>As you know you’ll need to extend <a href="http://msdn.microsoft.com/en-us/library/ee758694.aspx">TableServiceContext</a> in order to save our entities in Azure Table Storage. Each and every example that I’ve seen is creating a specific ServiceContext for every entity type that needs to be saved. We’ll, I’m not going to do that. </p>
<p>We start with our interface.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">

public interface IServiceContext&lt;TEntity&gt;
{
    IQueryable&lt;TEntity&gt; QueryableEntities { get; }

    void Create(TEntity entity);

    void Update(TEntity entity);

    void Delete(TEntity entity);
}

</pre>
<p>Easy enough, right? A basic interface exposing CRUD capabilities. The implementation is not much harder.</p>
<pre style="width: 653px; height: 679px" class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">

public class ServiceContext&lt;TEntity&gt; : TableServiceContext, IServiceContext&lt;TEntity&gt;
    where TEntity : TableServiceEntity
{
    private readonly string tableName;

    public ServiceContext()
        : base(AzureProvider.TableEndpoint, AzureProvider.Credentials)
    {
        tableName = typeof(TEntity).Name;
    }

    public IQueryable&lt;TEntity&gt; QueryableEntities
    {
        get
        {
             return CreateQuery&lt;TEntity&gt;(tableName);
        }
    }

    public void Create(TEntity entity)
    {
        AddObject(tableName, entity);
        SaveChanges();
    }

    public void Update(TEntity entity)
    {
        UpdateObject(entity);
        SaveChanges();
    }

    public void Delete(TEntity entity)
    {
        DeleteObject(entity);
        SaveChanges();
    }
}
</pre>
<p>So we create our own ServiceContext, extending <a href="http://msdn.microsoft.com/en-us/library/ee758694.aspx">TableServiceContext</a> as well as implementing our very own IServiceContext&lt;TEntity&gt;. As you can see, in the base constructor, we use a static helper class AzureProvider which basically just exposes values from CloudStorageAccount. This is just for readability and really not necessary. </p>
<p>Also worth mentioning is that we use whatever type name TEntity has as the table name. So if we create a ServiceContext&lt;Dog&gt;, our table would be “Dog”. This makes life easier and also solves a nasty performance issue.</p>
<blockquote>
<p>Due to a known performance issue with the ADO.NET Data Services client library, it is recommended that you use the table name for the class definition or define the ResolveType delegate on the DataServiceContext. If this is not used and when the entity class name is not the same as table name, query performance degrades with number of entities returned in the result.</p>
<p>- <a href="http://windowsclient.net/blogs/anshulee/archive/2010/05/27/best-practices-for-ado-net-dataservices-when-using-azure-table-storage.aspx">WindowsClient.net</a></p>
</blockquote>
<p>The ServiceContext class is basically the only code that will be <em>untestable</em>, but honestly… there are no actual logic or business rules inside that class. I would never strive for 100% coverage. As far as I’m concerned that’s a waste of time.</p>
<h2>Now what?</h2>
<p>First of all, in order to actually use our shiny new interface in a decent manner we need to register it with our IoC container of choice. As usual, I prefer <a href="http://structuremap.net/structuremap/">StructureMap</a>.</p>
<pre style="width: 681px; height: 201px" class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">ObjectFactory.Initialize(x =&gt;
{
    x.Scan(scanner =&gt;
    {
        scanner.TheCallingAssembly();
        scanner.ConnectImplementationsToTypesClosing(typeof(IServiceContext&lt;&gt;));
    });
    x.For(typeof (IServiceContext&lt;&gt;)).Use(typeof (ServiceContext&lt;&gt;));
});</pre>
<p>This little piece of code allows to instantiate a new class such as:</p>
<pre style="width: 653px; height: 257px" class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public class Foo : IFoo
{
    private readonly IServiceContext&lt;Person&gt; personContext;
    private readonly IServiceContext&lt;Dog&gt; dogContext;

    public Foo(IServiceContext&lt;Person&gt; personContext, IServiceContext&lt;Dog&gt; dogContext)
    {
        this.personContext = personContext;
        this.dogContext = dogContext;
    }
}</pre>
<p>Our IoC container will be able to create it without any problems. This class will be completely ignorant what’s behind IServiceContext&lt;TEntity&gt;, it could just as well be a database. Since we inject all dependencies via the constructor this class is quite easy to test. </p>
<h2>So?</h2>
<p>Really, the point that I’m trying to make is that it’s not hard to wrap the not-very-testable parts of Windows Azure SDK. Just do it from start and you’ll be a happy (unit test writing) camper. </p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/highfive.jpg" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="highfive" border="0" alt="highfive" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/highfive_thumb.jpg" width="275" height="275" /></a></p>
<p>Happy testing!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/29/an-example-of-a-testable-azure-table-storage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Clojure third language officially supported on Heroku</title>
		<link>http://blog.jayway.com/2011/07/07/clojure-third-language-officially-supported-on-heroku/</link>
		<comments>http://blog.jayway.com/2011/07/07/clojure-third-language-officially-supported-on-heroku/#comments</comments>
		<pubDate>Thu, 07 Jul 2011 00:34:11 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[heroku]]></category>
		<category><![CDATA[official]]></category>
		<category><![CDATA[support]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9012</guid>
		<description><![CDATA[According to this blog entry on Heroku, Clojure becomes the third language officially supported on the Cedar stack, after Ruby and Node.js. They write: - "Clojure combines the expressiveness of Lisp, the agility of a dynamic language, the performance of a compiled language, and the wide applicability of the JVM in a robust, production-ready package. [...]]]></description>
			<content:encoded><![CDATA[<p>According to <a href="http://blog.heroku.com/archives/2011/7/5/clojure_on_heroku/">this blog entry</a> on Heroku, Clojure becomes the third language officially supported on the Cedar stack, after Ruby and Node.js. They write:</p>
<p>- "Clojure combines the expressiveness of Lisp, the agility of a dynamic language, the performance of a compiled language, and the wide applicability of the JVM in a robust, production-ready package. Clojure is a practical language designed to support high-performance, concurrent applications which efficiently interoperate with other software in the JVM ecosystem. All of this combines to make it an ideal tool for the programmer to quickly build robust programs."</p>
<p>And motivate why they chose to support Clojure:</p>
<p>- "Clojure covers a new use case on the Heroku platform: components which demand correctness, performance, composability; and optionally, access to the Java ecosystem."</p>
<p>Ladies and gentlemen, it's time to consider moving the parenthesis from the end of the method name to the beginning of the function call. Try it, you'll like it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/07/07/clojure-third-language-officially-supported-on-heroku/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deploying a Clojure web app on Heroku</title>
		<link>http://blog.jayway.com/2011/06/13/deploying-a-clojure-web-app-on-heroku/</link>
		<comments>http://blog.jayway.com/2011/06/13/deploying-a-clojure-web-app-on-heroku/#comments</comments>
		<pubDate>Mon, 13 Jun 2011 13:56:05 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[heroku]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8712</guid>
		<description><![CDATA[<p><a href="http://www.heroku.com/">Heroku</a> is a cloud application platform for Ruby/Rails and Node.js. However, the <a href="http://devcenter.heroku.com/articles/cedar">Cedar stack</a> on Heroku makes it possible to deploy other types of applications. In this blog entry, I will first describe how to write a simple <a href="http://clojure.org">Clojure</a> web app using the <a href="https://github.com/mmcgrana/ring">Ring library</a> and the build tool <a href="https://github.com/technomancy/leiningen">Leiningen</a>. Then I will show how to deploy this Clojure web app on Heroku, using nothing but Git. I will make a change and see how to deploy that. I will also show how to easily roll back to a previous release.</p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.heroku.com/">Heroku</a> is a cloud application platform for Ruby/Rails and Node.js. However, the <a href="http://devcenter.heroku.com/articles/cedar">Cedar stack</a> on Heroku makes it possible to deploy other types of applications. In this blog entry, I will first describe how to write a simple <a href="http://clojure.org">Clojure</a> web app using the <a href="https://github.com/mmcgrana/ring">Ring library</a> and the build tool <a href="https://github.com/technomancy/leiningen">Leiningen</a>. Then I will show how to deploy this Clojure web app on Heroku, using nothing but Git. I will make a change and see how to deploy that. I will also show how to easily roll back to a previous release.</p>
<h2>Clojure maps</h2>
<p>A map is a data structure that associates keys to values. Maps are very important in Clojure, because they are used to store entity data, much like custom classes with fields and setters/getters are used in traditional object-oriented languages like Java. In the Java world, we have java.util.Map. They are somewhat cumbersome to work with, mostly due to the static, generic typing, but also because there is no literal map syntax, plus the fact that you can't initialize it with elements. You must first create it, then mutate it:</p>
<pre class="brush: java;gutter: false;">
import java.util.Map;
import java.util.HashMap;

Map&lt;String,Object&gt; map = new HashMap&lt;String,Object&gt;();
map.put("somekey", "somevalue");
</pre>
<p>Clojure maps, on the other hand, have a very concise literal syntax. Zero or more key-value pairs between curly braces. That's it.</p>
<pre class="brush: clojure;gutter: false;">
(def map {:somekey "somevalue"})
</pre>
<p>The key <code>:somekey</code> in the map above is a Clojure <code>keyword</code>. Keywords are symbolic identifiers that always evaluate to themselves, and they have a very fast equality check. For those reasons (and others, as we will see), keywords are often used, rather than strings, as keys in maps.</p>
<p>A Clojure map is not only a data structure, it is also a function. When a map is called with a key, it will return the corresponding value (or nil if no key was found). It can look like this when testing it from the <a href="http://en.wikipedia.org/wiki/Read-eval-print_loop">REPL</a>:</p>
<pre class="brush: clojure;gutter: false;">
user&gt; (def animal {:species :lion, :name "Leo", :age 3})
user&gt; (animal :name)
"Leo"
</pre>
<p>In fact, keywords are functions too. When a keyword is called with a map as argument, it will look itself up in the map and return the matching value:</p>
<pre class="brush: clojure;gutter: false;">
user&gt; (:name animal)
"Leo"
</pre>
<p>This form is more common in idiomatic Clojure.</p>
<h2>The Ring library</h2>
<p>Ring is a Clojure web applications library inspired by Ruby's Rack. Ring abstracts the <span class="caps">HTTP</span> request and response as maps, and expects handlers to be functions that take a map as argument and returns a map. The returned map is transformed by Ring into a <span class="caps">HTTP</span> response, which is sent back to the caller. This is a simple, but powerful abstraction. It means that web handlers can be written as regular functions, which can be tested in isolation. Web libraries like <a href="https://github.com/weavejester/compojure/wiki">Compojure</a> build on top of the Ring abstraction and provide more high-level constructs, like routing. In order to not complicate this example, however, we will stick to plain Ring.</p>
<p>Let's say that we have a <span class="caps">HTTP</span> request that looks like this:</p>
<pre class="brush: plain;gutter: false;">
GET /welcome HTTP/1.1
HOST: www.sayhello.com
</pre>
<p>Ring transforms this into a Clojure map that looks like this:</p>
<pre class="brush: clojure;">
{:protocol        :http
 :request-method  :get
 :uri             "/welcome"
 :server-name     "www.sayhello.com"}
</pre>
<p>Let's further assume that we want to generate a corresponding <span class="caps">HTTP</span> response:</p>
<pre class="brush: plain;gutter: false;">
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 11

Hello world
</pre>
<p>In order to produce that <span class="caps">HTTP</span> response, Ring expects this map:</p>
<pre class="brush: clojure;">
{:status 200
 :headers
    {"Content-Type" "text/plain"
     "Content-Length" 11}
 :body "Hello world"}
</pre>
<p>So all we need to do is to provide a function that returns the above map, like this:</p>
<pre class="brush: clojure;highlight:1">
(defn app [req]
  {:status 200
   :headers
      {"Content-Type" "text/plain"
       "Content-Length" 11}
   :body "Hello world"})
</pre>
<p>Ring provides a <code>response</code> convenience function that returns a skeletal response map with status 200, no headers, and the given argument as body:</p>
<pre class="brush: clojure;highlight:[1,3]">
(use 'ring.util.response)
(defn app [req]
  (response "Hello world"))
</pre>
<p>We'll use the <code>response</code> function in our example later.</p>
<h2>Leiningen</h2>
<p>In order to manage our dependencies, we will use the <a href="https://github.com/technomancy/leiningen">Leiningen</a> build tool. The simplest way to install it is to download the <a href="https://github.com/technomancy/leiningen/raw/stable/bin/lein">stable release</a> of the script and place it somewhere in the <span class="caps">PATH</span>, like ~/bin. Then run <code>lein self-install</code>:</p>
<pre class="brush: plain;gutter: false;">
$ lein self-install
Downloading Leiningen now...
...

$ lein version
Leiningen 1.5.2 on Java 1.6.0_24 Java HotSpot(TM) 64-Bit Server VM
</pre>
<h2>Building the web application</h2>
<p>We create a new project and go there:</p>
<pre class="brush: plain;gutter: false;">
$ lein new cljheroku
$ cd cljheroku
</pre>
<p>The newly created directory contains the following files:</p>
<pre class="brush: plain;gutter: false;">
cljheroku/
├── README
├── project.clj
├── src
│   └── cljheroku
│       └── core.clj
└── test
    └── cljheroku
        └── test
            └── core.clj
</pre>
<p>First we need to create a Procfile for Heroku:</p>
<pre class="brush: plain;gutter: false;">
$ echo "web: lein run -m cljheroku.core" &gt; Procfile
</pre>
<p>This will have Leiningen start the web application by running the function called <code>-main</code> in the namespace cljheroku.core, ie the file <code>src/cljheroku/core.clj</code>. We'll change that file to contain this:</p>
<pre class="brush: clojure;">
(ns cljheroku.core
  (:use ring.util.response
        ring.adapter.jetty))

(defn app [req]
  (response "Hello World"))

(defn -main []
  (let [port (Integer/parseInt (get (System/getenv) "PORT" "8080"))]
    (run-jetty app {:port port})))
</pre>
<p>Let's look at this code in more detail. We begin with the first chunk:</p>
<pre class="brush: clojure; first-line: 01;">
(ns cljheroku.core
  (:use ring.util.response
        ring.adapter.jetty))
</pre>
<p>The <a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/ns">ns macro</a> will create a namespace cljheroku.core and load all functions in the namespaces ring.util.response and ring.adapter.jetty. Since we used <code>:use</code> and not <code>:require</code>, these functions can be referenced by name, without any prefix or namespace qualifier. This enables us to write <code>(response ...)</code> instead of <code>(ring.util.response/response ...)</code>.</p>
<p>Then we define our Ring handler called <code>app</code>.</p>
<pre class="brush: clojure; first-line: 05;">
(defn app [req]
  (response "Hello World"))
</pre>
<p>As you can see, it's just a regular function that takes one argument: a <span class="caps">HTTP</span> request map, and returns the result of the response function: a <span class="caps">HTTP</span> response map. If we wanted to set the Content-Type header, we could use the <code>content-type</code> function, another function from ring.util.response. Instead of <code>(response "Hello world")</code>, we would pass the response through the <code>content-type</code> function: <code>(content-type (response "Hello world") "text/plain")</code>. But here we will just use <code>response</code>.</p>
<p>Finally we specify a <code>-main</code> function.</p>
<pre class="brush: clojure; first-line: 8;">
(defn -main []
  (let [port (Integer/parseInt (get (System/getenv) "PORT" "8080"))]
    (run-jetty app {:port port})))
</pre>
<p>It will serve the same purpose as the Java main method, namely provide an entry point from the outside world. It gets the value of the <span class="caps">PORT</span> environment variable, or uses 8080 as default. It can be enlightening to analyze that part in detail. <code>(System/getenv)</code> is simply Clojure's way of calling Java's static method <code>System.getenv()</code>, which returns a java.util.Map. The <code>get</code> function takes a map (yes, it works with Java maps too), a key and a default value, and returns the matching value. So, <code>(get (System/getenv) "PORT" "8080")</code> will get the <span class="caps">PORT</span> variable from the environment, and if there is no <span class="caps">PORT</span> set there, it will return "8080". The resulting string value of the port is parsed into an integer, and is stored as the local variable <code>port</code>. This value is then passed in to the Jetty adapter as part of a configuration map. All this in two lines. If you're not used to Clojure's lack of ceremony, you might find it overwhelming. I personally find it refreshingly to-the-point.</p>
<p>OK, that was the source code for our handler. We now need to adjust the project.clj file slightly, and provide a dependency to Ring. We'll also add an exclusion of a duplicate dependency that Jetty has. Here is the resulting project.clj:</p>
<pre class="brush: clojure;">
(defproject cljheroku "1.0.0-SNAPSHOT"
  :description "Example Ring app running on Heroku"
  :dependencies [[org.clojure/clojure "1.2.1"]
                 [ring/ring-core "0.3.8"]
                 [ring/ring-jetty-adapter "0.3.8"]]
  :exclusions [org.mortbay.jetty/servlet-api])
</pre>
<p>Before we do anything else, though, we should add this baby to Git:</p>
<pre class="brush: plain;gutter: false;">
$ git init
Initialized empty Git repository in /Users/john/Source/cljheroku/.git/

$ git add .

$ git commit -m "Initial commit"
</pre>
<p>We should probably push this to a maintained repository somewhere, but for our purposes, we have now stored this in Git.</p>
<h2>Testing locally</h2>
<p>Before we test it, we will ask Leiningen to retrieve the dependencies:</p>
<pre class="brush: plain;gutter: false;">
$ lein deps
</pre>
<p>The lib directory now contains a list of jars that we need. Leiningen will make sure they all get on the classpath without you ever having to see it. You <em>can</em> ask Leiningen for the classpath, though, should you really like to see it:</p>
<pre class="brush: plain;gutter: false;">
$ lein classpath
</pre>
<p>You can also have Leiningen create a pom file for you, which can be handy if you need to look at the dependency:tree, import the project into an <span class="caps">IDE</span> that only knows Maven; things like that:</p>
<pre class="brush: plain;gutter: false;">
$ lein pom
</pre>
<p>Anyway, we can now start this web application using the same command as we placed in the Procfile for Heroku. It will start Clojure with the correct classpath, find and make available the given namespace (cljheroku.core), and call its <code>-main</code> function with any given arguments (none, in our case):</p>
<pre class="brush: plain;gutter: false;">
$ lein run -m cljheroku.core
2011-06-12 18:41:24.927:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2011-06-12 18:41:24.928:INFO::jetty-6.1.26
2011-06-12 18:41:24.959:INFO::Started SocketConnector@0.0.0.0:8080
</pre>
<p>Browsing to localhost:8080 shows a page with "Hello world" on it. Good. It works.</p>
<p>We now change the handler function to instead respond with, say, "Hello everyone" and save it. When we reload the page, the new message appears. Excellent. It reloads automatically.</p>
<p>OK. We're happy with our web application and want to deploy it into the cloud. What do we do?</p>
<h2>Deploying on Heroku</h2>
<p>Heroku is, as I mentioned at the beginning, mainly a Ruby application platform. The command line tool for working with Heroku is a Ruby Gem. We first need to install Ruby and RubyGems. Assuming that has been done, we need to get the heroku gem:</p>
<pre class="brush: plain;gutter: false;">
$ sudo gem install heroku
</pre>
<p>Now we can create an app on the Cedar stack:</p>
<pre class="brush: plain;gutter: false;">
$ heroku create --stack cedar
Enter your Heroku credentials.
Email: john.doe@example.com
Password:
Found existing public key: /Users/john/.ssh/id_rsa.pub
Would you like to associate it with your Heroku account? [Yn]
Uploading ssh public key /Users/john/.ssh/id_rsa.pub
Creating furious-sword-794... done, stack is cedar
http://furious-sword-794.herokuapp.com/ | git@heroku.com:furious-sword-794.git
Git remote heroku added
</pre>
<p>We can list the remote repositories to see what the last sentence above meant:</p>
<pre class="brush: plain;gutter: false;">
$ git remote -v
heroku	git@heroku.com:furious-sword-794.git (fetch)
heroku	git@heroku.com:furious-sword-794.git (push)
</pre>
<p>And finally, in order to deploy our first verison of the web app, we push everything to heroku:</p>
<pre class="brush: plain;gutter: false;">
$ git push heroku master
The authenticity of host 'heroku.com (50.19.85.156)' can't be established.
RSA key fingerprint is 8b:48:5e:67:0e:c9:16:47:32:f2:87:0c:1f:c8:60:ad.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'heroku.com,50.19.85.156' (RSA) to the list of known hosts.
Counting objects: 13, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (13/13), 1.27 KiB, done.
Total 13 (delta 0), reused 0 (delta 0)

-----&gt; Heroku receiving push
-----&gt; Clojure app detected
-----&gt; Installing Leiningen
       Downloading: leiningen-1.5.2-standalone.jar
       Writing: lein script
-----&gt; Installing dependencies with Leiningen
       Running: lein deps :skip-dev
       Downloading: org/clojure/clojure/1.2.1/clojure-1.2.1.pom from central
       Downloading: ring/ring-core/0.3.8/ring-core-0.3.8.pom from clojars
       ...
       Copying 10 files to /tmp/build_19juox87ngduz/lib
-----&gt; Discovering process types
       Procfile declares types -&gt; web
-----&gt; Compiled slug size is 11.0MB
-----&gt; Launching... done, v4
       http://furious-sword-794.herokuapp.com deployed to Heroku

To git@heroku.com:furious-sword-794.git
 * [new branch]      master -&gt; master
</pre>
<p>We browse to http://furious-sword-794.herokuapp.com, and we see the text "Hello world" (if you remembered to change back from "Hello everyone"). Now we make a small change:</p>
<pre class="brush: plain;gutter: false;">
-  (response "Hello World"))
+  (response "Hello World, I tell you!"))
</pre>
<p>All we need to do to deploy the change is to commit it, and then push to heroku:</p>
<pre class="brush: plain;gutter: false;">
$ git ci -a
$ git push heroku master
</pre>
<p>When we reload the page, the new text is there.</p>
<h2>Roll back to previous release</h2>
<p>We can list the releases that have been pushed:</p>
<pre class="brush: plain;gutter: false;">
$ heroku releases
Rel   Change                          By                    When
----  ----------------------          ----------            ----------
v5    Deploy 34516b0                  john.doe@examp..  3 minutes ago
v4    Deploy e471ca1                  john.doe@examp..  5 minutes ago
</pre>
<p>Let's say there was a problem with the release that was just deployed, and we want to roll back. With Heroku, it's trivial to roll back to the previous release:</p>
<pre class="brush: plain;gutter: false;">
$ heroku rollback
Rolled back to v4
</pre>
<p>When we're done with this web app completely, we can destroy it like this:</p>
<pre class="brush: plain;gutter: false;">
$ heroku apps:destroy
</pre>
<p>It's even possible to roll back to earlier releases, but I won't show that here. This concludes the Clojure-on-Heroku guide. Thank you for your time.</p>
<h2>References</h2>
<ol>
<li>Heroku: <a href="http://www.heroku.com/">http://www.heroku.com/</a></li>
<li>Clojure: <a href="http://clojure.org/">http://clojure.org/</a></li>
<li>Ring library: <a href="https://github.com/mmcgrana/ring">https://github.com/mmcgrana/ring</a></li>
<li>Leiningen: <a href="https://github.com/technomancy/leiningen">https://github.com/technomancy/leiningen</a></li>
<li>Compojure: <a href="https://github.com/weavejester/compojure/wiki">https://github.com/weavejester/compojure/wiki</a></li>
<li><a href="http://flightcaster.com/">FlightCaster</a> uses Clojure and Heroku: <a href="http://www.infoq.com/articles/flightcaster-clojure-rails">http://www.infoq.com/articles/flightcaster-clojure-rails</a></li>
<li>I got the idea for this blog from this Gist: <a href="https://gist.github.com/1001206">https://gist.github.com/1001206</a></li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/06/13/deploying-a-clojure-web-app-on-heroku/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Windows Azure ServiceBus pitfalls</title>
		<link>http://blog.jayway.com/2011/05/12/windows-azure-servicebus-pitfalls/</link>
		<comments>http://blog.jayway.com/2011/05/12/windows-azure-servicebus-pitfalls/#comments</comments>
		<pubDate>Thu, 12 May 2011 07:43:58 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Cloud]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8283</guid>
		<description><![CDATA[I'm doing a POC (Proof of Concept) with Windows Azure for a big customer. The idea is to have a web site hosted on Windows Azure where managers can enter messages. These message will then be distributed to computers on sites scattered all over the world.  A kind of a messenger service, mainly intended to [...]]]></description>
			<content:encoded><![CDATA[<p>I'm doing a POC (Proof of Concept) with Windows Azure for a big customer. The idea is to have a web site hosted on Windows Azure where managers can enter messages. These message will then be distributed to computers on sites scattered all over the world.  A kind of a messenger service, mainly intended to be used when other systems fail. The messages sent will be something like "To all employees in Australia: Server X is down. Expected back online at 9 pm."</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/ServiceBus.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/ServiceBus_small.png" alt="" title="ServiceBus_small" width="500" height="234" class="alignnone size-full wp-image-8331" /></a></p>
<p>Now, there are samples and tutorials on the Microsofts Azure website that shows how to build similair systems. So I could just take one of those samples, modify it a little and be done. Piece of cake, right? NOT SO!</p>
<p>There are several pits I fell into during the development.</p>
<p><strong>Pitfall 1</strong><br />
I wrote the system on my development machine, deployed it to Azure and tested it. Works fine! Great! Lets go to the customer and try it!</p>
<p>The client application crashed because the ServiceBus assemblies was not installed on the client machine, thus the "netEventRelayBinding" could not be found. Solution? Add it to the config file:</p>
<pre>
&lt;system.serviceModel&gt;
  &lt;extensions&gt;
    &lt;bindingExtensions&gt;
      &lt;add name="netEventRelayBinding" type="Microsoft.ServiceBus.Configuration.NetEventRelayBindingCollectionElement, Microsoft.ServiceBus, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /&gt;
    &lt;/bindingExtensions&gt;
  &lt;/extensions&gt;
&lt;/system.serviceModel&gt;
</pre>
<p><strong>Pitfall2</strong><br />
The client application crashed again with a 'Access Denied' error. Cause? The customer firewall didn't allow connections on the port the service bus uses.</p>
<p>Solution? Use http/https on port 80/443 instead. Add this to the code:</p>
<pre>
ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;
</pre>
<p><strong>Pitfall 3</strong><br />
The application crashed with a "HTTP 407 Proxy Authentication Required" because the customer has an internet proxy that requires authentication.</p>
<p>Add this to the config-file:</p>
<pre>
&lt;system.net&gt;
  &lt;defaultProxy enable="true" useDefaultCredentials="true"/&gt;
&lt;/system.net&gt;
</pre>
<p><strong>Pitfall 4</strong><br />
The application crashed again with a cryptic error: "Chunked encoding upload is not supported on the HTTP/1.0 protocol".<br />
I worked together with a network technichian to try to find the problem. After a lot of log reading and head scratching, we have come to the conclusion the proxy thinks that servicebus.windows.net is an unapproperiate site and blocks it, just like facebook and other sites the customer employees shouldn't access during work.</p>
<p>Solution: Make sure the proxy allows outgoing connections to Azure AppFabric sites. Here's a list of IP-addresses:<br />
<a href="http://blogs.msdn.com/b/windowsazureappfabricannounce/archive/2010/01/28/additional-data-centers-for-windows-azure-platform-appfabric.aspx">http://blogs.msdn.com/b/windowsazureappfabricannounce/archive/2010/01/28/additional-data-centers-for-windows-azure-platform-appfabric.aspx</a></p>
<p><strong>Conclusion</strong><br />
If you are planning on using Windows Azure AppFabric from within a company network, beware of proxies. They may cause a lot of headaches.</p>
<p>Also, I found this to be quite helpful:<br />
<a href="http://social.technet.microsoft.com/wiki/contents/articles/troubleshooting-connectivity-issues-in-the-windows-azure-appfabric-service-bus.aspx">http://social.technet.microsoft.com/wiki/contents/articles/troubleshooting-connectivity-issues-in-the-windows-azure-appfabric-service-bus.aspx</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/05/12/windows-azure-servicebus-pitfalls/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Configuring automatic deployment of a Windows Azure application using TeamCity</title>
		<link>http://blog.jayway.com/2011/03/20/configuring-automatic-deployment-of-a-windows-azure-application-using-teamcity/</link>
		<comments>http://blog.jayway.com/2011/03/20/configuring-automatic-deployment-of-a-windows-azure-application-using-teamcity/#comments</comments>
		<pubDate>Sun, 20 Mar 2011 08:27:00 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[continuous integration]]></category>
		<category><![CDATA[TeamCity]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=7595</guid>
		<description><![CDATA[There are several reasons for setting up Continuous Integration for any project. The very same reasons (and some more) are true for an Azure project. In this post I’ll take you through the journey that I and a colleague travelled in our quest for a fully automated build-test-deployment solution for our Azure project. Before I [...]]]></description>
			<content:encoded><![CDATA[<p>There are several reasons for setting up Continuous Integration for any project. The very same reasons (and some more) are true for an Azure project. In this post I’ll take you through the journey that I and a colleague travelled in our quest for a fully automated build-test-deployment solution for our Azure project.</p>
<p>Before I get started I would like to extend a big thanks to <a href="http://scottdensmore.typepad.com/blog/" target="_blank">Scott Densmore</a>. More specifically thank you for <a href="http://scottdensmore.typepad.com/blog/2010/03/azure-deployment-for-your-build-server.html" target="_blank">this</a> great blog post! Surely would have been real hard without it.</p>
<p>In order to reach our goal we need to:</p>
<ol>
<li>Have our build server configured to build Azure projects, preferably without installing Visual Studio. </li>
<li>Create an MSBuild script that builds an Azure package ready to be uploaded to Windows Azure. </li>
<li>Replace the connection strings in our ServiceConfiguration.csfg production connection strings. </li>
<li>Create a certificate so that we can deploy using <a href="http://msdn.microsoft.com/en-us/library/ee460799.aspx" target="_blank">Windows Azure Service Management API</a>. </li>
<li>Use PowerShell to deploy our Azure package and configuration file. </li>
<li>Tie it all together with <a href="http://www.jetbrains.com/teamcity/" target="_blank">TeamCity</a>. </li>
</ol>
<p>Let’s get started!</p>
<h2>Make our TeamCity server build an Azure project</h2>
<p>As it is, our build server can build basic projects without any problems. But, as we soon found out, it could not build Azure projects. So my goal here is to describe all the issues that we ran into and how we solved them. Hopefully this will help some of you trying to do the same thing.</p>
<p>As I mentioned before our goal was to avoid installing Visual Studio on the build machine. We decided this for several reasons. I guess that the main reason had something to do with <em>developer pride</em>… Simply put, it should not be necessary to install a full development environment on a build server just to build an Azure project.</p>
<p>Anyway, we started out with installing <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=7a1089b6-4050-4307-86c4-9dadaa5ed018" target="_blank">Windows Azure SDK</a> on the build server triggered our first build.</p>
<h4>First problem</h4>
<p><span style="font-family: consolas; color: #ff0000">The type or namespace name 'WindowsAzure' does not exist in the namespace 'Microsoft'</span></p>
<h4>First solution</h4>
<p>Well this isn’t good is it? We installed all Azure assemblies but it still refused to find them. Well, the solution for this problem is apparently to copy Microsoft.CloudService.targets from your development machine to the build machine. The file is located at <em>C:\Program Files\MSBuild\Microsoft\Cloud Service\v1.0\</em>.</p>
<h4>Second problem</h4>
<p><span style="font-family: consolas; color: #ff0000">WAT050 : The version of the Windows Azure SDK currently installed is not compatible with this version of Windows Azure Tools for Microsoft Visual Studio.&#160; Please download and install the latest version of both the Windows Azure SDK and the Windows Azure Tools for Microsoft Visual Studio</span></p>
<h4>Second solution</h4>
<p>Wait, what? We have already installed that, right? We’ll for some reason this wasn’t quite enough. I order to solve this problem you first need open up the Registry Editor and navigate to <em>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\ServiceHosting\v1.3.</em> There you have an entry called ToolsVersionSupportLevel. Note the number, in our case is was 7.</p>
<p>Now navigate to Microsoft.CloudService.targets that you copied in the previous step and open it. Now find the element &lt;ServiceHostingVSSupport&gt; and change the value to whatever number you found in the registry. Some of you might call this a hack, I like to call it pragmatism.</p>
<h4>Third problem</h4>
<p><span style="font-family: consolas; color: #ff0000">MSB4057: The target &quot;PipelineTransformPhase&quot; does not exist in the project.</span></p>
<h4>Third solution</h4>
<p>It seems that this informative message tells us that it misses the file Microsoft.WebApplication.targets. In order to get rid of this error you need to copy <em>C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\Web</em> to your build server. This wasn’t easy to figure out… you’re welcome. <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-winkingsmile" alt="Winking smile" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/wlEmoticon-winkingsmile.png" /></p>
<h4>Fourth problem</h4>
<p><span style="font-family: consolas; color: #ff0000">Need to specify the physical directory for the virtual path 'Web/' of role MyProject.Web.</span></p>
<h4>Fourth solution</h4>
<p>Ah, this error actually made some sense. Or well, I don’t exactly know why we got this error, but the solution was at least not that hard to figure out. Since one of our Azure roles is a WebRole, we need to specify its physical directory in ServiceDefinition.csdf. So find the element &lt;Site&gt; and add the attribute <strong>physicalDirectory=”..\MyProject.Web” </strong>(assuming that your WebRole’s name is MyProject.Web… which it's probably not).</p>
<h3>UPDATE</h3>
<h4>Fifth problem</h4>
<p><font color="#ff0000" face="Consolas">error MSB4019: The imported project &quot;C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\Windows Azure Tools\1.5\Microsoft.WindowsAzure.targets&quot; was not found.</font></p>
<p><font color="#ff0000" face="Consolas">Confirm that the path in the &lt;Import&gt; declaration is correct, and that the file exists on disk.</font></p>
<h4>Fith solution</h4>
<p>Noted by <a href="http://blog.jayway.com/author/andreashallberg/" target="_blank">Andreas Hallberg</a>, just copy copy the &quot;Windows Azure Tools&quot; dir to buildserver C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0</p>
<h4>Building</h4>
<p>That's it! Now our build server built our Azure project, ran all the test with coverage and doing this without complaining. First step done!</p>
<h2>Build our Azure package file</h2>
<p>The next step was to build our package file. You know, the same file that gets generated when you select publish in Visual Studio. This is basically an encrypted zip file containing all your assemblies needed to run your Azure roles. In order to have our build server build the very same package, we wrote a simple MSBuild script that invoked <a href="http://msdn.microsoft.com/en-us/library/gg432988.aspx" target="_blank">cspack</a>. It looked something like this.</p>
<pre class="brush: xml; ruler: true; gutter: false;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;Project xmlns=&quot;http://schemas.microsoft.com/developer/msbuild/2003&quot;&gt;
    &lt;PropertyGroup&gt;
        &lt;PackageCommand&gt;
            &quot;C:\Program Files\Windows Azure SDK\v1.3\bin\cspack.exe&quot; MyProject.Azure\ServiceDefinition.csdef /out:Publish\Package.cspkg /role:MyProject.Web;MyProject.Web /rolePropertiesFile:MyProject.Web;roleProperties.txt /role:MyProject.Worker;MyProject.Worker\bin\Release;MyProject.Worker.dll /rolePropertiesFile:MyProject.Worker;roleProperties.txt
        &lt;/PackageCommand&gt;
    &lt;/PropertyGroup&gt;
    &lt;Target Name=&quot;Build&quot;&gt;
        &lt;MakeDir Directories=&quot;Publish&quot;&gt;&lt;/MakeDir&gt;
        &lt;Message Text=&quot;Using cspack create a package for deployment...&quot;/&gt;
        &lt;Exec Command=&quot;$(PackageCommand)&quot;/&gt;
    &lt;/Target&gt;
&lt;/Project&gt;</pre>
<p>As you can see we simply invoke cspack and pass arguments so that it creates a neat little package containing a WebRole (MyProject.Web) and a WorkerRole (MyProject.Worker).</p>
<p>Worth noting here is the option /rolePropertiesFile. This is <span style="text-decoration: underline">absolutely necessary</span> if you have an application compiled for .NET 4.0. The roleProperties.txt file referenced only contains a single line: <em>TargetFrameWorkVersion=v4.0</em>. If you don’t add this option your role(s) won't start. I know this from personal experience…</p>
<h2>Replace our development configuration with production configuration</h2>
<p>Now we have all the assemblies neatly packed in a file named Package.cspkg. But in order to successfully deploy we also need to update our ServiceConfiguration.cscfg. As it is, it looks like this.</p>
<pre class="brush: xml; ruler: true; gutter: false;">&lt;ServiceConfiguration serviceName=&quot;Azure&quot; xmlns=&quot;http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration&quot; osFamily=&quot;1&quot; osVersion=&quot;*&quot;&gt;
  &lt;Role name=&quot;AzureRole.Worker&quot;&gt;
    &lt;Instances count=&quot;1&quot; /&gt;
    &lt;ConfigurationSettings&gt;
      &lt;Setting name=&quot;DataConnectionString&quot; value=&quot;UseDevelopmentStorage=true&quot; /&gt;
      &lt;Setting name=&quot;Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString&quot; value=&quot;UseDevelopmentStorage=true&quot; /&gt;
    &lt;/ConfigurationSettings&gt;
  &lt;/Role&gt;
  &lt;Role name=&quot;AzureRole.Web&quot;&gt;
    &lt;Instances count=&quot;1&quot; /&gt;
    &lt;ConfigurationSettings&gt;
      &lt;Setting name=&quot;DataConnectionString&quot; value=&quot;UseDevelopmentStorage=true&quot; /&gt;
      &lt;Setting name=&quot;Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString&quot; value=&quot;UseDevelopmentStorage=true&quot; /&gt;
    &lt;/ConfigurationSettings&gt;
  &lt;/Role&gt;
&lt;/ServiceConfiguration&gt;</pre>
<p>As you can see we have a configuration that uses our development storage. If we would deploy using these settings our deployment would simply not start. We could add our connection strings to our production storage, but that would make testing a somewhat delicate process.</p>
<p>What we don’t want to do is to change all connection strings before each commit so that our deployment works. This is exactly the type of manual work that we want to avoid. In other words, this is exactly the type of work we would like to delegate to our build server. So, we create another MSBuild script.</p>
<pre class="brush: xml; ruler: true; gutter: false;">&lt;Project ToolsVersion=&quot;3.5&quot; DefaultTargets=&quot;Deploy&quot; xmlns=&quot;http://schemas.microsoft.com/developer/msbuild/2003&quot;&gt;
  &lt;PropertyGroup Condition=&quot;'$(BuildType)' == ''&quot;&gt;
    &lt;BuildType&gt;Release&lt;/BuildType&gt;
  &lt;/PropertyGroup&gt;

  &lt;!-- Azure Information --&gt;
  &lt;PropertyGroup&gt;
    &lt;HostedServiceName&gt;azureservice&lt;/HostedServiceName&gt;
    &lt;StorageAccountName&gt;azurestorage&lt;/StorageAccountName&gt;
    &lt;StorageAccountKey&gt;****************&lt;/StorageAccountKey&gt;
  &lt;/PropertyGroup&gt;

  &lt;!-- Project/Solution Information --&gt;
  &lt;PropertyGroup&gt;
    &lt;PackageLocation&gt;Artifacts\&lt;/PackageLocation&gt;
    &lt;PackageName&gt;Package.cspkg&lt;/PackageName&gt;
    &lt;ServiceConfigName&gt;ServiceConfiguration.cscfg&lt;/ServiceConfigName&gt;
  &lt;/PropertyGroup&gt;

  &lt;UsingTask AssemblyFile=&quot;lib\BuildTasks\Microsoft.Practices.WindowsAzure.MSBuildTasks.dll&quot; TaskName=&quot;Microsoft.Practices.WindowsAzure.MSBuildTasks.RegexReplace&quot;/&gt;

  &lt;Target Name=&quot;SetConnectionStrings&quot;&gt;
    &lt;RegexReplace
        Pattern='Setting name=&quot;Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString&quot; value=&quot;UseDevelopmentStorage=true&quot;'
        Replacement='Setting name=&quot;Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString&quot; value=&quot;DefaultEndpointsProtocol=https;AccountName=$(StorageAccountName);AccountKey=$(StorageAccountKey)&quot;'
        Files='$(PackageLocation)\$(ServiceConfigName)'/&gt;
    &lt;RegexReplace
        Pattern='Setting name=&quot;DataConnectionString&quot; value=&quot;UseDevelopmentStorage=true&quot;'
        Replacement='Setting name=&quot;DataConnectionString&quot; value=&quot;DefaultEndpointsProtocol=https;AccountName=$(StorageAccountName);AccountKey=$(StorageAccountKey)&quot;'
        Files='$(PackageLocation)\$(ServiceConfigName)'/&gt;
  &lt;/Target&gt;
&lt;/Project&gt;</pre>
<p>I’m guessing that this might need some explaining. Starting with the <strong>Azure Information</strong> we have HostedServiceName which is whatever name you gave your service in the Azure Web Portal. Same goes for StorageAccountName. StorageAccountKey is the secret key used to access your storage.</p>
<p><strong>Project/Solution Information</strong> starts with our PackageLocation. In our case we store our package in a directory called Artifacts. PackageName is simply the name you gave your package when executing cspack and the ServiceConfigName is the name of your configuration file (will most likely always be ServiceConfiguration.cscfg).</p>
<p>As you see, we are also using a task in order to do our RegEx replace. You can either use <a href="http://msbuildtasks.tigris.org/" target="_blank">MSBuild Tasks</a> or download the dll directly from <a href="http://scottdensmore.typepad.com/blog/2010/03/azure-deployment-for-your-build-server.html" target="_blank">Scott Densmore’s blog</a>.</p>
<p>Then we basically do our replacement of our development configuration strings to our production connection strings. Magic!</p>
<h2>Create and upload certificates to Azure</h2>
<p>As it is you cannot deploy to Azure without a certificate that you first upload to your Azure account. You can actually do this quite easily with IIS 7, <a href="http://weblogs.asp.net/scottgu/archive/2007/04/06/tip-trick-enabling-ssl-on-iis7-using-self-signed-certificates.aspx" target="_blank">the Gu shows you how</a>. You can safely ignore everything except on how to create the Self Signed Certificate.</p>
<p>Once you have your certificate you need move it to your personal certificates and export it. You can do this by opening Microsoft Management Console (by typing launching Run and type mmc). There you can press Ctrl + M and then choose Certificates and press “Add &gt;” and then “Finish”.</p>
<p>First navigate to <em>Trusted Root Certification Authorities\Certificates</em> and find your newly created certificate. Then drag and drop it in the <em>Personal\Certificates</em> folder. Now right click and choose Export.</p>
<p><strong>Important</strong>, make sure that the user that runs the TeamCity BuildAgent have the certificate in its Personal folder as well. It’s not going to work otherwise.</p>
<p>Now you only need to upload your certificate. Browse to the <a href="http://windows.azure.com/" target="_blank">Management Portal</a> and then on the left side find <em>Management Certificates</em>. There you can choose to upload your newly created certificate.</p>
<h2>Use PowerShell and Azure Service CmdLets to deploy to Azure</h2>
<p>Stay strong, only one more step before we can tie it all together. Now we have a package ready for deployment, we have a configuration file with the correct configuration strings and we have a certificate that allows us to deploy all of this to Windows Azure. The final step is to actually deploy everything that we fought so hard to build and configure.</p>
<p>We’ll be using PowerShell and <a href="http://archive.msdn.microsoft.com/azurecmdlets/" target="_blank">Windows Azure Service Management CmdLets</a>.</p>
<p>First you need to download the setup file from their web page and then execute it on the build server. Then it’s time to start writing the script (almost an exact copy of Scott Densmore’s script, thanks again!).</p>
<pre class="brush: ps; ruler: true; gutter: false;">$cert = Get-Item cert:\CurrentUser\My\***********

$sub = &quot;********-****-****-****-************&quot;
$buildPath = $args[0]
$packagename = $args[1]
$serviceconfig = $args[2]
$servicename = $args[3]
$storageservicename = $args[4]
$package = join-path $buildPath $packageName
$config = join-path $buildPath $serviceconfig
$a = Get-Date
$buildLabel = $a.ToShortDateString() + &quot;-&quot; + $a.ToShortTimeString()

if ((Get-PSSnapin | ?{$_.Name -eq &quot;AzureManagementToolsSnapIn&quot;}) -eq $null)
{
  Add-PSSnapin AzureManagementToolsSnapIn
}

write-host Getting service...
$hostedService = Get-HostedService $servicename -Certificate $cert -SubscriptionId $sub | Get-Deployment -Slot Staging

if ($hostedService.Status -ne $null)
{
    write-host Service found.

    write-host Suspending service...
    $hostedService |
      Set-DeploymentStatus 'Suspended' |
      Get-OperationStatus -WaitToComplete

    write-host Removing deployment...
    $hostedService |
      Remove-Deployment |
      Get-OperationStatus -WaitToComplete
}

write-host Creating staging deployment...
Get-HostedService $servicename -Certificate $cert -SubscriptionId $sub |
    New-Deployment Staging -package $package -configuration $config -label $buildLabel -StorageServiceName $storageservicename |
    Get-OperationStatus -WaitToComplete

write-host Starting staging deployment...
Get-HostedService $servicename -Certificate $cert -SubscriptionId $sub |
    Get-Deployment -Slot Staging |
    Set-DeploymentStatus 'Running' |
    Get-OperationStatus -WaitToComplete

write-host Done!</pre>
<p>If you never seen a PowerShell script before this might seem a little intimidating. I’ll try my best to explain it from the top. First we fetch our certificate and store it in our $cert variable. All the stars that you see is the Thumbprint for the certificate. Then we declare our subscription Id in $sub. We continue to declare a bunch of variables that we need to send in as parameters to the script.</p>
<p>When all variable declaring is done, we make sure that our AzureManagementToolsSnapIn is installed, if not we install it.</p>
<p>The next step is to find out if we already have a running service deployed in our staging environment. If so, we stop and delete it. Then we upload and start our new deployment.</p>
<p>So in order to actually use this script we need to extend our MSBuild script that we used when we replaced our development connection strings with production connection strings. At the end of the file we simply add:</p>
<pre class="brush: xml; ruler: true; gutter: false;">&lt;Target Name=&quot;Deploy&quot; DependsOnTargets=&quot;SetConnectionStrings;Build&quot;&gt;
  &lt;MSBuild
    Projects=&quot;$(AzureProjectPath)\$(AzureProjectName)&quot;
    Targets=&quot;CorePublish&quot;
    Properties=&quot;Configuration=$(BuildType)&quot;/&gt;

  &lt;Exec WorkingDirectory=&quot;$(MSBuildProjectDirectory)&quot;
    Command=&quot; $(windir)\system32\WindowsPowerShell\v1.0\powershell.exe -f deploy.ps1 $(PackageLocation) $(PackageName) $(ServiceConfigName) $(HostedServiceName)&quot; /&gt;

&lt;/Target&gt;</pre>
<p>This will be executed after we updated the configuration file.</p>
<h2>Tie it all together</h2>
<p>So now we need to tie this all together in TeamCity. For our project we have two build configurations that look like this.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/buildconfiguration.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="buildconfiguration" border="0" alt="buildconfiguration" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/buildconfiguration_thumb.png" width="659" height="97" /></a></p>
<p>The first configuration, <em>Build</em>, have three build steps.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/buildsteps.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="buildsteps" border="0" alt="buildsteps" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/buildsteps_thumb.png" width="660" height="180" /></a></p>
<p>We first build the entire project. Then we run all our tests with coverage. Finally, we invoke our BuildPackage.msbuild (that’s the script creating the package file using cspack.exe). We then save our output from the build script as an Artifact.</p>
<p>In our second build configuration, <em>Deploy to Staging</em>, we only have one build step.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/deploystep.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="deploystep" border="0" alt="deploystep" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/deploystep_thumb.png" width="668" height="70" /></a></p>
<p>We simply execute the build script that replaces all the connection strings and deploys the package and configuration file to Windows Azure. Worth noting is that this build configuration have a dependency on the artifact created by <em>Build</em>.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/artifactdependencies.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="artifactdependencies" border="0" alt="artifactdependencies" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/artifactdependencies_thumb.png" width="670" height="71" /></a></p>
<p>The artifact in this case is the Package.cspkg and ServiceConfiguration.cscfg.</p>
<p>That’s it! Now you can either have <em>Deploy to Staging</em> to trigger for each successful build of <em>Build</em> or you could, for example, schedule it to run each morning.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/success_baby.jpg" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="success_baby" border="0" alt="success_baby" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/success_baby_thumb.jpg" width="329" height="219" /></a></p>
<h2>Conclusion</h2>
<p>First of all I would like to say that getting all of this up and running wasn’t easy. My hope is that by writing all of this down in one place I can make it easier for anyone else that wants an automatic deployment for their Azure project.</p>
<p>If you do run into any problems with your deployment (for example that it’s not starting) please have a look <a href="http://msdn.microsoft.com/en-us/library/gg465402.aspx" target="_blank">here</a>. It’s a list of common errors and how to resolve them.</p>
<p>I would also like to recommend taking this example a little further. Now that you can deploy from your build server, there really is nothing stopping you from scheduled tear downs every evening and then redeployment every morning. This will seriously decrease the time you have your application deployed during development, which in turn will decrease the money you have to spend in order to use Azure. Use the cloud as it was intended, only pay for what you use!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/03/20/configuring-automatic-deployment-of-a-windows-azure-application-using-teamcity/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Azure Summit Malmö &#8211; An Azure day hosted by Jayway</title>
		<link>http://blog.jayway.com/2011/03/07/azure-summit-malmo-an-azure-day-hosted-by-jayway/</link>
		<comments>http://blog.jayway.com/2011/03/07/azure-summit-malmo-an-azure-day-hosted-by-jayway/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 19:59:03 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[presentation]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=7489</guid>
		<description><![CDATA[On Thursday 3 mars Jayway hosted an Azure event at Malmö Högskola. It became a great event with about 60 attendees! Content Dag König, Microsoft, kicked off the day, delivering two great presentations. The first session was Introducing Windows Azure followed by Demonstration of Windows Azure. Together, both of the sessions delivered excellent content for anyone [...]]]></description>
			<content:encoded><![CDATA[<p>On Thursday 3 mars Jayway hosted an Azure event at Malmö Högskola. It became a great event with about 60 attendees!</p>
<h2>Content</h2>
<p><a href="http://buzzfrog.blogs.com/" target="_blank">Dag König</a>, <a title="Microsoft" href="http://msdn.microsoft.com/sv-se/" target="_blank">Microsoft</a>, kicked off the day, delivering two great presentations. The first session was <em>Introducing Windows Azure</em> followed by <em>Demonstration of Windows Azure</em>. Together, both of the sessions delivered excellent content for anyone new to Azure. You can download Dag’s slides <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/Azure-Introduktion.pdf" target="_blank">here</a>.</p>
<p>Next up was <a href="http://blogs.msdn.com/b/robf/" target="_blank">Robert Folkesson</a>, <a title="Microsoft" href="http://msdn.microsoft.com/sv-se/" target="_blank">Microsoft</a>. Robert delivered a more advanced session about <em>Azure Best Practices</em>. We learned about poisonous message handling, dynamically adding functionality to a worker role, idempotency and much more. You can find Robert’s slides <a href="http://blogs.msdn.com/b/robf/archive/2011/03/04/m-246-nster-f-246-r-skalbara-och-dynamiska-molntj-228-nster-presentation-fr-229-n-azure-summit-malm-246.aspx" target="_blank">here</a>.</p>
<p>After lunch <a href="http://twitter.com/#!/henrikfeldt" target="_blank">Henrik Feldt</a>, <a title="Jayway" href="http://www.jayway.com" target="_blank">Jayway</a>, continued with a session on <em>Azure AppFabric ServiceBus</em>. Henrik gave a deep technical presentation where he demonstrated the ServiceBus and encouraged discussion. Henrik’s slides can be downloaded <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/ServiceBus.pdf" target="_blank">here</a>.</p>
<p>Then it was my turn. I gave a session titled <em>Examples from real life</em>. I gave some examples on how to best utilize your workers and how we design them so that we easily can add more functionality without adding to the cost. I also spoke about continuous integration and lessons learned. You can download my presentation <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/Real-life-examples.pdf" target="_blank">here</a>.</p>
<h2>Thank you</h2>
<p>Thanks to all of you that attended and helped making this a great event! I hope that we can do this again sometime in the future.</p>
<p><a rel="lightbox" href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/ThankYouLarge.gif"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px; border-width: 0px;" title="ThankYouLarge" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/03/ThankYouLarge_thumb.gif" border="0" alt="ThankYouLarge" width="240" height="240" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/03/07/azure-summit-malmo-an-azure-day-hosted-by-jayway/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making the most out of your WorkerRoles</title>
		<link>http://blog.jayway.com/2011/02/20/making-the-most-out-of-your-workerroles/</link>
		<comments>http://blog.jayway.com/2011/02/20/making-the-most-out-of-your-workerroles/#comments</comments>
		<pubDate>Sun, 20 Feb 2011 22:54:57 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[IoC]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=7223</guid>
		<description><![CDATA[When creating your first WorkerRole you probably have a particular task in mind. It could be to generate a report every night or perhaps to send a welcome mail to newly registered users. The problems begins when you have another task that needs a worker, or a third. What you don’t want to do is [...]]]></description>
			<content:encoded><![CDATA[<p>When creating your first WorkerRole you probably have a particular task in mind. It could be to generate a report every night or perhaps to send a welcome mail to newly registered users. The problems begins when you have another task that needs a worker, or a third. What you don’t want to do is to create a new WorkerRole instance for each task. You’ll be wasting both time and money. </p>
<p>This post will show you how to make the most of a single WorkerRole instance. I’ll use StructureMap but you can just as well use any IoC container.</p>
<h2>Why?</h2>
<p>Right, so the scenario that we try to avoid is the one where you create a new WorkerRole instance for each specific task.</p>
<h2><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/02/image.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; margin: 0px 6px 6px 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Worker" border="0" alt="I generate thumbnails" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/02/image_thumb.png" width="174" height="186" /></a><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/02/image1.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; margin: 0px 6px 6px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Worker" border="0" alt="I send e-mails" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/02/image_thumb1.png" width="174" height="186" /></a><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/02/image2.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 6px 6px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Worker" border="0" alt="I generate reports" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/02/image_thumb2.png" width="174" height="186" /></a></h2>
<p>The thing is, if you only need to generate reports once every night you’ll end up with a WorkerRole that sleeps most of the time. The other two instances will probably have something to do every now and then, but not nearly enough to occupy an entire dedicated WorkerRole instance. The primary reason for avoiding this is of course the cost (since you need to pay for every instance), but also the amount of work when creating a new work task. You’ll basically have to create a new project every single time you need some a new type of worker.</p>
<h2></h2>
<h2></h2>
<h2>What then?</h2>
<p>What you want is something like this.</p>
<h2><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/02/image3.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 6px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Worker" border="0" alt="We can do anything" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/02/image_thumb3.png" width="316" height="198" /></a></h2>
<p>Instead of having three instances we have three workers on a single instance. This is both cost effective and we can easily add more workers as we need them.</p>
<h2>How?</h2>
<p>Well to start with I have an IWorker that looks like this.</p>
<pre class="brush: csharp; ruler: true; gutter: false;">

public interface IWorker
{
    int Priority { get; }
    bool HasWork { get; }
    void DoWork();
}
</pre>
<p>It’s a simple interface that gives us two properties and one method to implement. Priority will be used when sorting the workers. HasWork will tell us if the current worker has any job that needs doing. Finally, DoWork is where the Worker will do his task. </p>
<p>So, take for example the worker that sends e-mails, let’s call him SendMailWorker.</p>
<pre class="brush: csharp; ruler: true; gutter: false;">public class SendMailWorker : IWorker
{
    private readonly IMailQueue _mailQueue;
    private readonly IMailSender _mailSender;

    public SendMailWorker(IMailQueue mailQueue, IMailSender mailSender)
    {
        _mailQueue = mailQueue;
        _mailSender = mailSender;
    }

    public int Priority { get { return 1; } }

    public bool HasWork { get { return _mailQueue.ContainsAnyMessages(); } }

    public void DoWork()
    {
        var message = _mailQueue.GetMessage();
        _mailSender.SendMail(message.AsString);
        _mailQueue.DeleteMessage(message);
    }
}</pre>
<p>As you can see we take two dependencies in our constructor, IMailQueue and IMailSender. IMailQueue is basically a wrapper for an Azure Queue where we put our e-mails that we want to send and IMailSender actually sends our mail for us. If we would like to have another type of worker we would simply inject other dependencies in the constructor. </p>
<p>If we take a look at the HasWork property we see that we only check if the Queue contains any messages, actually we do a PeekMessage() on the queue.</p>
<p>The other two workers will look quite similar so I’ll skip posting their implementation, I’m guessing that you understand my point by now.</p>
<p>Now, in the StartUp method for the WorkerRole I’ll bootstrap StructureMap. </p>
<pre class="brush: csharp; ruler: true; gutter: false;">public override bool OnStart()
{
    ObjectFactory.Configure(x =&gt; x.Scan(scanner =&gt;
                    {
                        scanner.WithDefaultConventions();
                        scanner.TheCallingAssembly();
                        scanner.AssemblyContainingType&lt;IMailQueue&gt;();
                        scanner.AddAllTypesOf&lt;IWorker&gt;();
                    }));

    return base.OnStart();
}</pre>
<p>WithDefaultConventions tells StructureMap to register all instances that follow the pattern IFoo with the implementation Foo. TheCallingAssembly will look for instances to register in the executing assembly. By specifying AssemblyContainingType&lt;IMailQueue&gt; I make sure that we register both the IMailSender and IMailQueue, both located in the same assembly. Finally, AddAllTypesOf&lt;IWorker&gt; will register any class implementing IWorker. </p>
<p>Now we are ready to add some code to our Run method.</p>
<pre class="brush: csharp; ruler: true; gutter: false;">public override void Run()
{
    var workersInPriorityOrder = ObjectFactory.GetAllInstances&lt;IWorker&gt;()
                                              .OrderBy(w =&gt; w.Priority)
                                              .ToList();
    while (true)
    {
        foreach (var worker in workersInPriorityOrder)
        {
            if(worker.HasWork)
            {
                worker.DoWork();
            }
        }
        Thread.Sleep(10000);
    }
}</pre>
<p>So, the first thing that we do is to fetch all registered instances of IWorker and sort them in priority order. Then we enter our infinite loop and start to process them one by one. </p>
<h2>Result</h2>
<p>If we would like to add another worker, all we have to do is to have implement IWorker. Then our IoC container will take care of the rest. Also, by injecting any external dependencies in the constructor we can easily implement our worker to do any kind of job. So we have both simplified the task of adding a new Worker and we also made it “free”. Success!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/02/20/making-the-most-out-of-your-workerroles/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using StructureMap with WCF in Azure</title>
		<link>http://blog.jayway.com/2011/02/17/using-structuremap-with-wcf-in-azure/</link>
		<comments>http://blog.jayway.com/2011/02/17/using-structuremap-with-wcf-in-azure/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 12:20:00 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=7074</guid>
		<description><![CDATA[I currently have the luxury of starting out on a green field Azure project. Naturally you start out with the intention that this will be the project where everything is done right (let’s see how that goes) from start. Besides delivering what the customer wants, for me, done right includes well designed code, well tested [...]]]></description>
			<content:encoded><![CDATA[<p>I currently have the luxury of starting out on a green field Azure project. Naturally you start out with the intention that this will be the project where everything is done right (let’s see how that goes) from start. Besides delivering what the customer wants, for me, done right includes well designed code, well tested code and (since we are using Azure) highly scalable code.</p>
<p>In this project we have a REST WCF service that will be called by devices such as WP7, iPhone and Android phones. This service is then used to create users and then persist them into Azure Table Storage. In order to fulfill my “done right” criteria I want to be able to inject dependencies into the constructors of the WCF services to make them easier to test. I also would like to delegate the instantiation work to <a href="http://structuremap.net/structuremap/" target="_blank">StructureMap</a>. To set all of this up we’ll have to</p>
<ol>
<li>Implement our own <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx" target="_blank">IInstanceProvider</a> </li>
<li>Implement our own <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.aspx" target="_blank">IServiceBehaviour</a> </li>
<li>Override <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webservicehost.aspx" target="_blank">WebServiceHost</a> </li>
<li>Override <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.webservicehostfactory.aspx" target="_blank">WebServiceHostFactory</a> </li>
<li>Make sure that our WCF service use our own <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.webservicehostfactory.aspx" target="_blank">WebServiceHostFactory</a> </li>
<li>Register our dependencies in <a href="http://structuremap.net/structuremap/" target="_blank">StructureMap</a> </li>
<li>Taste the glory </li>
</ol>
<p>I realize that it looks to be a lot of work, but the implementations really are straight forward and easy to follow. Basically, our end goal is to have our WCF service look something like this.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public class UserService : IUserService
{
    private readonly IUserRepository _userRepository;

    public UserService(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public bool CreateUser(string name, string address, string mail)
    {
        var user = new User(name, address, mail);
        if(user.IsValid())
        {
            _userRepository.CreateNewUser(user);
            return true;
        }
        return false;
    }
}</pre>
<p>By injecting an IUserRepository directly in the constructor we can easily test this class using mocking tools such as <a href="http://www.ayende.com/projects/rhino-mocks.aspx" target="_blank">Rhino Mocks</a>. Now, to be able to write our services like this we need to do two things. First we need replace the factories instantiating our UserService so that we can create them using constructors taking parameters. Secondly, we need to make sure that our implementation of IUserRepository is registered in StructureMap.</p>
<p>Before we start I would like to mention that I had a lot of help from both <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/07/29/integrating-structuremap-with-wcf.aspx" target="_blank">Jimmy Bogard’s post</a> and <a href="http://blogs.planbsoftware.co.nz/?p=492" target="_blank">PlanB Software’s post</a> (thanks for you help!).</p>
<h2></h2>
<h2>Create our own WCF instances</h2>
<p>In order to create our own WCF instances we need to implement our own <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx" target="_blank">IInstanceProvider</a>. This will allow us to create our instances using StructureMap.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public class StructureMapInstanceProvider : IInstanceProvider
{
    private readonly Type _serviceType;

    public StructureMapInstanceProvider(Type serviceType)
    {
        _serviceType = serviceType;
    }

    public object GetInstance(InstanceContext instanceContext)
    {
        return GetInstance(instanceContext, null);
    }

    public object GetInstance(InstanceContext instanceContext, Message message)
    {
        return ObjectFactory.GetInstance(_serviceType);
    }

    public void ReleaseInstance(InstanceContext instanceContext, object instance)
    { }
}</pre>
<p>As you can see, in GetInstance(…), we call StructureMap’s ObjectFactory to create the instance for us. Now we have to tell WCF to actually use our own InstanceProvider instead of the default. In order to do that we need to implement <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.aspx" target="_blank">IServiceBehaviour</a>.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public class StructureMapServiceBehavior : IServiceBehavior
{
    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        var endpointDispatchers = serviceHostBase.ChannelDispatchers
                                                 .OfType&lt;ChannelDispatcher&gt;()
                                                 .SelectMany(cd =&gt; cd.Endpoints);

        foreach (var endpointDispatcher in endpointDispatchers)
        {
            endpointDispatcher.DispatchRuntime.InstanceProvider =
                new StructureMapInstanceProvider(serviceDescription.ServiceType);
        }
    }

    public void AddBindingParameters(ServiceDescription serviceDescription,
                                     ServiceHostBase serviceHostBase,
                                     Collection&lt;ServiceEndpoint&gt; endpoints,
                                     BindingParameterCollection bindingParameters)
    { }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    { }
}</pre>
<p>Here we make sure that we use our own StructureMapInstanceProvider for each endpoint. Now it’s time to add this behavior to our WCF service. First, we will override the default <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webservicehost.aspx" target="_blank">WebServiceHost</a>.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public class StructureMapWebServiceHost : WebServiceHost
{
    public StructureMapWebServiceHost(object singletonInstance, params Uri[] baseAddresses)
        : base(singletonInstance, baseAddresses)
    { }

    public StructureMapWebServiceHost(Type serviceType, params Uri[] baseAddresses)
        : base(serviceType, baseAddresses)
    { }

    protected override void OnOpening()
    {
        Description.Behaviors.Add(new StructureMapServiceBehavior());
        base.OnOpening();
    }
}</pre>
<p>In OnOpening() we make sure that we add our own StructureMapServiceBehavior. In order to have WCF use our StructureMapWebServiceHost we also need to override <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.webservicehostfactory.aspx" target="_blank">WebServiceHostFactory</a>.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public class StructureMapWebServiceHostFactory : WebServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        return new StructureMapWebServiceHost(serviceType, baseAddresses);
    }
}</pre>
<p>Finally, since this is a REST WCF Service, we add in our Global.asax.cs. As you can see we also specifies that it should use our StructureMapWebServiceHostFactory.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public class Global : HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes();
    }        

    private void RegisterRoutes()
    {
        RouteTable.Routes.Add(new ServiceRoute(&quot;UserService&quot;, new StructureMapWebServiceHostFactory(), typeof(UserService)));
    }
}</pre>
<p>That’s it! We have replaced the default WCF instantiation with our own. Now to the next part, register our IUserRepository in StructureMap.</p>
<h2>Register types in StructureMap</h2>
<p>First of all, let’s take a look at the implementation of IUserRepostory.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">public class UserRepository : IUserRepository
{
    private readonly UserServiceContext _userServiceContext;

    public UserRepository(UserServiceContext userServiceContext)
    {
        _userServiceContext = userServiceContext;
    }

    public void CreateNewUser(User newUser)
    {
        _userServiceContext.AddObject(_userServiceContext.TableName, newUser);
        _userServiceContext.SaveChangesWithRetries();
    }
}</pre>
<p>As you can see we take a UserServiceContext as a parameter in the constructor. This is our way into Azure Table Storage. Since we don’t inject a interface in the constructor, this class will be quite hard to test. So we’ll try to keep this class as simple and without logic as much as possible.</p>
<p>Since the WCF Service runs in an Azure WebRole, my first thought was to initialize the ObjectFactory in the OnStart() method of the <a href="http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.serviceruntime.roleentrypoint.aspx" target="_blank">RoleEntryPoint</a>. From personal experience I can tell you that it won’t work, at least not in Azure SDK 1.3. Instead I put the initialization in Global.asax.cs Application_Start(…) method.</p>
<pre class="brush: csharp; ruler: true; auto-links: false; smart-tabs: false;">void Application_Start(object sender, EventArgs e)
{
    Bootstrap();
    RegisterRoutes();
}

public void Bootstrap()
{
    var storageCredentials = CloudStorageAccount.FromConfigurationSetting(&quot;DataConnectionString&quot;).Credentials;
    var cloudTableClient = CloudStorageAccount.FromConfigurationSetting(&quot;DataConnectionString&quot;).CreateCloudTableClient();
    var tableEndpoint = cloudTableClient.BaseUri;

    ObjectFactory.Initialize(x =&gt;
    {
        x.Scan(scanner =&gt;
        {
            scanner.AssemblyContainingType&lt;IUserRepository&gt;();
            scanner.TheCallingAssembly();
            scanner.LookForRegistries();
            scanner.WithDefaultConventions();
        });
        x.For&lt;UserServiceContext&gt;().Use(() =&gt; new UserServiceContext(tableEndpoint, storageCredentials));
    });
}</pre>
<p>There is really no magic here (except the awesomeness of StructureMap). We let StructureMap scan our assemblies for type to register and we specifically tell it how to create the UserServiceContext so that it can be injected into our UserRepository.</p>
<h2>Summary</h2>
<p>With all this in place we basically have our infrastructure completed and hopefully we only need to make few, if any changes, while developing. We only use StructureMap directly in two places so we don’t need take any special care depending on which IoC container we use. It’s simply enough to create new types and inject them into the constructors and StructureMap will find and register them as we go.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/02/17/using-structuremap-with-wcf-in-azure/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Deleting All Your Files on Amazon S3</title>
		<link>http://blog.jayway.com/2010/04/20/deleting-all-your-files-on-s3/</link>
		<comments>http://blog.jayway.com/2010/04/20/deleting-all-your-files-on-s3/#comments</comments>
		<pubDate>Tue, 20 Apr 2010 14:15:07 +0000</pubDate>
		<dc:creator>Adam Skogman</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5377</guid>
		<description><![CDATA[How to recursively delete all your files in all your buckets on an S3 account.]]></description>
			<content:encoded><![CDATA[<p>Deleting all your files on S3 is not as easy as you may think, since it requires you to delete all files, one by one, before you can remove the buckets.</p>
<p>Thankfully, this can be done using a small ruby script. First, install the needed ruby gems:</p>
<pre>
>sudo gem install right_aws
</pre>
<p>Then, paste this into your text editor, and edit before you run:</p>
<pre class="ruby">&nbsp;
<span style="color:#008000; font-style:italic;">#!/usr/bin/env ruby -w</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'rubygems'</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'right_aws'</span>
&nbsp;
s3 = <span style="color:#6666ff; font-weight:bold;">RightAws::S3</span>.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>aws_access_key=<span style="color:#996600;">'your-access-key-here'</span>, aws_secret_access_key=<span style="color:#996600;">'your-secret-access-key-here'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
s3.<span style="color:#9900CC;">buckets</span>.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> |bucket|
&nbsp;
  keys = bucket.<span style="color:#9900CC;">keys</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'max-keys'</span>=&gt;<span style="color:#006666;">1000</span> <span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">while</span> keys.<span style="color:#9900CC;">length</span> &gt; <span style="color:#006666;">0</span> <span style="color:#9966CC; font-weight:bold;">do</span>
    keys.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> |key|
      <span style="color:#CC0066; font-weight:bold;">puts</span> key.<span style="color:#9900CC;">full_name</span>
      key.<span style="color:#9900CC;">delete</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
    keys = bucket.<span style="color:#9900CC;">keys</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'max-keys'</span>=&gt;<span style="color:#006666;">1000</span> <span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  bucket.<span style="color:#9900CC;">delete</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;</pre>
<p>Note that I only get a 1000 keys at a time. Having a lot of files in a bucket will break most GUI tools, because they try to do to much - like listing all of my files...</p>
<p>Happy deleting!</p>
<p><strong>Tip:</strong> Run this for an instance on Amazon, not from your own computer. Running inside Amazon is much faster.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/04/20/deleting-all-your-files-on-s3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Neo4j .NET Client over HTTP using REST and json</title>
		<link>http://blog.jayway.com/2010/04/16/neo4j-net-client-over-http-using-rest-and-json/</link>
		<comments>http://blog.jayway.com/2010/04/16/neo4j-net-client-over-http-using-rest-and-json/#comments</comments>
		<pubDate>Fri, 16 Apr 2010 09:49:25 +0000</pubDate>
		<dc:creator>Magnus Mårtensson</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[httpclient]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[neo4j]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/2010/04/16/neo4j-net-client-over-http-using-rest-and-json/</guid>
		<description><![CDATA[Here it is; a Proof of Concept of the world’s first Neo4j .NET Client. In other words: Here follows a discussion on how to create a client library for communicating with a graph database over REST. UPDATE: There is now a live CodePlex project for the realization of this concept; A .NET Client Library for [...]]]></description>
			<content:encoded><![CDATA[<p>Here it is; a <a href="http://en.wikipedia.org/wiki/Proof_of_concept">Proof of Concept</a> of the world’s first Neo4j .NET Client. In other words: Here follows a discussion on how to create a client library for communicating with a graph database over <a href="http://en.wikipedia.org/wiki/REST">REST</a>.</p>
<p><strong>UPDATE:</strong> There is now a live CodePlex project for the realization of this concept; A .NET Client Library for Neo4j over HTTP using REST and JSON; <a title="http://neo4jrestsharp.codeplex.com/" href="http://neo4jrestsharp.codeplex.com/">http://neo4jrestsharp.codeplex.com/</a></p>
<h3>Intro</h3>
<p><a href="http://neotechnology.com/">Neo Technologies</a> have come out with a <a href="http://components.neo4j.org/neo4j-rest/">Neo4j REST API</a> for their popular Neo4j graph database. Since I am employed at <a href="http://jayway.com">Jayway</a> and a couple of colleagues working with Neo are too a little bird by the name of <a href="http://twitter.com/peterneubauer/status/11761202320">Peter Neubauer tweeted in my ear</a> that there was a free T-Shirt involved in making a working sample for .NET that communicated with the Neo4j server. Not only was that a handsome offer – I wanted to check out what the <em>Architecture</em> of such a client library for a graph database would look like.</p>
<p>I’ve recently been involved in client library abstractions and good architecture with the RESTful interface to <a href="http://www.microsoft.com/windowsazure/windowsazure/">Windows Azure Storage</a>. (More on Azure and storage on my blog <a href="http://blog.noop.se/archive/2009/11/29/azure-contrib-codeplex-updated-to-the-november-ctp.aspx">here</a>, <a href="http://blog.noop.se/archive/2009/08/15/introducing-the-cloud-storage-api.aspx">here</a>, <a href="http://blog.noop.se/archive/2009/08/17/using-the-cloudstorage.api-the-message-queue.aspx">here</a>, <a href="http://blog.noop.se/archive/2009/08/19/using-the-cloudstorage.api-the-blob-storage.aspx">here</a> and <a href="http://blog.noop.se/archive/2009/08/20/using-the-cloudstorage.api-the-entity-storage.aspx">here</a>.) Enough with the side tracking (sorry)!</p>
<p>Said and done; We set out to code up a working sample for .NET. I hacked the client code. The Neo-guys cheered me on and offered very helpful assistance when I ran into trouble or was just plane stumped on how to proceed with the API. A very nice team effort, including a remote team debugging session, later and we have a small and running POC</p>
<p>Tweeting on this effort it is notable how a bunch of people answer back with an interest in this idea for potential applications in the .NET world. I’ve been approached both on twitter (<a href="http://twitter.com/noopman">@noopman</a>) and on <a href="http://se.linkedin.com/in/noopman">LinkedIn</a> with questions on this.</p>
<p>This blog post is to submit our findings to the world and hope that someone will be inspired to get going with a real .NET client library for Neo4j.</p>
<h3>Architecture</h3>
<p>First let’s look at the architecture for creating a client library for a RESTful service. This is a more general discussion that leads to our client library POC below. If your main reason for reading is the actual sample; scroll down.</p>
<p>When doing a client library abstractions and domain thinking comes into play. What we want is for the forgotten users (developers) of your application to work with their normal domain objects in the business code and for them to use an API that makes sense to their domain while talking to a highly specific graph database backend store. This means you have to keep all the RESTfulness, HTTP and <a href="http://json.org/">json</a> away from the domain code. Let me show you a sketch and see if I can make this explanation a bit less wordy:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/image.png" rel="lightbox"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/image_thumb.png" width="563" height="551" /></a> </p>
<p>At the other side of the Cloud from our .NET code is a Java based graph database. It is friendly enough to expose a RESTful API so that we may speak to it.</p>
<p>Doing so we want to create a client library that is capable of a couple of things:1) Taking care of serializing objects to json (and deserializing them back again). 2) Knowing about HTTP requests and how to handle them. In our sample we employed the power of the <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx">HttpWebRequest</a> class to handle things like HTTP Headers, Content Types, URIs etc. 3) Finally this library must understand to expose an interface to your code that you can use from a specialized Data Access Component.</p>
<p>To protect the business layer from knowing anything about the specifics of the Neo4j API you really should use a specialized Data Access Component. There is now law being broken if you don’t do that. However a good rule of thumb is to add abstraction layers in your system to shield your domain code in your business components from any specifics of an underlying storage structure. The details of serialization of objects to json and making requests over HTTP are not a natural fit to the business problem you are solving. The code that does this separation is code you write yourself in your application. Only you know how to adapt a foreign library and technology to your domain. The sole purpose of this code, in other words, is to abstract away from your business logic the underlying technologies used to persist and query data used in the application. This component translates between the two worlds of your business logic and the techniques used to store data in a graph database. Most of the specific technical details of storage are wrapped up in the Client Lib mind you but the Data Access Layer DAL knows about this problem domain. It understands that the persistence indeed is a REST based service over HTTP with all that this entails. This component in your code can handle synchonisity and take care of specific errors or faults that may occur when using the storage. All of this is done in a language that is fairly close to the API that Neo4j exposes. In the end this component translates into terms useful to the domain in which your business operates. Instead of saying .PostNode() in your code perhaps you instead expose a .StorePerson() action.</p>
<p>What we achieve is a good and sound (and classic) layering model: Business Logic – DAL – Client Lib.</p>
<p>There is one more observation to make in the picture and that is the matter of <a href="http://en.wikipedia.org/wiki/Inversion_of_control">IoC - Inversion of Control</a>. In order to keep your code testable, maintainable and untangled from the implementations at lower layers you should always employ the method of Inversion of Control – making your business code for instance not reference the DAL direct but instead use a common contract to do so. The <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle">Depencency Inversion Principle</a> states briefly that a higher layer should never depend direct on a lower layer but instead depend on an abstraction. If this is true you are able to test your business logic without using the actual underlying storage. This is for instance key in a <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD – Test Driven Development</a> development style.</p>
<p>Code that depends on abstractions can be tested very quickly and does not depend on specific data in a data store to be correct in order to test the intended behavior. The Business Logic uses a contract for the DAL and the DAL implements it. Then you use something called an IoC container (read on at Wikipedia in the link above) to create the DAL instances and hand them to the Business Logic employing the technique of <a href="http://en.wikipedia.org/wiki/Dependency_injection">DI -Dependency Injection</a>. This separation enables you to modify, re-deploy or even exchange DAL components without having to touch your Business Layer at all. If separating the Business Logic from the DAL using contracts is important it is almost event more important to do so in the lower layer that in run time speaks direct to the data store! You never want to end up in the situation where in order to test your DAL code you have to have access to a specific data store with specific data in it. Not only is that an inconvenience; it also makes executing your tests run as slow as transferring data over the Internet compared to as fast as your CPU can execute code. From experience it is an obvious conclusion that tests that are slow to run are not in fact run. The conclusion from all of these IoC discussions can only be that it is imperative that your Client Library comes with an abstraction layer.</p>
<h4>What did we do with the Architecture in our POC?</h4>
<p>All of these architectural considerations are of course premature in a POC. This is why in our sample we did not really separate the DAL code from the Client Lib. However to prove the point of IoC and DI I did however separate out the Business Logic from the Data Access logic using a simple contract and an equally simple <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">Factory Method Pattern</a>. Instead of new:ing up a DAL component in my code I called a factory method to access an abstraction of the DAL.</p>
<h3>Our POC sample</h3>
<p>Our code sample creates a small node graph with a few relationships. Then it makes a traversal of the graph to find all who “knows” someone according to the relationships. Finally it deletes the graph again.</p>
<p>Here is the graph we create in our sample: <a title="http://wiki.neo4j.org/content/The_Matrix" href="http://wiki.neo4j.org/content/The_Matrix">http://wiki.neo4j.org/content/The_Matrix</a> We only create names on nodes and types on relationships in our simple sample.</p>
<p>And here is also the code so that you may download and follow along with our explanation your self:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F60BB8FA-6F02-4999-8F5E-9DD4E92C4DA7:2ece3c0c-e960-4fb6-bcfc-b89358d619c9" class="wlWriterEditableSmartContent">
<div><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/Neo4j.POC.zip" target="_self">Neo4j.POC.zip</a></div>
</div>
<p>First, in accordance with architectural considerations (above) we get hold of our DAL using a factory method. We also create a new Person object and store him (in this case Thomas Anderson – Neo):</p>
<pre class="code"><span style="color: #2b91af">INeo4jStorageClient </span>neo4JStorageClient =
<span style="color: #2b91af">Neo4jStorageFactory</span>.GetNodeStorageClient(neo4jServerUri);

neo = <span style="color: blue">new </span><span style="color: #2b91af">Person</span>(<span style="color: #a31515">&quot;Thomas Anderson&quot;</span>);
neo4JStorageClient.StoreNode(neo);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><font color="#222222" face="Verdana">As you can see in our business code this is just standard .NET</font> classes being instantiated and a “Neo” Person is stored in a very normal way. In the business logic code there is no real details on how this storage happens. There is of course a “node” concept and you can consider for your self if that should be hidden away from business code too.</p>
<p>Since this is a POC the implementation of .StoreNode(neo) is very very trivial. If this were a real client library we would have included things like a library to transform (serialize) the neo-Person node into a json string. Now we just do it statically:</p>
<pre class="code"><span style="color: blue">public void </span>StoreNode(<span style="color: #2b91af">Person </span>person)
{
    <span style="color: blue">var </span>name = person.Name;

    <span style="color: blue">string </span>jsonString = <span style="color: #a31515">@&quot;{&quot;&quot;Name&quot;&quot;:&quot;&quot;&quot; </span>+ name + <span style="color: #a31515">@&quot;&quot;&quot;}&quot;</span>;

    <span style="color: blue">var </span>nodeProtocol = <span style="color: blue">new </span><span style="color: #2b91af">NodeProtocol</span>(uri);

    <span style="color: blue">var </span>nodeId = nodeProtocol.PostNode(jsonString);
    person.Id = nodeId;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The interesting part here is the existence of a <span style="color: #2b91af">NodeProtocol</span> implementation. I’ve found it useful working with a remote API like Windows Azure Storage and also with this Neo4j REST API to implement methods in C# code that correlate very closely to the API methods available. In our case we have a PostNode operation on the REST API and consequently we have a .PostNode() method in the C# implementation of that HTTP method call.</p>
<pre class="code"><span style="color: blue">public int </span>PostNode(<span style="color: blue">string </span>nodeData)
{
    <span style="color: blue">var </span>uri = <span style="color: #2b91af">HttpHelper</span>.ConcatUri(baseUri, <span style="color: #a31515">&quot;node&quot;</span>);

    <span style="color: #2b91af">HttpWebRequest </span>request =
        <span style="color: #2b91af">Request</span>.CreateWebRequest(<span style="color: #2b91af">HttpWebRequestMethod</span>.POST, uri);

    <span style="color: #2b91af">HttpHelper</span>.AddBody(request, nodeData);

    <span style="color: blue">var </span>response = requestMaker.MakeRequest(request);

    <span style="color: blue">return </span><span style="color: #2b91af">HttpHelper</span>.FindNodeId(response.Item3);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>I won’t bore you with the exact details of all of the helper classes. To dig in to those it is better if you just download the code and look at the details your self.</p>
<p>As you can see we create a HttpWebRequest, add some headers to it (in the CreateWebRequest method) specifying things like request.Accept = &quot;application/json&quot;; meaning we accept a json formatted response. Also we specify that the body we send out is formatted as json with request.ContentType = &quot;application/json&quot;;. Finally we make the call and return the id of the node we just created.</p>
<p>Again this is a solution bordering on triviality but still it is to the point of making a REST request and receiving a response. Also there is no code to handle any errors present here and the request is done synchronously.</p>
<p>What does the actual HTTP REST and json request and response look like for this simple sample?</p>
<p>Request:</p>
<pre class="code">

POST <a href="http://try.neo4j.org:9999/node">http://try.neo4j.org:9999/node</a> HTTP/1.1
Content-Type: application/json
Host: try.neo4j.org:9999
Content-Length: 26
Expect: 100-continue
Connection: Keep-Alive

<font style="background-color: #ececec"></font>
{&quot;Name&quot;:&quot;Thomas Anderson&quot;}
</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Response (note that the added line breaks in the response body were added by me):</p>
<pre class="code">

HTTP/1.1 201 Created
server: grizzly/1.8.1
Content-Encoding: UTF-8
Location: <a href="http://try.neo4j.org:9999/node/1">http://try.neo4j.org:9999/node/1</a>

Content-Type: application/json
Content-Length: 860
Date: Fri, 16 Apr 2010 08:36:45 GMT

{&quot;incoming typed relationships&quot;:

<a href="http://try.neo4j.org:9999/node/1/relationships/in/{-list|&amp;|types}">http://try.neo4j.org:9999/node/1/relationships/in/{-list|&amp;|types}</a>,

&quot;incoming relationships&quot;:<a href="http://try.neo4j.org:9999/node/1/relationships/in">http://try.neo4j.org:9999/node/1/relationships/in</a>,

&quot;all relationships&quot;:<a href="http://try.neo4j.org:9999/node/1/relationships/all">http://try.neo4j.org:9999/node/1/relationships/all</a>,

&quot;create relationship&quot;:<a href="http://try.neo4j.org:9999/node/1/relationships">http://try.neo4j.org:9999/node/1/relationships</a>,

&quot;data&quot;:{&quot;Name&quot;:&quot;Thomas Anderson&quot;},

&quot;traverse&quot;:<a href="http://try.neo4j.org:9999/node/1/traverse/{returnType}">http://try.neo4j.org:9999/node/1/traverse/{returnType}</a>,

&quot;property&quot;:<a href="http://try.neo4j.org:9999/node/1/properties/{key}">http://try.neo4j.org:9999/node/1/properties/{key}</a>,

&quot;self&quot;:<a href="http://try.neo4j.org:9999/node/1">http://try.neo4j.org:9999/node/1</a>,

&quot;properties&quot;:<a href="http://try.neo4j.org:9999/node/1/properties">http://try.neo4j.org:9999/node/1/properties</a>,

&quot;all typed relationships&quot;:

<a href="http://try.neo4j.org:9999/node/1/relationships/all/{-list|&amp;|types}">http://try.neo4j.org:9999/node/1/relationships/all/{-list|&amp;|types}</a>,

&quot;outgoing typed relationships&quot;:

<a href="http://try.neo4j.org:9999/node/1/relationships/out/{-list|&amp;|types}">http://try.neo4j.org:9999/node/1/relationships/out/{-list|&amp;|types}</a>,

&quot;outgoing relationships&quot;:<a href="http://try.neo4j.org:9999/node/1/relationships/out">http://try.neo4j.org:9999/node/1/relationships/out</a>}

</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>As you can see the Neo4j REST API is self explanatory. Creating a node gives you back a response with all the things you can now do with this new node over the API. Since this quite a lot of data when the only thing that really matters is in the header (Location: <a href="http://try.neo4j.org:9999/node/1">http://try.neo4j.org:9999/node/1</a>) I’ve already given feedback to the Neo team that I’d like a simple Uri switch (like APIDocumentation=0) to shut off the detailed response. But in fact I do like that you get so many Uris back that you may use direct. Depending on your needs this is either good or to verbose a payload to get back in your response. As you can see the node we created got the Id set to 1.</p>
<p>Now we proceed to create all the other nodes and in a very similar fashion the relationships between nodes. Here is the relationship that says that “Neo knows Trinity” (who has a node id of 2). This is a POST operation to /node/1/relationships:</p>
<pre class="code">

POST <a href="http://try.neo4j.org:9999/node/1/relationships">http://try.neo4j.org:9999/node/1/relationships</a> HTTP/1.1
Content-Type: application/json
Host: try.neo4j.org:9999
Content-Length: 56
Expect: 100-continue

{&quot;type&quot;:&quot;Knows&quot;,&quot;to&quot;:<a href="http://try.neo4j.org:9999/node/2">http://try.neo4j.org:9999/node/2</a>}
</pre>
<p>Once the node graph for the Matrix is created we proceed to make a traversal of the graph. We want to find anyone who knows someone throughout the graph.</p>
<p>The request looks like this in REST (after a similar path through the code as above with a call from business logic to DAL and through to the client lib that makes the actual call using REST):</p>
<pre class="code">

POST <a href="http://try.neo4j.org:9999/node/1/traverse/node">http://try.neo4j.org:9999/node/1/traverse/node</a> HTTP/1.1
Accept: application/json
Content-Type: application/json
Host: try.neo4j.org:9999
Content-Length: 57
Expect: 100-continue
Connection: Keep-Alive

{ &quot;relationships&quot;: { &quot;type&quot;: &quot;Knows&quot; }, &quot;max depth&quot;: 10 }
</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Again we simplified to a “max depth” of 10 relationships deep into the graph which works fine for our sample.</p>
<p>The result is a list of all the nodes that match. Because of the self explanatory API mentioned above the result also gives you actions to perform on each node that comes back in the response thus making the response body quite long. Rather than pasting the whole thing here into the blog post you can try it out your self (by downloading the application) and you will get a result exactly like this from the app:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/image1.png" rel="lightbox"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/image_thumb1.png" width="221" height="222" /></a> </p>
<p>Neo knows Trinity and Morpheus, who knows Cypher, who in turn knows Agent Smith.</p>
<h3>Difficulties</h3>
<p>We had only two real challenges in coding this POC.</p>
<p>The first one was an issue with streams and the optional so called <a href="http://en.wikipedia.org/wiki/Byte_Order_Mark">Byte Order Mark (BOM)</a> that you can put at the head of a stream. I’ve posted on this here: <a href="http://blog.jayway.com/2010/04/14/would-you-like-a-byte-order-mark-to-go-with-that/">Would you like a Byte Order Mark to go with that?</a>.</p>
<p>The other challenge was that I wrote a small app for Windows to show our results. But the guys on the Neo team are certainly not Windows users. The wanted to show the code on Mono. Just to be sure of compatibility I scaled back to a good old Windows Forms demo app in .NET Framework 3.0. This worked great on Mono which was our intent. But the drawback was that the library I’d found to handle object serialization didn’t respond well to that old version of the framework. That’s why I replaced my lib with static string creations (as you can see in the implementation of the .StoreNode() method above).</p>
<h3>What have we learned from this?</h3>
<p>First of all creating a client library for .NET to speak REST and json over HTTP to Neo4j is very doable; quite easy and straight forward.</p>
<p>Second (and that’s just a word of warning); keep your layers separated. This goes for all applications I guess but if you start to put code to create instances of web requests with web methods and content types and such in your business code you will end up in a very tangled and messy situation very fast which will be a pain and a high cost to maintain.</p>
<p>Finally we have considered looking into using <a href="http://msdn.microsoft.com/en-us/data/bb931106.aspx">WCF data services</a> (and <a href="http://www.odata.org/">OData</a> – the Open Data Protocol) and also possibly <a href="http://msdn.microsoft.com/en-us/netframework/aa904594.aspx">Linq</a> – Language Integrated Query on the client side to make implementations in the library even more powerful and useful. And we do need a object to json serializer library.</p>
<p>Oh and here is another post on using the Neo4j REST API by the team itself: <a title="http://blog.neo4j.org/2010/04/neo4j-rest-server-part1-get-it-going.html" href="http://blog.neo4j.org/2010/04/neo4j-rest-server-part1-get-it-going.html">http://blog.neo4j.org/2010/04/neo4j-rest-server-part1-get-it-going.html</a></p>
<p>That’s it!</p>
<p>We hope this is inspirational enough for you to get going with your own samples or even client libraries in .NET to speak to Neo4j. If you do; please get back in touch with us!</p>
<p>Cheers,</p>
<p>M.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/04/16/neo4j-net-client-over-http-using-rest-and-json/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Effective and Infinite storage in the cloud session at TechDays 2010 Sweden</title>
		<link>http://blog.jayway.com/2010/04/06/effective-and-infinite-storage-in-the-cloud-session-at-techdays-2010-sweden/</link>
		<comments>http://blog.jayway.com/2010/04/06/effective-and-infinite-storage-in-the-cloud-session-at-techdays-2010-sweden/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 20:06:59 +0000</pubDate>
		<dc:creator>Magnus Mårtensson</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[sql azure]]></category>
		<category><![CDATA[storage]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[windows azure]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/2010/04/06/effective-and-infinite-storage-in-the-cloud-session-at-techdays-2010-sweden/</guid>
		<description><![CDATA[The main points of our Effective and Infinite Storage in the Cloud session at TechDays 2010 in Sweden are listed below as well as links to all of our related material and the zip with our demos. The slides are here too but they are in Swedish only. Our session at TechDays 2010 gave an [...]]]></description>
			<content:encoded><![CDATA[<p>The main points of our Effective and Infinite Storage in the Cloud session at <a href="http://microsoft.se/techdays">TechDays 2010 in Sweden</a> are listed below as well as links to all of our related material and the zip with our demos. The slides are here too but they are in Swedish only.</p>
<p>Our session at TechDays 2010 gave an overview of what storage in the Cloud is, according to Microsoft at present date, and some of the goals for the future in this area. We intended our session to provide the basis for companies to be able to evaluate if and how moving storage to the Cloud can enhance their business for their own specific scenarios.</p>
<p>Speaking about Cloud storage and Microsoft today means you need to give a session divided into two parts; <a href="http://www.microsoft.com/windowsazure/sqlazure/">SQL Azure</a> and <a href="http://www.microsoft.com/windowsazure/windowsazure/">Windows Azure storage</a>. And so our presentation had two distinct parts.</p>
<p>As consultants working with different clients we see that companies in general are not yet ready to adopt Cloud storage on a broad scale. However we also see a continuous increase in interest in this area and we believe that this is directly related to the richness of the offerings and services now becoming available. The story matures in the Microsoft camp and the pace is rapid. Cloud storage from Microsoft is admittedly still very young. (Youngest in the business?) But now Microsoft has thrown the full weight of the company behind making the cloud story stick. Expect to see a lot of new offerings, services, products, frameworks etc. in the Cloud coming out from Microsoft in the near future.</p>
<p>There are a few common concerns when it comes to storing data in the cloud. A quick (and perhaps not complete) listing follows:</p>
<h3>Storage cost in the Cloud</h3>
<p>One big concern we hear from clients and in the buzz at conferences that take place around now is a concern related to the cost of storage and data transfer in the Cloud. This is naturally an equally important issue regardless in what Cloud you choose to store your data.</p>
<p>The thing about storing your data in the Cloud is that the cost for this storage is a lot more self evident compared to storing your data in your own servers on premise. This is because you receive a bill each month stating exactly what you have spent for storage in the passed period. What we tend to mitigate is that storage, backups, crash plans and managing all of this on premise, or even hosted, does not exactly come for free either. The big question then becomes what difference in cost there will be for your company for storing and transferring data to a Cloud compared to local hardware operated by your local IT department.</p>
<p>Another aspect of the cost for storage in general is the question of how you build your apps. We believe that many have been a bit oblivious to this issue when they have run their apps and stored our data only on premise or with traditional hosting. Perhaps we have been cost inefficient in this area until now? In the age of Soft Deletes - deleting data does not remove it but rather marks it as deleted – no data is ever actually deleted - managing costs for storing data will become a more and more important question for everyone. Building Cloud applications and storing data in the Cloud has to be done with data storing and management costs in mind. As we hinted to above; the same should have been true for all of your applications up until now. Storing data in the Cloud just makes this point more obvious.</p>
<h3>Storage Security when your data in the Cloud</h3>
<p>Perhaps the fist fear when it comes to storing data in the Cloud is the fear of security breeches and the perceived loss of control of this security. Your data is no longer at home.</p>
<p>What you need to ask yourself, and here we choose to quote a good colleague Sergio Molero <a href="http://twitter.com/sergio_molero">@sergio_molero</a>, is; “What sense of security do you have today? What security is it that you think you will loose when storing your data in the Cloud?”</p>
<p>The same exact thing can be said for hosted data as compared to data stored in the Cloud because the two concepts are very much the same thing in this regard. Data in the Cloud is also hosted data!</p>
<p>One important thing to also keep in mind is that moving to a data storage solution in the Cloud does not mean all of your data must move “out there” somewhere. It is still quite possible to store the most sensitive data on premise and use Cloud storage for more public data only. We believe that the higher focus on security for data in the Cloud will put higher focus on your security efforts compared to your present security on premise. The move to the Cloud could in conclusion prove to heighten the overall security level for your data.</p>
<p>Also look into <a href="http://msdn.microsoft.com/en-us/security/aa570351.aspx">Windows Identity Foundation (WIF)</a> for insights on how to secure your data in the Cloud.</p>
<h3>Trusting someone else with your data in the Cloud</h3>
<p>If security from external attacks to your data in the Cloud is a concern you feel somewhat confident you will be able to handle then perhaps trusting someone else with storing your company sensitive data is a concern that causes you to think twice? Trust is a complex issue not to be taken lightly. We will only raise the concern here and not delve too deep into it.</p>
<p>Can you trust a hosted data storage provider today? If you can, then this is no difference compared to trusting data stored in the Cloud.</p>
<p>If you can’t trust anyone else with your data, then the Cloud is not an option for you. Clean and simple.</p>
<h3>Legal ramifications for storing data in the Cloud</h3>
<p>It feels important to also comment briefly on the potential legal ramifications for storing your data in a Cloud in another country somewhere. That being said we’d just like to point out that we are no lawyers. Let’s be clear on that.</p>
<p>Some data cannot legally be moved outside the borders of your own country. Hospital patient information is a good example of this. Other data must for legal reasons stay within your geo-region, say for instance the EU.</p>
<p>As we hinted to above; not all of your data has this limiting concern. You do have more public data as well as more private data in your business. Only the latter is a potential legal problem. There will be more hybrid solutions for data Storage in the future. Some data for a company will be stored in the Clouds and other data will be stored on premise.</p>
<p>But how can we store data both on premise and in the Cloud without having two separate data storage solutions? One thing that will assist in this endeavor is the rumored upcoming availability of local on-premise, or hosted, Clouds that will be possible to install locally and behave in the same way the big Clouds out there on the Internet do. Right now there does not exist many offerings of this nature. There will in time when companies start to demand them. In fact, given that the storage Clouds today has a REST interface, it is not very difficult to implement that same interface on your own on premise machines! Doing this however will require a good effort on your part and you will end up with a proprietary solution that you will have to evolve over time as the real Clouds shift. Another option is to wait a bit and let the Cloud vendors come up with packaged solutions that you may install simply install in your own data centers. The hybrid solutions that will result from this will play an important role in shaping the solutions for data storage for the coming decade.</p>
<h3>SQL Azure</h3>
<p>In our SQL Azure part of our talk we pointed out three pros and three cons for attendees to take away from our session.</p>
<ol>
<li>Because Windows Azure takes care of all of the maintenance normally associated with a SQL Server server developers are now allowed to <strong>focus on the database</strong> rather than performing administrative tasks.</li>
<li>The database is always available in the sense that upgrades are seamless as well as failover, backup and crash plan which means that the SQL Azure database is <strong>always available</strong>.</li>
<li>The <strong>scaling </strong>story is very strong in SQL Azure. If you can shard your database into many pieces you can scale out from one database to many (say 100) databases to meet a peek load and then back down again to just one at will. For now there is no built in support for this in SQL Azure but this will likely be a story further down the road and you can build it your self today.</li>
</ol>
<p>There are some things to consider when looking into deploying to SQL Azure.</p>
<ol>
<li><strong>Security is locked down </strong>compared to SQL Server. The sys-tables are not yet available for instance. This is because your databases are co-located on the same servers as data belonging to some one else.</li>
<li><strong>Your data is no longer at home</strong> in the sense that it is moved outside your company and even outside your country.</li>
<li>The size right now for one database in SQL Azure is 10 GB but this will increase to 50 GB in June.</li>
</ol>
<h3>Windows Azure Storage</h3>
<p>With Windows Azure Storage Microsoft addresses a set of data storage stories that do not really fit well into a standard relational database structure.</p>
<ol>
<li>There is a powerful and “infinite” message queuing system that enables messaging between the different machines in your applications. This queuing system does not guarantee 100% ordering of the messages in the queue. This is in case of more than one machine working on the same queue. However the queues require dequeue (GET) and delete (DELETE) in order to complete an actual removal of a message. This method will ensure each message will actually be handled in full in case of some error when decueing and handling the message the first time.</li>
<li>There is also a concept in Windows Azure of that which is known as a “Big Table”. Say you want to store 200 million user data sets for Facebook or why not all the messages ever sent to Twitter. For this you need an “infinite” tabular structure that has no end that you will ever hit.</li>
<li>The third thing you can store in Windwos Azure are two kinds of blobs. 1) A so called Block Blob. A blob that is handled in blocks when uploaded. A block Blob is not really intended to be changed once uploaded. You can exchange blocks in the blob but that is not the intent. This is typically a video file or a picture or something that is rarely if ever changed. You would use block blobs to build the next youtube where you can stream files down into a player. 2) A Page Blob. This kind of blob is divided into pages rather than blocks. You can real or write pages at will into this kind of blob. This means that you are able to create a Virtual HardDrive (VHD) and upload it as a page blob to Windows Azure. Then you can actually mount this blob to one or more virtual machines in Windows Azure as an extra hard drive. This comes in handy when moving an application to Windows Azure that uses a lot of disk. All of your old File.Open will continue to work.</li>
</ol>
<p>When considering Windows Azure for your storage think about:</p>
<ol>
<li>You should use only the parts of Windows Azure that you really need. If you need to store backup blob type of data – use only that. There is a good advantage to consider when you have applications to run that will use Windows Azure Storage. If you deploy your application to Windows Azure as well as the data to <em>the same</em> datacenter then the internal data transfer costs between this application and storage is without cost. If you instead run your apps on premise and store data in the cloud the transfer of data to and from the cloud carries a cost.</li>
<li>Regarding the cost you should really make a data storage estimate and analysis before you start up deploying. Your application should have a plan for the amount of data stored, transferred and the duration of storage. This is true on premise too, as discussed above, and data storage plans and budgets will become a more and more important part of any application for the future.</li>
<li>Windows Azure Storage means learning to use a new API. Perhaps not a dramatic thing but the three storage options also affects the way you build the rest of your application. If you disagree chances are you need to learn more about storing data in the cloud.</li>
</ol>
<h3>Links</h3>
<p><a href="http://www.microsoft.com/downloads/details.aspx?familyid=AA40F3E2-AFC5-484D-B4E9-6A5227E73590&amp;displaylang=en">Windows Azure SDK</a></p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=5664019e-6860-4c33-9843-4eb40b297ab6&amp;displaylang=en">Windows Azure Tools for Visual Studio</a></p>
<p><a href="http://www.cerebrata.com/Products/CloudStorageStudio/Default.aspx">Cloud Storage Studio</a> – a SSMS look alike for Windows Azure Storage</p>
<p><a href="http://www.fiddler2.com/fiddler2/">Fiddler2</a> – Web debugging proxy</p>
<p><a href="http://cloudstorageapi.codeplex.com/">CloudStorage.API</a> @ CodePlex</p>
<p><a href="http://azurecontrib.codeplex.com/">Azure Contrib</a> @ CodePlex</p>
<p><a href="http://sqlazuremw.codeplex.com/">SQL Azure Migration Wizard</a></p>
<h3>Downloads</h3>
<p>Ziped version of the demo code in the Windows Azure Queue Storage sample:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/AzureStorage1.zip">AzureStorage</a></p>
<p>Slides from the presentation:</p>
<p><a href="http://blog.noop.se/images/blog_noop_se/WindowsLiveWriter/EffectiveandInfinitestorageinthecloudses_CCAA/EffektivOchOandligLagringIMolnet.ppsx">EffektivOchOandligLagringIMolnet.ppsx</a></p>
<p><a href="http://blog.noop.se/images/blog_noop_se/WindowsLiveWriter/EffectiveandInfinitestorageinthecloudses_CCAA/EffektivOchOandligLagringIMolnet.pdf">EffektivOchOandligLagringIMolnet.pdf</a></p>
<p>Slides for the demo attached as a zip above</p>
<p><a href="http://blog.noop.se/images/blog_noop_se/WindowsLiveWriter/EffectiveandInfinitestorageinthecloudses_CCAA/DemoWindowsAzureCloudQueue_1.ppsx">DemoWindowsAzureCloudQueue.ppsx</a></p>
<p><a href="http://blog.noop.se/images/blog_noop_se/WindowsLiveWriter/EffectiveandInfinitestorageinthecloudses_CCAA/DemoWindowsAzureCloudQueue.pdf">DemoWindowsAzureCloudQueue.pdf</a></p>
<h3>Final Words</h3>
<p>We would like to thank Microsoft for arranging TechDays, we had a blast! Thanks to the audience for listening.</p>
<p>Cheers,</p>
<p>Peter von Lochow <a href="http://twitter.com/vonlochow">@vonlochow</a> and Magnus Mårtensson <a href="http://twitter.com/noopman">@noopman</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/04/06/effective-and-infinite-storage-in-the-cloud-session-at-techdays-2010-sweden/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How-to get a large C: drive for Windows on Amazon</title>
		<link>http://blog.jayway.com/2010/03/31/how-to-get-a-large-c-drive-for-windows-on-amazon/</link>
		<comments>http://blog.jayway.com/2010/03/31/how-to-get-a-large-c-drive-for-windows-on-amazon/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 09:08:11 +0000</pubDate>
		<dc:creator>Adam Skogman</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[ebs]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5238</guid>
		<description><![CDATA[Amazon has excellent Windows support these days. Many time you'd like a larger C: drive than the 30 GB that come standard with the Amazon images. Here is how you enlarge the boot drive to 100 GB.]]></description>
			<content:encoded><![CDATA[<p>Amazon has excellent Windows support these days, and computers boot up from EBS. Drives are therefor both fast and robust. However, many time you'd like a larger C: drive than the 30 GB that come standard with the Amazon images. Here is how you enlarge the boot drive!</p>
<p>First step is to boot an instance. You need the command line tools for this, as neither the AWS Management Web Console nor ElasticFox currently supports this right now (note to developers - please add!).</p>
<pre>
ec2-run-instances --region eu-west-1 \
     -K pk-YOURKEYHERE.pem \
     -C cert-YOURCERTHERE.pem \
     <strong>-b '/dev/sda1=:100' \</strong>
     ami-d7a78ca3 \
     -g my-security-group -g common-security-group \
     -t m1.large \
     -k thekeyhere \
     --disable-api-termination \
     --instance-initiated-shutdown-behavior stop \
     -z eu-west-1a
</pre>
<ul>
<li>The command is <strong>ec2-run-instances</strong> with an <strong>'s'</strong> in the end. There is another command in the API without the s, which doesn't work.</li>
<li><strong>-b</strong> is the most important flag here. It says to make the boot disk (/dev/sda is Linux speek for C:) 100 GB, despite what the AMI manifest says (which is 30 GB).</li>
<li><strong>ami-d7a78ca3</strong> is the Windows image, in this case a 64bit Windows 2008.</li>
<li>-g security-group you should add as many as you like. Remember to think these through, since you cannot change which groups an instance belongs to.</li>
<li>The flags <strong>--disable-api-termination --instance-initiated-shutdown-behavior stop</strong> are really nice, because that make sure you cannot accidentally terminate the instance, making the harddrive disappear.</li>
<li>Note that I'm running in the EU region here.</li>
</ul>
<p>Ok, so now you have a running Windows server. Once it has booted, you log on using remote desktop (well, as soon as you have the generated password, which takes 15 min). PLease note that the C: drive will show up as 30 GB at this point. The partition is still only 30 GB, even if the virtual harddrive is 100 GB.</p>
<ol>
<li>Go into the windows management console. Go to <strong>disk management</strong>.</li>
<li><strong>Right-click</strong> on the C: drive. Choose <strong>Extend volume</strong> from the context menu.</li>
<li>In the wizard that pops up, just accept the defaults, and click finish.</li>
</ol>
<p>Done! The change is instant (no reboot or anything), and your system drive C: is now 100 GB.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/03/31/how-to-get-a-large-c-drive-for-windows-on-amazon/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Blogging Among the Clouds</title>
		<link>http://blog.jayway.com/2009/05/07/blogging-among-the-clouds/</link>
		<comments>http://blog.jayway.com/2009/05/07/blogging-among-the-clouds/#comments</comments>
		<pubDate>Thu, 07 May 2009 18:31:57 +0000</pubDate>
		<dc:creator>Henrik Bernström</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[dreamhost]]></category>
		<category><![CDATA[ebs]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[s3]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[ssl]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://79.125.9.149/?p=1619</guid>
		<description><![CDATA[Up until now this WordPress blog has been hosted by DreamHost, a company with a good reputation and a solid knowledge in hosting. Unfortunately, the server we've been located on, Trafficante, have lately had some problems with stability and performance and DreamHost have also had some MySQL stability issues. This, plus the fact that we've [...]]]></description>
			<content:encoded><![CDATA[<p>Up until now this WordPress blog has been hosted by <a href="http://dreamhost.com/aboutus.html">DreamHost</a>, a company with a good reputation and a solid knowledge in hosting. Unfortunately, the server we've been located on, Trafficante, have lately had some problems with stability and performance and DreamHost have also had some MySQL stability issues. This, plus the fact that we've had some really good experience with <a href="http://aws.amazon.com/">Amazons' Web Services</a> has made us take the leap, up among the clouds. </p>
<p>That said, I must also give credit to DreamHost for always being very helpful and supporting when needed.</p>
<p>If you want to know what we did to gain the speed needed for a lift-of, keep on reading.</p>
<h3>Exporting the Existing Database</h3>
<p>I really like MySQL, but when it comes to encoding for character sets and collations there seems to be such a complexity in the details that users often get lost and configure it the wrong way. The UTF-8 configured database we used on DreamHost worked just fine together with our WordPress installation but it turned out to be impossible to export a correct UTF-8 version for importing into our new environment. And I tried a lot of things. Really. I'm not going to go into details but to sum it up I had to sit down and do kind of manual replacements of the swedish specific characters in the database export. Lucky me this blog is in english. </p>
<p>Anyway, I had ssh access to the Trafficante server and could use this connection to export the database from the DreamHost MySQL server by issueing:</p>
<pre class="bash">&nbsp;
mysqldump --default-character-<span style="color: #007800;">set=</span>UTF8 -u <span style="color: #7a0874; font-weight: bold;">&#91;</span>user<span style="color: #7a0874; font-weight: bold;">&#93;</span> -p -h <span style="color: #7a0874; font-weight: bold;">&#91;</span>host<span style="color: #7a0874; font-weight: bold;">&#93;</span>.dreamhosters.com <span style="color: #7a0874; font-weight: bold;">&#91;</span>database<span style="color: #7a0874; font-weight: bold;">&#93;</span> -r <span style="color: #7a0874; font-weight: bold;">&#91;</span>output<span style="color: #7a0874; font-weight: bold;">&#93;</span>.sql
&nbsp;</pre>
<p>This resulted in a database dump later used for importing into the new MySQL instance.</p>
<h3>Setting up the Amazon EC2 Instance</h3>
<p>To make your Amazon life easier start with installing the Firefox plugins <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=609">Elasticfox</a> and <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=771">S3 Organizer</a>. These tools give you a GUI view of the somewhat more complex underlying details of Amazon. </p>
<p>Amazons' cloud solution is based on a user account. There are no start-up fees, you only pay for what you use. So if you still haven't got an account, <a href="http://www.amazon.com/gp/aws/registration/registration-form.html">sign-up now</a>. The rest of this article assumes you have signed up and set up accounts for <a href="http://aws.amazon.com/ec2/">Amazon EC2</a>, <a href="http://aws.amazon.com/s3/">Amazon S3</a> and <a href="http://aws.amazon.com/ebs/">Amazon EBS</a>. Start by reading the <a href="http://docs.amazonwebservices.com/AWSEC2/latest/GettingStartedGuide/">EC2 Getting Started Guide</a> and don't stop reading until you have created an ssh key pair, a security group and have a server instance running.</p>
<p>Now you should also have a private key and a certificate in your <em>${EC2_HOME}</em> (preferrably <em>${HOME}/.ec2/</em>) folder of your local computer. These two files should also be uploaded to your instance /mnt folder to make it possible to bundle and upload your images to your S3 "bucket(s)" (buckets are one level deep folders/directories). Make sure you put them in the /mnt folder to prevent them from being bundled with the image and thereby increasing the risk of having your identity revealed.</p>
<p>Bundling, by the way, should be done when you've made changes to your server instance that you don't want to loose. The result of a bundling and uploading is an image with a specific Amazon Image Id (AMI ID) reflecting the state of your server instance at the moment of bundling. You also have to register the image with the manifest file created for you. If you do that you could then safely close down your instance and have it up and running again by issuing the ec2-run-instances command with the AMI ID as parameter. A way to save money.</p>
<p>Bundling and uploading was made easier for me as I used two scripts created by my colleague <a href="/author/ulriksandberg">Ulrik</a>. I put these scripts in the /root folder.</p>
<pre class="bash">bundle-myself.<span style="color: #c20cb9; font-weight: bold;">sh</span>:
&nbsp;
<span style="color: #808080; font-style: italic;">#!/bin/sh</span>
<span style="color: #007800;">prg=</span>`<span style="color: #c20cb9; font-weight: bold;">basename</span> $<span style="color: #000000;">0</span>`
<span style="color: #007800;">dest=</span>/mnt
<span style="color: #007800;">image=</span>blog-image
&nbsp;
<span style="color: #007800;">USAGE=</span><span style="color: #ff0000;">&quot;Usage: $prg &lt;datetime&gt;
&nbsp;
Example:
% $prg 20090415-1000
Bundling into $dest/$image-20090415-1000.manifest.xml&quot;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$#</span> -ne <span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
  <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;$USAGE&quot;</span>
  <span style="color: #7a0874; font-weight: bold;">exit</span> <span style="color: #000000;">1</span>
<span style="color: #000000; font-weight: bold;">fi</span>
<span style="color: #007800;">date=</span>$<span style="color: #000000;">1</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Bundling into $dest/$image-$date.manifest.xml&quot;</span>
ec2-bundle-vol --debug -k /mnt/pk-PRIVATE_KEY.pem -c /mnt/cert-CERTIFICATE.pem -u USER_ACCOUNT_ID -d <span style="color: #007800;">$dest</span> -p <span style="color: #007800;">$image</span>-<span style="color: #007800;">$dat</span>
e -r i386
&nbsp;</pre>
<pre class="bash">upload-myself.<span style="color: #c20cb9; font-weight: bold;">sh</span>:
&nbsp;
<span style="color: #808080; font-style: italic;">#!/bin/sh</span>
<span style="color: #007800;">prg=</span>`<span style="color: #c20cb9; font-weight: bold;">basename</span> $<span style="color: #000000;">0</span>`
<span style="color: #007800;">dest=</span>/mnt
<span style="color: #007800;">image=</span>blog-image
&nbsp;
<span style="color: #007800;">USAGE=</span><span style="color: #ff0000;">&quot;Usage: $prg &lt;date&gt;
&nbsp;
Example:
% $prg 20090415-1000
Uploading bundled AMI parts to https://s3.amazonaws.com:443/[S3_BUCKET] ...
Uploaded blog-image-20090415-1000.part.00 to https://s3.amazonaws.com:443/[S3_BUCKET]/blog-image-20090415-1000.part.00.
...&quot;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$#</span> -ne <span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
  <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;$USAGE&quot;</span>
  <span style="color: #7a0874; font-weight: bold;">exit</span> <span style="color: #000000;">1</span>
<span style="color: #000000; font-weight: bold;">fi</span>
<span style="color: #007800;">date=</span>$<span style="color: #000000;">1</span>
ec2-upload-bundle --retry -m <span style="color: #007800;">$dest</span>/<span style="color: #007800;">$image</span>-<span style="color: #007800;">$date</span>.manifest.xml -b blog-images -a <span style="color: #7a0874; font-weight: bold;">&#91;</span>PUBLIC_KEY<span style="color: #7a0874; font-weight: bold;">&#93;</span> -s <span style="color: #7a0874; font-weight: bold;">&#91;</span>PRIVATE_KEY<span style="color: #7a0874; font-weight: bold;">&#93;</span>
&nbsp;</pre>
<p>Another thing I needed was a static IP address for my instance. To solve this I used Amazons Elastic IP service which doesn't cost anything as long as the generated IP address is in use. So, I generated an Elastic IP address and assigned it to the instance.</p>
<h3>Installing Necessary Software</h3>
<p>The blog require <a href="http://httpd.apache.org/">Apache2</a>, <a href="http://www.php.net/">Php5</a>, <a href="http://www.mysql.com">MySQL</a> and the <a href="http://www.phpgd.com/">Php GD graphics package</a>, to start with. This was easily installed using <a href="http://en.wikipedia.org/wiki/Advanced_Packaging_Tool">Advanced Packaging Tool</a>, apt-get:</p>
<pre class="bash">&nbsp;
<span style="color: #808080; font-style: italic;"># <span style="color: #c20cb9; font-weight: bold;">sudo</span> apt-get update</span>
<span style="color: #808080; font-style: italic;"># <span style="color: #c20cb9; font-weight: bold;">sudo</span> apt-get <span style="color: #c20cb9; font-weight: bold;">install</span> apache2 php5 mysql-server php5-mysql php5-gd</span>
&nbsp;</pre>
<h3>Setting up the Database for EBS</h3>
<p>EBS volumes are, as you might know, more persistent than EC2 instances and will survive if instances go down. Volumes are attached to the instance and could as well be detached and re-attached to new instances. As EBS volumes are not 100% reliable you should also take snapshots of your database data and have it uploaded to an S3 bucket. All this is nicely described in <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1663">Eric Hammonds' EBS and MySQL tutorial</a>, so I urge you to read it if you haven't yet. </p>
<p>The only thing I sidestepped in the tutorial was the MySQL configuration to point out the data and log directories. Instead I used symbolic links:</p>
<pre class="bash">&nbsp;
<span style="color: #808080; font-style: italic;"># <span style="color: #c20cb9; font-weight: bold;">ln</span> -s /vol/lib/mysql/ /var/lib/mysql</span>
<span style="color: #808080; font-style: italic;"># <span style="color: #c20cb9; font-weight: bold;">ln</span> -s /vol/log/mysql/ /var/log/mysql</span>
&nbsp;</pre>
<p>The tutorial also walks you through automatic snapshots which requires the EC2 command line tools. Here is <a href="https://help.ubuntu.com/community/EC2APITools">a nice tutorial on setting these tools up on Ubuntu</a>.</p>
<p>I had to tweak the environment variable settings in ec2-snapshot-xfs-mysql.pl script from</p>
<pre>
BEGIN {
  $ENV{PATH} = '/bin:/usr/bin:/usr/local/bin';
}
</pre>
<p>to</p>
<pre>
BEGIN {
  $ENV{PATH} = '/bin:/usr/bin:/usr/local/bin:/usr/sbin:/root/ec2-api-tools/bin';
  $ENV{EC2_CERT} = '/mnt/cert-CERTIFICATE.pem';
  $ENV{EC2_PRIVATE_KEY} = '/mnt/pk-PRIVATE_KEY.pem';
  $ENV{EC2_HOME} = '/root/ec2-api-tools';
  $ENV{HOME} = '/root';
  $ENV{JAVA_HOME} = '/usr/lib/jvm/java-1.5.0-sun';
}
</pre>
<p>to get the snapshotting to fully work. I also wrapped the ec2-snapshot-xfs-mysql.pl script for a more convenient way to handle the input:</p>
<pre>/root/snapshot-myself.sh

#!/bin/sh
mountpoint=/vol
volume_id=[VOLUME_ID]

su -c "/root/ec2-snapshot-xfs-mysql.pl ${mountpoint} ${volume_id} > /vol/cron.log"
</pre>
<p>To automatize the snapshotting I set up a simple crontab job by issueing:</p>
<pre class="bash">&nbsp;
<span style="color: #808080; font-style: italic;"># crontab -e</span>
&nbsp;</pre>
<p>and then edited it like this</p>
<pre>
05 */6 * * * sh /root/snapshot-myself.sh
</pre>
<p>which makes the job run five minutes past every six hours, every day.</p>
<p>I also had to set the timezone info to apply to our local time. The easiest way I've found out of setting this for a Linux server is like this:</p>
<pre class="bash">&nbsp;
<span style="color: #808080; font-style: italic;"># <span style="color: #c20cb9; font-weight: bold;">ln</span> -sf /usr/share/zoneinfo/Europe/Stockholm /etc/localtime</span>
&nbsp;</pre>
<h3>Configuring MySQL</h3>
<p>To configure MySQL for UTF-8 content make sure the <em>/etc/mysql/my.cnf</em> file contains the following:</p>
<pre>
[client]
default-character-set=utf8

[mysqld]
#
# * Basic Settings
#
init_connect='SET collation_connection = utf8_general_ci'
init_connect='SET NAMES utf8'
character-set-server=utf8
collation-server=utf8_general_ci
default-character-set=utf8
skip-character-set-client-handshake
</pre>
<p>Now, if you haven't yet, go on and start your MySQL server. You need to create your wordpress database. It's as simple as:</p>
<pre class="sql">&nbsp;
<span style="color: #808080; font-style: italic;"># mysql -u [user] -p</span>
&gt; <span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">DATABASE</span> <span style="color: #66cc66;">&#91;</span>database_name<span style="color: #66cc66;">&#93;</span>
&nbsp;</pre>
<p>To create the user with which WordPress will access the database:</p>
<pre class="sql">&nbsp;
&gt; <span style="color: #993333; font-weight: bold;">GRANT</span> <span style="color: #993333; font-weight: bold;">ALL</span> <span style="color: #993333; font-weight: bold;">ON</span> <span style="color: #66cc66;">&#91;</span>database_name<span style="color: #66cc66;">&#93;</span>.* <span style="color: #993333; font-weight: bold;">TO</span> <span style="color: #ff0000;">'[user]'</span>@<span style="color: #ff0000;">'localhost'</span> <span style="color: #993333; font-weight: bold;">IDENTIFIED</span> <span style="color: #993333; font-weight: bold;">BY</span> <span style="color: #ff0000;">'[password]'</span>;
&nbsp;</pre>
<p>And to import your database dump into the newly created database:</p>
<pre class="bash">&nbsp;
<span style="color: #808080; font-style: italic;"># mysql -u <span style="color: #7a0874; font-weight: bold;">&#91;</span>user<span style="color: #7a0874; font-weight: bold;">&#93;</span> -p <span style="color: #7a0874; font-weight: bold;">&#91;</span>database_name<span style="color: #7a0874; font-weight: bold;">&#93;</span> &lt; <span style="color: #7a0874; font-weight: bold;">&#91;</span>output<span style="color: #7a0874; font-weight: bold;">&#93;</span>.sql</span>
&nbsp;</pre>
<p>You shouldn't need to specify any character set or collation when importing thanks to the configuration done in <em>/etc/mysql/my.cnf</em>.</p>
<p>In order for us to stick with our domain name and have no downtime we needed to use the instances IP address until we were finished testing. This means I had to replace two properties in the database to prevent the blog from redirecting to the original host; the '<em>siteurl</em>' and '<em>blogurl</em>' properties residing in the <em>option_value</em> column of the <em>wp_options</em> table. The commands</p>
<pre class="sql">&nbsp;
<span style="color: #808080; font-style: italic;"># mysql -u [user] -p</span>
&gt; <span style="color: #993333; font-weight: bold;">UPDATE</span> wp_options <span style="color: #993333; font-weight: bold;">SET</span> option_value=<span style="color: #ff0000;">'http://[ip_address]/wordpress/'</span> <span style="color: #993333; font-weight: bold;">WHERE</span> option_name=<span style="color: #ff0000;">'siteurl'</span>
&gt; <span style="color: #993333; font-weight: bold;">UPDATE</span> wp_options <span style="color: #993333; font-weight: bold;">SET</span> option_value=<span style="color: #ff0000;">'http://[ip_address]/wordpress/'</span> <span style="color: #993333; font-weight: bold;">WHERE</span> option_name=<span style="color: #ff0000;">'blogurl'</span>
&nbsp;</pre>
<p>fixed this. As soon as the DNS info was propagated throughout the Internet this was reset to <em>"http://blog.jayway.com/wordpress"</em> from within the WordPress admin interface.</p>
<h3>Apache Configuration</h3>
<p>Our WordPress installation makes use of permalinks and redirects to <a href="http://feedburner.google.com/">FeedBurner</a> for RSS statistics. This is based on <em>.htaccess</em> redirects (at least that's how we've solved it) which in turn is dependent on the Apache redirect module. So, in order to make this to work I had to enable that. </p>
<pre class="bash">&nbsp;
<span style="color: #808080; font-style: italic;"># <span style="color: #c20cb9; font-weight: bold;">sudo</span> a2enmod rewrite</span>
&nbsp;</pre>
<p>Easy as that! One more thing on redirections. I had to configure Apache to allow redirection directives specified in the <em>.htaccess</em> file by changing the <em>/etc/apache2/sites-available/default</em> configuration of the <em><VirtualHost *></em> element from</p>
<pre class="xml">&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;Directory</span> /var/www<span style="font-weight: bold; color: black;">/&gt;</span></span>
		Options Indexes FollowSymLinks MultiViews
		AllowOverride None
		Order allow,deny
		allow from all
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/Directory<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>to</p>
<pre class="xml">&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;Directory</span> /var/www<span style="font-weight: bold; color: black;">/&gt;</span></span>
		Options Indexes FollowSymLinks MultiViews
		AllowOverride All <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;----------</span>
		Order allow,deny
		allow from all
	<span style="font-weight: bold; color: black;">&lt;/Directory<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<h3>Securing the WordPress Admin Interface</h3>
<p>Again, I choose to refer to detailed and well written sources. Here are the two articles I followed to create a self-signed certificate and to configure Apache to use it.</p>
<ul>
<li><a href="http://www.tc.umn.edu/~brams006/selfsign.html">Creating a self-signed certificate</a></li>
<li><a href="http://www.tc.umn.edu/~brams006/selfsign_ubuntu.html">Configuring Apache for SSL on Ubuntu</a></li>
</ul>
<p>To enable https access from the "outside world" I also edited the group policy to open up port 443. This could easily be done via the Elasticfox Firefox plugin mentioned earlier.</p>
<h3>Installing and Configuring WordPress</h3>
<p>The default location for Apache httpd server for reading content is <em>/var/www/</em>. If you, as I did, have an existing WordPress installation you can simply copy this to the new server. I ended up having it located at <em>/var/www/wordpress/</em> on the Amazon instance.</p>
<p>Once the database connection properties in the <em>wp-config.php</em> wordpress configuration file was adapted to the new environment I was able to access the WordPress installation via a browser and the Amazon instances' IP address. Sweet!</p>
<p>And as we have our WordPress installation in a separate "<em>/wordpress</em>" folder instead of in the document root of Apache we need to specify, in WordPress admin settings, that the '<em>Site URL</em>' should be "<em>${host}/wordpress</em>" but the<em> 'Blog URL</em>' should simply say "<em>${host}</em>" to prevent the resulting URL from containing "<em>/wordpress/...</em>". This also requires that we move the <em>.htaccess</em> and <em>index.php</em> files from within our "<em>/wordpress</em>" folder and up one level to "<em>/var/www/</em>", in our case. </p>
<p>In the <em>index.php</em> file, make sure to change from</p>
<pre class="php">&nbsp;
<span style="color: #808080; font-style: italic;">/** Loads the WordPress Environment and Template */</span>
<span style="color: #b1b100;">require</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'./wp-blog-header.php'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>to </p>
<pre class="php">&nbsp;
<span style="color: #808080; font-style: italic;">/** Loads the WordPress Environment and Template */</span>
<span style="color: #b1b100;">require</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'./wordpress/wp-blog-header.php'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>If or when specifying the permalinks, WordPress must have write access to the <em>.htaccess</em> file, so 'chmod' that file. </p>
<pre class="bash">&nbsp;
<span style="color: #808080; font-style: italic;"># <span style="color: #c20cb9; font-weight: bold;">chmod</span> <span style="color: #000000;">755</span> .htaccess</span>
&nbsp;</pre>
<p>Otherwise it will complain and simply print out the <em>.htaccess</em> modification it tried to modify with and you are left to change it manually, instead.</p>
<h3>Sending Mail from WordPress</h3>
<p>Mailing is used in WordPress when generating new passwords to users, among others. We also use it to send data backups to the administator of the blog. </p>
<p>Setting up a mail server isn't a trivial task. I gave it a thought but quickly put it aside in favour of the simple WordPress plugin <a href="http://wordpress.org/extend/plugins/wp-mail-smtp/">WP Mail SMTP</a> as I realized I could make use of our existing corporate mail server. It was a breeze to configure the plugin with the necessary mail user credentials.</p>
<p>So, here we are. Sailing these fluffy clouds. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/07/blogging-among-the-clouds/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Testing Among the Clouds, Part 2</title>
		<link>http://blog.jayway.com/2008/10/20/testing-among-the-clouds-part-2/</link>
		<comments>http://blog.jayway.com/2008/10/20/testing-among-the-clouds-part-2/#comments</comments>
		<pubDate>Mon, 20 Oct 2008 14:22:56 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring ldap]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[typica]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=357</guid>
		<description><![CDATA[In a recent post I wrote about the particular problems we've been having with integration testing the Spring LDAP project and the use we've made of Amazon EC2 for solving these problems. In this post I'll present the implementation details. Prerequisites In order to keep this reasonably brief I'll have to refer to the getting [...]]]></description>
			<content:encoded><![CDATA[<p>In a <a target="_blank" href="http://blog.jayway.com/2008/09/11/testing-among-the-clouds/">recent post</a> I wrote about the particular problems we've been having with integration testing the <a target="_blank" href="http://springframework.org/ldap">Spring LDAP</a> project and the use we've made of <a target="_blank" href="http://aws.amazon.com/ec2/">Amazon EC2</a> for solving these problems. In this post I'll present the implementation details.</p>
<h3>Prerequisites</h3>
<p>In order to keep this reasonably brief I'll have to refer to the <a target="_blank" href="http://docs.amazonwebservices.com/AmazonEC2/gsg/2006-06-26/">getting started guide</a> for information on how to get going with Amazon EC2.</p>
<h3>A FactoryBean to Launch EC2 Instances</h3>
<p>What we want to achieve here is to launch an EC2 instance transparently and independently of the actual test code. Ideally, the test code should be oblivious of the target server and we want to externalize those details to external configuration. We will use Spring's excellent JUnit test support to automatically wire the integration test setup and make sure that the target server is up and running before the actual test code is running.</p>
<p>A powerful way to transparently perform complex initialization logic when using Spring is the <a target="_blank" href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-extension-factorybean"><code>FactoryBean</code></a> concept. We will create a <code>FactoryBean</code> implementation to launch the EC2 image and set up our target resource:</p>
<pre class="java">AbstractEc2InstanceLaunchingFactoryBean.<span style="color: #006600;">java</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> AbstractEc2InstanceLaunchingFactoryBean <span style="color: #000000; font-weight: bold;">extends</span> AbstractFactoryBean <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">int</span> INSTANCE_START_SLEEP_TIME = <span style="color: #cc66cc;">1000</span>;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">long</span> DEFAULT_PREPARATION_SLEEP_TIME = <span style="color: #cc66cc;">30000</span>;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> Log log = LogFactory.<span style="color: #006600;">getLog</span><span style="color: #66cc66;">&#40;</span>AbstractEc2InstanceLaunchingFactoryBean.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> imageName;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> awsKey;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> awsSecretKey;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> keypairName;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> groupName;
  <span style="color: #000000; font-weight: bold;">private</span> Instance instance;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">long</span> preparationSleepTime = DEFAULT_PREPARATION_SLEEP_TIME;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setImageName<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> imageName<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">imageName</span> = imageName;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setAwsKey<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> awsKey<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">awsKey</span> = awsKey;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setAwsSecretKey<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> awsSecretKey<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">awsSecretKey</span> = awsSecretKey;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setKeypairName<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> keypairName<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">keypairName</span> = keypairName;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setGroupName<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> groupName<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">groupName</span> = groupName;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setPreparationSleepTime<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">long</span> preparationSleepTime<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">preparationSleepTime</span> = preparationSleepTime;
  <span style="color: #66cc66;">&#125;</span>
  @Override
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">final</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> createInstance<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>imageName, <span style="color: #ff0000;">&quot;ImageName must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>awsKey, <span style="color: #ff0000;">&quot;AwsKey must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>awsSecretKey, <span style="color: #ff0000;">&quot;AwsSecretKey must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>keypairName, <span style="color: #ff0000;">&quot;KeyName must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasLength</span><span style="color: #66cc66;">&#40;</span>groupName, <span style="color: #ff0000;">&quot;GroupName must be set&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
      log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Launching EC2 instance for image: &quot;</span> + imageName<span style="color: #66cc66;">&#41;</span>;
&nbsp;
      Jec2 jec2 = <span style="color: #000000; font-weight: bold;">new</span> Jec2<span style="color: #66cc66;">&#40;</span>awsKey, awsSecretKey<span style="color: #66cc66;">&#41;</span>;
      LaunchConfiguration launchConfiguration = <span style="color: #000000; font-weight: bold;">new</span> LaunchConfiguration<span style="color: #66cc66;">&#40;</span>imageName<span style="color: #66cc66;">&#41;</span>;
      launchConfiguration.<span style="color: #006600;">setKeyName</span><span style="color: #66cc66;">&#40;</span>keypairName<span style="color: #66cc66;">&#41;</span>;
      launchConfiguration.<span style="color: #006600;">setSecurityGroup</span><span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">singletonList</span><span style="color: #66cc66;">&#40;</span>groupName<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
      ReservationDescription reservationDescription = jec2.<span style="color: #006600;">runInstances</span><span style="color: #66cc66;">&#40;</span>launchConfiguration<span style="color: #66cc66;">&#41;</span>;
      instance = reservationDescription.<span style="color: #006600;">getInstances</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #b1b100;">while</span> <span style="color: #66cc66;">&#40;</span>!instance.<span style="color: #006600;">isRunning</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> &amp;&amp; !instance.<span style="color: #006600;">isTerminated</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
          log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Instance still starting up; sleeping &quot;</span> + INSTANCE_START_SLEEP_TIME + <span style="color: #ff0000;">&quot;ms&quot;</span><span style="color: #66cc66;">&#41;</span>;
          <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThread+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Thread</span></a>.<span style="color: #006600;">sleep</span><span style="color: #66cc66;">&#40;</span>INSTANCE_START_SLEEP_TIME<span style="color: #66cc66;">&#41;</span>;
          reservationDescription = jec2.<span style="color: #006600;">describeInstances</span><span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">singletonList</span><span style="color: #66cc66;">&#40;</span>instance.<span style="color: #006600;">getInstanceId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
          instance = reservationDescription.<span style="color: #006600;">getInstances</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
&nbsp;
      <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>instance.<span style="color: #006600;">isRunning</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
          log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;EC2 instance is now running&quot;</span><span style="color: #66cc66;">&#41;</span>;
          <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>preparationSleepTime &gt; <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
              log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Sleeping &quot;</span> + preparationSleepTime + <span style="color: #ff0000;">&quot;ms allowing instance services to start up properly.&quot;</span><span style="color: #66cc66;">&#41;</span>;
              <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThread+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Thread</span></a>.<span style="color: #006600;">sleep</span><span style="color: #66cc66;">&#40;</span>preparationSleepTime<span style="color: #66cc66;">&#41;</span>;
              log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Instance prepared - proceeding&quot;</span><span style="color: #66cc66;">&#41;</span>;
          <span style="color: #66cc66;">&#125;</span>
          <span style="color: #000000; font-weight: bold;">return</span> doCreateInstance<span style="color: #66cc66;">&#40;</span>instance.<span style="color: #006600;">getDnsName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#123;</span>
          <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AIllegalStateException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">IllegalStateException</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Failed to start a new instance&quot;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #66cc66;">&#125;</span>
   <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">abstract</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> doCreateInstance<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> ip<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a>;
&nbsp;
  @Override
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> destroyInstance<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> ignored<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">instance</span> != <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
      log.<span style="color: #006600;">info</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Shutting down instance&quot;</span><span style="color: #66cc66;">&#41;</span>;
      Jec2 jec2 = <span style="color: #000000; font-weight: bold;">new</span> Jec2<span style="color: #66cc66;">&#40;</span>awsKey, awsSecretKey<span style="color: #66cc66;">&#41;</span>;
      jec2.<span style="color: #006600;">terminateInstances</span><span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">singletonList</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">instance</span>.<span style="color: #006600;">getInstanceId</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>This superclass makes use of the <a target="_blank" href="http://code.google.com/p/typica/">typica</a> library (<a target="_blank" href="http://mvnrepository.com/artifact/com.google.code.typica/typica">also available in maven</a>) to launch the EC2 instance and delegates to <code>doCreateInstance</code> for creating the target resource that we will use in our test case. In our setup we want to create a <code>ContextSource</code>, which is the Spring LDAP equivalent of a <code>DataSource</code>:</p>
<pre class="java">ContextSourceEc2InstanceLaunchingFactoryBean.<span style="color: #006600;">java</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ContextSourceEc2InstanceLaunchingFactoryBean <span style="color: #000000; font-weight: bold;">extends</span> AbstractEc2InstanceLaunchingFactoryBean <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> base;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> userDn;
  <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> password;
  @Override
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000000; font-weight: bold;">Class</span> getObjectType<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> ContextSource.<span style="color: #000000; font-weight: bold;">class</span>;
  <span style="color: #66cc66;">&#125;</span>
  @Override
  <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">final</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> doCreateInstance<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">final</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> dnsName<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">Assert</span>.<span style="color: #006600;">hasText</span><span style="color: #66cc66;">&#40;</span>userDn<span style="color: #66cc66;">&#41;</span>;
    LdapContextSource instance = <span style="color: #000000; font-weight: bold;">new</span> LdapContextSource<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    instance.<span style="color: #006600;">setUrl</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;ldap://&quot;</span> + dnsName<span style="color: #66cc66;">&#41;</span>;
    instance.<span style="color: #006600;">setUserDn</span><span style="color: #66cc66;">&#40;</span>userDn<span style="color: #66cc66;">&#41;</span>;
    instance.<span style="color: #006600;">setPassword</span><span style="color: #66cc66;">&#40;</span>password<span style="color: #66cc66;">&#41;</span>;
    instance.<span style="color: #006600;">setBase</span><span style="color: #66cc66;">&#40;</span>base<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    instance.<span style="color: #006600;">afterPropertiesSet</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000000; font-weight: bold;">return</span> instance;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setBase<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> base<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">base</span> = base;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setUserDn<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> userDn<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">userDn</span> = userDn;
  <span style="color: #66cc66;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> setPassword<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> password<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">password</span> = password;
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Note that the <code>AbstractEc2InstanceLaunchingFactoryBean</code> will wait for the instance to start up properly. It will also wait an additional period of time once the instance is up and running to allow for all relevant services to start up properly. Finally it will  automatically close down the launched instance once it is properly shut down (which it will be when executing using the Spring automated test support).</p>
<h3>Test Case Configuration</h3>
<p>We now have the infrastructure to have the EC2 instance launched transparently from a Spring Application Context. All we need to do is configure it:</p>
<pre class="xml">testContext.xml
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;location&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;ldap.properties&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;systemPropertiesModeName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;SYSTEM_PROPERTIES_MODE_OVERRIDE&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.ContextSourceEc2InstanceLaunchingFactoryBean&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;awsKey&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.key}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;awsSecretKey&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.secret.key}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;imageName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.ami}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;groupName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.security.group}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;keypairName&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${aws.keypair}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;base&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;dc=jayway,dc=se&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;userDn&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${userDn}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${password}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;ldapTemplate&quot;</span>
  <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.core.LdapTemplate&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>We are referring to <code>ldap.properties</code> for the actual settings:</p>
<pre>
userDn=cn=admin,dc=jayway,dc=se
password=secret
base=dc=jayway,dc=se
aws.ami=ami-56ec083f
aws.keypair=spring-ldap-keypair
aws.security.group=spring-ldap
</pre>
<p>The referenced AMI is a public image specifically set up for our test cases. It has OpenLDAP installed and has been pre-populated with the test data that our test cases expect.</p>
<p>Note that we are not specifying any property value for <code>aws.key</code> and <code>aws.secret.key</code>, as this is the Amazon account access information. That will be the account settings of the individual developer and should be supplied at runtime using system properties (e.g. <code>mvn -Daws.key=xxxxxxx -Daws.secret.key=xxxxxx test</code>).</p>
<h3>Performing the Test</h3>
<p>Now all we need to do is use Spring's automated test support to start our test:</p>
<pre class="java">SomeLdapITest.<span style="color: #006600;">java</span>
@ContextConfiguration<span style="color: #66cc66;">&#40;</span>locations = <span style="color: #66cc66;">&#123;</span> <span style="color: #ff0000;">&quot;testContext.xml&quot;</span> <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SomeLdapITest <span style="color: #000000; font-weight: bold;">extends</span> AbstractJUnit4SpringContextTests <span style="color: #66cc66;">&#123;</span>
  @Autowired
  <span style="color: #000000; font-weight: bold;">private</span> LdapTemplate tested;
&nbsp;
  @Test
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testSomething<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">// Use the automatically injected LdapTemplate instance to perform a test.</span>
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<h3>Set to Go</h3>
<p>With the above you should be all set to go to start using this powerful approach to integration testing. The actual code is available with the 1.3.0.RC1 release of Spring LDAP; links to downloads and documentation available <a href="http://www.springframework.org/ldap">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/10/20/testing-among-the-clouds-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing Among the Clouds</title>
		<link>http://blog.jayway.com/2008/09/11/testing-among-the-clouds/</link>
		<comments>http://blog.jayway.com/2008/09/11/testing-among-the-clouds/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 08:53:26 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[continuous integration]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring ldap]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[typica]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=77</guid>
		<description><![CDATA[One of the major challenges we've been facing in the Spring LDAP project is to make certain that the library works together with different LDAP servers. Different servers behave differently in certain situations; some functionality might only be supported on select servers, etc. In the ideal situation we would run our automated test suite against [...]]]></description>
			<content:encoded><![CDATA[<p>One of the major challenges we've been facing in the <a title="Spring LDAP" href="http://springframework.org/ldap" target="_blank">Spring LDAP</a> project is to make certain that the library works together with different LDAP servers. Different servers behave differently in certain situations; some functionality might only be supported on select servers, etc. In the ideal situation we would run our automated test suite against a multitude of target platforms for each change made to the code. Each developer would be able to run the test suite locally against each of these platforms, and the <a href="http://build.springframework.org:8085/browse/LDAP" target="_blank">continuous integration server</a> would automatically run them on each commit. This is the key element to automated testing: the automated tests must be relevant, and they must be quickly and easily run at any time, by any member of the team (or - in this case, being an open source project - by anyone that might have checked the source out from subversion). These conditions are imperative for any type of automated tests - if the conditions are not fulfilled the tests will not be run at all and consequently they will die.</p>
<p>In the perfect world, each developer would at all times have access to a server park with all of these different server versions installed. Reality is however almost always a different question: Being an Open Source project with limited funding and developers located throughout the world this has been impossible for us, up until now. You're probably already guessing: The answer is in the Clouds.</p>
<p>Having used <a href="http://www.amazon.com/gp/browse.html?node=201590011" target="_blank">Amazon EC2</a> in a couple of customer projects, we suddenly realized this is the answer to our problems. For those of you not completely familiar with the concept, the general idea of Amazon EC2 is that you configure one or several <strong>machine images</strong>, installing whatever software and data you might need on each image. You will then start an <strong>instance</strong> from one of these pre-configured images, which will in effect start up a virtual computer somewhere in the amazon cloud, a computer that will then be yours to play around with in any way you might like until you're finished with it and just shut the instance down. All of this is available at a very reasonable pricing - you pay only (a very modest amount) for the time that your instances have been running.</p>
<p>The concept suits us perfectly: we want a number of isolated environments, each with a known start state where we can run our test suite against a particular server setup. So that's what we've started to do: we have now created an EC2 image with an Open LDAP installation, pre-loaded with the data that our test cases expect. We then devised support classes to have the JUnit test cases automatically start an appropriate instance (using the excellent <a href="http://code.google.com/p/typica/" target="_blank">typica</a> library), run the tests against the started virtual machines, and shut down the instance after the tests are finished (regardless of the outcome - we don't want any stray instances running around costing us money <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ). We still have some more work to do with setting up more images for other server setups, but we're hoping to get that work going as we move on...</p>
<p>I'm planning to dig a little bit deeper into the details of the setup and the code involved in a later post. In the meantime: if you're really interested, feel free to check the code out from the <a href="https://springframework.svn.sourceforge.net/svnroot/springframework/spring-ldap/trunk/mvn-build" target="_blank">svn repo</a> and have a look at what we've done so far. The relevant code for this is in the test/integration-tests-openldap directory.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/09/11/testing-among-the-clouds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Amazon S3 for backup</title>
		<link>http://blog.jayway.com/2007/09/02/using-amazon-s3-for-backup/</link>
		<comments>http://blog.jayway.com/2007/09/02/using-amazon-s3-for-backup/#comments</comments>
		<pubDate>Sun, 02 Sep 2007 22:50:20 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[s3]]></category>
		<category><![CDATA[storage]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=162</guid>
		<description><![CDATA[Amazon Simple Storage Service (S3) is cheap on-line storage with a Web Service interface. You just log in with your Amazon id, sign up for S3, designate a credit card, and that's it. You now have access to pretty much unlimited storage space, managed by Amazon. The price is $0.15 per GB-Month of storage used [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://aws.amazon.com/s3">Amazon Simple Storage Service (S3)</a> is cheap on-line storage with a Web Service interface. You just log in with your Amazon id, sign up for S3, designate a credit card, and that's it. You now have access to pretty much unlimited storage space, managed by Amazon. The price is $0.15 per GB-Month of storage used (plus transfer costs). It was too tempting; I simply had to test it.</p>
<p>I used the <a href="http://jungledisk.com/">Jungle Disk</a> software to provide the mapping from the S3 web service interface to a network drive. You give Jungle Disk your S3 account information, and it provides a network disk which you can use as the backup device. I first tried my existing backup software (<a href="http://www.qdea.com/pages/pages-sprox/sprox1.html">Synchronize! Pro X</a>) and it happily began creating directories and copying files. I then tried the backup feature built into Jungle Disk, and it works fine too. It's not fast compared to a local FireWire disk. It's limited to your upload bandwidth, which often is substantially smaller than the download bandwidth.</p>
<p>Anyway, it has been tugging along today storing 5 GB of by digital photos. It feels pretty good to know that my photos are now stored encrypted and with 99.99% availability somewhere far far away, costing me only 75 cents per month after the initial $2 for the transfer.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/09/02/using-amazon-s3-for-backup/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

