<?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>Tales from behind the browser</title>
	<atom:link href="http://www.servicestack.net/mythz_blog/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.servicestack.net/mythz_blog</link>
	<description>adventures of a coder</description>
	<lastBuildDate>Thu, 24 Nov 2011 02:02:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Async, Cached Twitter API Proxy in F#</title>
		<link>http://www.servicestack.net/mythz_blog/?p=811</link>
		<comments>http://www.servicestack.net/mythz_blog/?p=811#comments</comments>
		<pubDate>Mon, 03 Oct 2011 10:24:04 +0000</pubDate>
		<dc:creator>mythz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.servicestack.net/mythz_blog/?p=811</guid>
		<description><![CDATA[Following on from showing how easy it was to create web services in F# with Service Stack, it&#8217;s now a good time to step it up a bit and do something useful to showcase some F#&#8217;s async goodness! The final solution is available as a stand-alone HttpListener or an ASP.NET host which I just happen [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D811"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D811&amp;source=demisbellot&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Following on from showing how easy it was to create web services in F# with Service Stack, it&#8217;s now a good time to step it up a bit and do something useful to showcase some F#&#8217;s async goodness!</p>
<blockquote><p>The final solution is available as a stand-alone <a href="https://gist.github.com/1242208">HttpListener</a> or an <a href="https://gist.github.com/1258515">ASP.NET host</a> which I just happen to have deployed earlier on a Linux server at <a href="http://www.servicestack.net/ftweetstack/metadata">http://www.servicestack.net/ftweetstack/</a>. Here&#8217;s a couple example urls to see the stats of all my friends and followers:</p>
<p><a href="http://www.servicestack.net/ftweetstack/followers/demisbellot">http://www.servicestack.net/ftweetstack/followers/demisbellot</a><br />
<a href="http://www.servicestack.net/ftweetstack/friends/demisbellot">http://www.servicestack.net/ftweetstack/friends/demisbellot</a></p></blockquote>
<h3>Edit Screenshots added:</h3>
<p>As I&#8217;m now getting rate limited by twitter, the live services have stopped working so I&#8217;ve included screenshots of the web service responses, reminiscent of happier times <img src='http://www.servicestack.net/mythz_blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>[format=html]</strong></p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/10/fstack-html.png"><img class="alignnone size-full wp-image-826" title="fstack-html" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/10/fstack-html.png" alt="" width="544" height="361" /></a></p>
<p><strong>[format=csv]</strong></p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/10/fstack-csv.png"><img class="alignnone size-full wp-image-827" title="fstack-csv" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/10/fstack-csv.png" alt="" width="552" height="397" /></a></p>
<p><strong>[format=json]</strong></p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/10/fstack-json.png"><img class="alignnone size-full wp-image-828" title="fstack-json" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/10/fstack-json.png" alt="" width="542" height="482" /></a></p>
<p><span id="more-811"></span></p>
<h2>Back to the code editor&#8230;</h2>
<p>The best way to showoff some Async code is to do some IO, and the most interesting IO people do these days is against 3rd Party APIs, and the API nearly everyone is familiar with is Twitter&#8217;s, so let&#8217;s write some code that calls Twitter&#8217;s API!</p>
<p><span style="font-size: 15px; font-weight: bold;">Stuck with the old</span></p>
<p>We&#8217;ll first start with something simple &#8211; a basic HTTP request. Unfortunately F# doesn&#8217;t come with hot new networking libs to make life easy for us. Nope we&#8217;re stuck with the same Async APIs .NET was born with &#8211; and .NETs Asynchronous Programming Model (APM) of using the BeginXXX/EndXXX pattern could very well be the worst async model in use today. But what F# doesn&#8217;t fix with new cake, it fixes with sweeteners providing us some nice sugar coating we can use over the top to make these APIs more palatable.</p>
<p>Async.FromBeginEnd(,) takes the BeginXXX,EndXXX async method pair and returns an Asynchronous computation that wraps the Async task for use in F#&#8217;s built-in Asynchronous workflows.</p>
<h3>Doing something new with it</h3>
<p>Taking advantage of F#&#8217;s ability to extend existing types, we can add this helper method to the familiar WebRequest type with:</p>
<pre class="brush: csharp; title: ;">
	type System.Net.WebRequest with
	    member x.GetResponseAsync() =
	    	Async.FromBeginEnd(x.BeginGetResponse, x.EndGetResponse)
</pre>
<p>With this in-place we can build a high level asyncHttp API that downloads the text contents of a http resource asynchronously.</p>
<pre class="brush: csharp; title: ;">
	let asyncHttp (url:string) =
	    async {
	        printfn &quot;downloading: %s&quot; url
	        let req = System.Net.WebRequest.Create(url)
	        let! rsp = req.GetResponseAsync()
	        printfn &quot;processing response...&quot;
	        use stream = rsp.GetResponseStream()
	        use reader = new System.IO.StreamReader(stream)
	        return reader.ReadToEnd() }
</pre>
<h3>What is this async { &#8230; } ?</h3>
<p>What&#8217;s different with this function is it doesn&#8217;t actually return a string as the implementation might suggest, it actually returns an Async which is basically says <em>&#8220;I wrap an asynchronous computation that returns a string&#8221;</em>. Async workflows in F# are surrounded by an <strong>async { &#8230; }</strong> block, inside this block you will occaisionally see a <strong>let!</strong> statement. The <strong>let!</strong> statement above which happens to be against the async helper we created earlier is used when calling Async APIs which performs the async task without blocking the current execution, when the task completes it resumes, and executes the remaining logic in the async block.</p>
<p>In code terms this looks like:</p>
<pre class="brush: csharp; title: ;">
	let fetchMe = asyncHttp &quot;http://api.twitter.com/1/users/lookup.json?screen_name=demisbellot&quot;
	printfn &quot;doing other stuff... la, di, da...&quot;
	let json = fetchMe |&gt; Async.RunSynchronously
</pre>
<p>Which when run in <strong>fsi</strong> returns:</p>
<pre class="brush: csharp; title: ;">
	doing other stuff... la, di, da...
	downloading: http://api.twitter.com/1/users/lookup.json?screen_name=demisbellot
	processing response...
	val fetchMe : Async&lt;string&gt;
	val json : string =
	  &quot;[{&quot;id_str&quot;:&quot;17575623&quot;,&quot;profile_link_color&quot;:&quot;43594A&quot;,&quot;follower&quot;+[1330 chars]
</pre>
<p>As illustrated invoking the <strong>asyncHttp</strong> method doesn&#8217;t execute it immediately, instead it returns an async workflow that can be called upon later, in this way it works like the deferred exeuction of yield iterators in C# where the iterator itself is only executed when it&#8217;s enumerated, i.e. someone calls .ToList() or in this case <strong>Async.RunSynchronously</strong> which runs the async task and awaits the results.</p>
<p>Great, we now know how to make an async HTTP request so let&#8217;s create a service out of it. To help with error handling I&#8217;ve added a wrapper over the raw asyncHttp call to detect and log errors of any fail whales caught and return an empty JSON array muting Exceptions. I&#8217;ve also added a <strong>join</strong> method to join any lists we need to and a short <strong>jsonTo</strong> alias to make using <a href="http://www.servicestack.net/mythz_blog/?p=344">ServiceStack&#8217;s fast Json Serializer</a> easier on the eyes <img src='http://www.servicestack.net/mythz_blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre class="brush: csharp; title: ;">
	let asyncJson url =
	    async {
	        try
	            return! asyncHttp url
	        with
	            | ex -&gt; printfn &quot;Error downloading: %s =&gt; %s&quot; url ex.Message; return &quot;[]&quot; }

	let joinWith delim seq =
	    let sb = new System.Text.StringBuilder()
	    seq |&gt; Seq.iter (fun x -&gt; sb.Append((if sb.Length &gt; 0 then delim else &quot;&quot;) + x.ToString()) |&gt; ignore)
	    sb.ToString()

	let join seq = joinWith &quot;,&quot; seq

	let jsonTo&lt;'a&gt; json = ServiceStack.Text.JsonSerializer.DeserializeFromString&lt;'a&gt;(json)
</pre>
<p>We also need a model to dehydrate twitter&#8217;s response. I&#8217;m only interested in Users statistics for this example which I can easily map into an F# Record Type which makes definiing POCO&#8217;s effortless.</p>
<p>And as I&#8217;m always striving for DRY, readable code, I&#8217;ll wrap the async calls into more readable methods. Immediately you can start to see the benefits of F# async workflows as we&#8217;re able to compose higher level async APIs together without infecting the calling code, a common problem with many Async APIs.</p>
<pre class="brush: csharp; title: ;">
    type UserStat = {
        mutable id: uint64;
        mutable screen_name: string;
        mutable name: string;
        mutable friends_count: int;
        mutable followers_count: int;
        mutable listed_count: int;
        mutable statuses_count: int }

    let asyncUsers screenNames = asyncJson(&quot;http://api.twitter.com/1/users/lookup.json?screen_name=&quot; + (screenNames |&gt; join))

    let usersByNames screenNames = asyncUsers screenNames |&gt; Async.RunSynchronously |&gt; jsonTo&lt;UserStat[]&gt; |&gt; Seq.toList
</pre>
<p>With the above helpers in place all we need to do is to create the service, which is easy as creating the <strong>UserStats</strong> Request DTO so we know what to expect then and the actual implementation which just passes the list of names into our above <strong>usersByNames</strong> function, returning the results as-is:</p>
<pre class="brush: csharp; title: ;">
    type UserStats = { mutable ScreenNames: string; }
    type UserStatsService() =
        interface IService&lt;UserStats&gt; with
            member this.Execute (req:UserStats) = req.ScreenNames.Split(',') |&gt; usersByNames :&gt; Object
</pre>
<p>After registering the appropriate Route in our AppHost we can now call our service passing in multiple twitter user names:</p>
<p><strong>http://localhost:8080/users/demisbellot,servicestack,dsyme</strong></p>
<h2>More Async</h2>
<p>Although we&#8217;ve created a web service that calls Twitter&#8217;s REST API asynchronously, we&#8217;re synchronously waiting for it straight after so it&#8217;s not doing us much good. The benefits of Async begin to show itself when you&#8217;re performing multiple IO calls, which is what will be needed in order to gather the stats of your friends or followers using twitter&#8217;s APIs.</p>
<p>Twitter only provides an API to return your followers or friends as a list of user ids, to get the user info, another API call is needed to <strong>lookup.json</strong> which at most only accepts 100 user ids at a time. Knowing this, the quickest way to fetch the user info for your friends of followers is to send the requests for userinfo asynchronously, in parallel.</p>
<p>The actual API calls given they&#8217;re just JSON urls are the easiest to do, just 1 line each. I&#8217;ll further wrap them in higher level <strong>followerIds</strong> and <strong>friendIds</strong> functions which deserializes the json ids in the response into a list of longs:</p>
<pre class="brush: csharp; title: ;">
    let asyncFollowerIds screenName = asyncJson(&quot;http://api.twitter.com/1/followers/ids.json?screen_name=&quot; + screenName)
    let asyncFriendIds screenName = asyncJson(&quot;http://api.twitter.com/1/friends/ids.json?screen_name=&quot; + screenName)
    let asyncUserIds userIds = asyncJson(&quot;http://api.twitter.com/1/users/lookup.json?user_id=&quot; + (userIds |&gt; join))

    let followerIds screenName = asyncFollowerIds screenName |&gt; Async.RunSynchronously |&gt; jsonTo&lt;uint64[]&gt; |&gt; Array.toList
    let friendIds screenName = asyncFriendIds screenName   |&gt; Async.RunSynchronously |&gt; jsonTo&lt;uint64[]&gt; |&gt; Array.toList
</pre>
<p>The first piece of functionality required is batching an unbounded list of ids into manageable 100-size chunks. My first attempt at this was short and Linq-y:</p>
<pre class="brush: csharp; title: ;">
	let batchesOf size (sequence: _ seq) : _ list seq =
	    seq {
	        let s = ref sequence
	        while not (!s |&gt; Seq.isEmpty)  do
	            yield !s |&gt; Seq.truncate size |&gt; List.ofSeq
	            s := System.Linq.Enumerable.Skip(!s, size)
	    }
</pre>
<p><a href="http://stackoverflow.com/questions/7509863/most-idiomatic-way-to-write-batchesof-size-seq-in-f">But was later discovered to be fairly slow</a>, given the repetitive call to Skip. Since I&#8217;m particularly sensitive to perf in my library functions, I opted to go with a more verbose version, but one that only enumerates the sequence once:</p>
<pre class="brush: csharp; title: ;">
	let batchesOf size (s: seq&lt;'v&gt;) =
	    seq {
	        let en = s.GetEnumerator()
	        let more = ref true
	        while !more do
	        let group = [
	            let i = ref 0
	            while !i &lt; size &amp;&amp; en.MoveNext () do
	                yield en.Current
	                i := !i + 1 ]
	        if List.isEmpty group then
	            more := false
	        else
	            yield group }
</pre>
<p>As third party IO calls are amongst the most expensive things you can do, having a cache is a good idea to reduce unnecessary IO calls. We&#8217;ll need a threadsafe collection here since we&#8217;ll be reading and writting to it at runtime, and .NET 4&#8242;s Generic <strong>ConcurrentDictionary</strong> handles the task nicely and made easily available to F#:</p>
<pre class="brush: csharp; title: ;">
    let userCache = System.Collections.Concurrent.ConcurrentDictionary&lt;uint64,UserStat&gt;()
</pre>
<p>With the rest of what we need in place we can focus on the most complicated piece to asynchronously download in parallel the the user info for an unlimited list of user ids in <strong>batches of 100</strong>. In addition, the function should make use of the <strong>userCache</strong> only fetching the missing entries before merging the new and cached UserStat&#8217;s. Surprisingly this entire behaviour can be achieved in just a few lines of F# code:</p>
<pre class="brush: csharp; title: ;">
    let usersByIds userIds =
		let cachedIds, missingIds = userIds |&gt; List.partition userCache.ContainsKey
		missingIds
		|&gt; batchesOf 100
		|&gt; Seq.map asyncUserIds
		|&gt; Async.Parallel |&gt; Async.RunSynchronously
		|&gt; Seq.map jsonTo&lt;UserStat[]&gt;
		|&gt; Seq.collect (fun xs -&gt; xs |&gt; Seq.map
			(fun x -&gt; userCache.TryAdd(x.id, x) |&gt; ignore; x)) |&gt; Seq.toList
		|&gt; List.append (cachedIds |&gt; List.map (fun x -&gt; userCache.TryGetValue x |&gt; snd))
</pre>
<p>As there&#8217;s a bit going on here I&#8217;ll explain what&#8217;s happening for each line:</p>
<p><strong>#2:</strong> Split the entire list of user ids into the ids we have cached and the ones that are missing.<br />
<strong> #3:</strong> Group the ids in batches of 100<br />
<strong> #4:</strong> Create separate async API calls for each of those batches<br />
<strong> #5:</strong> Call each of the API calls in Parallel and wait till they&#8217;re all completed<br />
<strong> #6:</strong> Deserialize the response into lists of UserStat[] types<br />
<strong> #7:</strong> Merge the UserStat&#8217;s together adding each entry into the cache<br />
<strong> #8:</strong> Append the resulting entries with the previously cached UserStats</p>
<p>Neat! the hard part&#8217;s over now it&#8217;s just a matter of exposing them in web services and then we&#8217;re done:</p>
<pre class="brush: csharp; title: ;">
    let followers screenName = followerIds screenName |&gt; usersByIds
    let friends screenName = friendIds screenName |&gt; Seq.toList |&gt; usersByIds

    type FollowerStats = { mutable ScreenName: string; }
    type FollowerStatsService() =
        interface IService&lt;FollowerStats&gt; with
            member this.Execute (req:FollowerStats) = followers req.ScreenName :&gt; Object

    type FriendsStats = { mutable ScreenName: string; }
    type FriendsStatsService() =
        interface IService&lt;FriendsStats&gt; with
            member this.Execute (req:FriendsStats) = friends req.ScreenName :&gt; Object
</pre>
<p>After adding the routes for each service we can now see the stats for all my friends and followers at these two friendly urls:</p>
<p><strong>http://localhost:8080/followers/demisbellot</strong><br />
<strong> http://localhost:8080/friends/demisbellot</strong></p>
<p>We can test the above urls live using the deployed web service on <a href="http://servicestack.net">servicestack.net</a>:</p>
<p><a href="http://www.servicestack.net/ftweetstack/followers/demisbellot">http://www.servicestack.net/ftweetstack/followers/demisbellot</a><br />
<a href="http://www.servicestack.net/ftweetstack/friends/demisbellot">http://www.servicestack.net/ftweetstack/friends/demisbellot</a></p>
<p>Because we&#8217;re using <a href="http://www.servicestack.net">ServiceStack</a>, viewing these urls in a web browser (or any REST client with Accept: text/html) returns the data in a human readable <a href="http://www.servicestack.net/docs/framework/json-report-format">HTML Report Format</a>. Naturally, the usual <strong>XML</strong> and <strong>JSON</strong> formats are available and likewise the <strong>CSV format</strong> which will load the response data into your preferred spreadsheet program or database. All the different formats are available by appending the format to the url e.g: <strong>?format=csv</strong> or by specifying it in the Accept HTTP Header.</p>
<p><a href="http://www.servicestack.net/ftweetstack/followers/demisbellot?format=csv">http://www.servicestack.net/ftweetstack/followers/demisbellot?format=csv</a><br />
<a href="http://www.servicestack.net/ftweetstack/friends/demisbellot?format=json">http://www.servicestack.net/ftweetstack/friends/demisbellot?format=json</a></p>
<p>Should you feel like angering the REST gods, you can commit heresy by accessing twitters REST-ful API over the SOAP endpoints and WSDLS at <strong>/soap11</strong> and <strong>/soap12</strong> urls <img src='http://www.servicestack.net/mythz_blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>Download in ASP.NET or HttpListener modes</h2>
<p>The complete source code for the above is available in different hosting flavours which can be compiled and run on all <strong>Windows/OSX/Linux</strong> platforms:</p>
<ul>
<li><a href="https://gist.github.com/1258515">ASP.NET Host [gist]</a></li>
<li><a href="https://gist.github.com/1242208">Stand alone HttpListener [gist]</a></li>
</ul>
<p><a href="http://www.servicestack.net/mythz_blog/?p=785">Check the previous post</a> for more information on creating ServiceStack Web Services with F#.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.servicestack.net/mythz_blog/?feed=rss2&amp;p=811</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>F# Web Services on any platform in and out of a web server!</title>
		<link>http://www.servicestack.net/mythz_blog/?p=785</link>
		<comments>http://www.servicestack.net/mythz_blog/?p=785#comments</comments>
		<pubDate>Wed, 28 Sep 2011 11:32:03 +0000</pubDate>
		<dc:creator>mythz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.servicestack.net/mythz_blog/?p=785</guid>
		<description><![CDATA[Following on from my previous post where I took a first look at F# through my C# tinted eyes, I looked into some of the advantages of what this versatile language brings to a C# devs table. One of the major benefits I mentioned in passing but failed to explain in detail was it&#8217;s exceptionally [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D785"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D785&amp;source=demisbellot&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Following on from my previous post where I took a first look at <a href="http://www.servicestack.net/mythz_blog/?p=765">F# through my C# tinted eyes</a>, I looked into some of the advantages of what this versatile language brings to a C# devs table. One of the major benefits I mentioned in passing but failed to explain in detail was it&#8217;s exceptionally good async story, which in many respects provides arguably the best async programming development experience to date on any platform.</p>
<h3>F# and .NET Web Services</h3>
<p>If F# only had to interface with other code as its inputs and outputs, the async world of F# is pristine and beautiful. Such is rarely the case so we&#8217;re stuck with having to interface with existing frameworks to provide these additional user facing services. Unfortunately the Web Services story for .NET isn&#8217;t pretty, where if for whatever reason you&#8217;re forced to use Microsoft-only technologies, you&#8217;re left with either having to deal with the WCF problem or extend MVC&#8217;s framework and roll your own REST-ful framework-in-a-framework yourself &#8211; which although less capable, I&#8217;ve witnessed to be a viable alternative providing a better iterative experience than WCF in the wild. Another web framework worth considering along similar lines, but developed in true Open Source spirit is <a href="https://github.com/NancyFx/Nancy">NancyFX</a>.</p>
<p>However if like me you like Web Services and still want to use a framework optimized for the task but consider <a href="https://github.com/ServiceStack/ServiceStack/#anti-wcf">WCF to be an anti-pattern promoting, over architected abstraction</a> I&#8217;m happy to highlight a more elegant option in <a href="http://www.servicestack.net">Service Stack</a> which does the same job as WCF in allowing you to expose XML, JSON and SOAP services (as well as CSV, JSV &amp; HTML formats) but does so cleanly, out-of-the-box, without any configuration required! It&#8217;s typed, DTO-first development model gets out of your way providing a friction-free dev experience that encourages the development of clean, best-practice web services &#8211; easily consumable from any client.</p>
<p>I should note the latest Web Service offering coming out of Redmond: <a href="http://wcf.codeplex.com/wikipage?title=WCF%20HTTP">WCF Web API</a> is not be confused with WCF (even if the naming tries) does a much better job of &#8216;exposing HTTP and REST&#8217; rather than hiding it like the original WCF framework upon which it is built. This may work better for you, although my preference for Open source solutions favouring light, DRY, typed, performance-focused API&#8217;s with the ability to run cross platform keeps me using and continue to recommend and maintain Service Stack for the foreseeable future.</p>
<h3>Hello, F# World!</h3>
<p>To get started we just need the Service Stack dlls that can be <a href="https://github.com/ServiceStack/ServiceStack/downloads">downloaded from GitHub</a>. In the unzipped folder you can spark up your favourite text editor and write your first Hello, World web service which looks like <a href="https://gist.github.com/1247149">[gist]</a>:</p>
<pre class="brush: csharp; title: ;">
open System
open ServiceStack.ServiceHost
open ServiceStack.WebHost.Endpoints

type Hello = { mutable Name: string; }
type HelloResponse = { mutable Result: string; }
type HelloService() =
    interface IService&lt;Hello&gt; with
        member this.Execute (req:Hello) = { Result = &quot;Hello, &quot; + req.Name } :&gt; Object

//Define the Web Services AppHost
type AppHost =
    inherit AppHostHttpListenerBase
    new() = { inherit AppHostHttpListenerBase(&quot;Hello F# Services&quot;, typeof&lt;HelloService&gt;.Assembly) }
    override this.Configure container =
        base.Routes
            .Add&lt;Hello&gt;(&quot;/hello&quot;)
            .Add&lt;Hello&gt;(&quot;/hello/{Name}&quot;) |&gt; ignore

//Run it!
[&lt;EntryPoint&gt;]
let main args =
    let host = if args.Length = 0 then &quot;http://*:8080/&quot; else args.[0]
    printfn &quot;listening on %s ...&quot; host
    let appHost = new AppHost()
    appHost.Init()
    appHost.Start host
    Console.ReadLine() |&gt; ignore
    0
</pre>
<p>The rest of the code except for the 5 lines of code needed to create the actual service need only be written once which is just used to setup the AppHost and run it, in this case as a Console Application.</p>
<p>Great, once you copy all that in, and hit save using the filename Hello.fs &#8211; you can compile with the 1-liner:</p>
<pre class="brush: csharp; title: ;">fsharpc -r:ServiceStack.Common.dll -r:ServiceStack.Interfaces.dll -r:ServiceStack.Text.dll -r:ServiceStack.dll Hello.fs</pre>
<p>Which cuts you a nice Hello.exe that you can double-click to run on Windows, otherwise run on OSX or Linux with:</p>
<pre class="brush: csharp; title: ;">sudo mono Hello.exe</pre>
<p>And Voila! your stand alone F# self-hosting Web Service is ready to serve you at: <a href="http://localhost:8080/hello/FSharp!">http://localhost:8080/hello/FSharp!</a></p>
<h3>Convert into an ASP.NET Web Service</h3>
<p>To convert this into an ASP.NET application we just need to do some minor tweaks add the appropriate files to deal with the nuances of having an ASP.NET application. For this we need to venture back to a time before VS.NET templates existed that did all this for us.<br />
Note: All files including HelloAsp.fs, Global.asax and Web.Config files used in the walkthrough below are available on this <a href="https://gist.github.com/1247567">[gist]</a>.</p>
<p>First lets take a copy of the file and call it <strong>HelloAsp.fs</strong></p>
<p>1. As we want to create a .NET assembly we wrap the entire script in a namespace adding the declaration on top and indenting the rest of the file</p>
<pre class="brush: csharp; title: ;">namespace HelloFSharp</pre>
<p>2. Change the AppHost from a Http Listener to an ASP.NET AppHost by removing the word <strong>HttpListener</strong> from AppHostHttpListenerBase e.g:</p>
<pre class="brush: csharp; title: ;">
    type AppHost =
        inherit AppHostBase
        new() = { inherit AppHostBase(&quot;Hello F# Services&quot;, typeof&lt;HelloService&gt;.Assembly) }
        override this.Configure container =
            base.Routes
                .Add&lt;Hello&gt;(&quot;/hello&quot;)
                .Add&lt;Hello&gt;(&quot;/hello/{Name}&quot;) |&gt; ignore
</pre>
<p>3. Replace starting the AppHost from the command line with initialising it from HttpApplication Application_Start() event, i.e:</p>
<pre class="brush: csharp; title: ;">
    type Global =
        inherit System.Web.HttpApplication
        new() = { }
        member x.Application_Start() =
            let appHost = new AppHost()
            appHost.Init()
</pre>
<p>4. Create the Global.asax stub to point it to the Global type, i.e:</p>
<pre class="brush: csharp; title: ;">echo &quot;&lt;%@ Application Inherits=\&quot;HelloFSharp.Global\&quot; %&gt;&quot; &gt;&gt; Global.asax</pre>
<p>5. Compile HelloAsp.fs into a library since its now an ASP.NET app instead of a stand-alone executable:</p>
<pre class="brush: csharp; title: ;">fsharpc -r:ServiceStack.Common.dll -r:ServiceStack.Interfaces.dll -r:ServiceStack.Text.dll -r:ServiceStack.dll --target:library HelloAsp.fs</pre>
<p>6. make a bin directory and copy all the dlls into it:</p>
<pre class="brush: csharp; title: ;">mkdir bin &amp;&amp; cp *.dll bin</pre>
<p>7. Copy the desired Web.config mapping from <a href="http://www.servicestack.net/ServiceStack.Hello/#rootpath">Hello World Tutorial</a></p>
<pre class="brush: csharp; title: ;">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;configuration&gt;
&lt;system.web&gt;
  &lt;httpHandlers&gt;
    &lt;add path=&quot;*&quot; type=&quot;ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack&quot; verb=&quot;*&quot;/&gt;
  &lt;/httpHandlers&gt;
&lt;/system.web&gt;
&lt;!-- Required for IIS 7.0 --&gt;
&lt;system.webServer&gt;
  &lt;handlers&gt;
    &lt;add path=&quot;*&quot; name=&quot;ServiceStack.Factory&quot; type=&quot;ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack&quot; verb=&quot;*&quot; preCondition=&quot;integratedMode&quot; resourceType=&quot;Unspecified&quot; allowPathInfo=&quot;true&quot; /&gt;
  &lt;/handlers&gt;
&lt;/system.webServer&gt;
&lt;/configuration&gt;
</pre>
<p>8. Run the .NET 4.0 version of xsp in the current directory</p>
<pre class="brush: csharp; title: ;">xsp4</pre>
<p>If all went well you should see the following output:</p>
<pre class="brush: csharp; title: ;">
Listening on address: 0.0.0.0
Root directory: /Users/mythz/src/fsharp/fsharpstack
Listening on port: 8080 (non-secure)
Hit Return to stop the server.
</pre>
<p>and you&#8217;ll be able to hit the service again using the same url at <a href="http://localhost:8080/hello/FSharp!">http://localhost:8080/hello/FSharp!</a></p>
<p>You now have a fully-fledged ServiceStack ASP.NET application that can be hosted in any ASP.NET compatible web server e.g:</p>
<ul>
<li>IIS</li>
<li>Apache + mod_mono</li>
<li>Nginx + MonoFastCGI</li>
<li>XSP</li>
<li>WebDevServer.exe</li>
</ul>
<p>Now that you know how to create functional F# web services, you can read more about the goodies you get for free when using Service Stack, complete with live links to all those juicy XML, JSON, SOAP, HTML, CSV and JSV Formats check out: <a href="http://www.servicestack.net/ServiceStack.Hello/">http://www.servicestack.net/ServiceStack.Hello/</a></p>
<h3>Next &#8211; Async Goodness!</h3>
<p>With the basics out of the way tomorrow we&#8217;ll tackle a more complex service taking advantage of F#&#8217;s async and parallel good ness to provide nice high-level aggregate features off twitters public API.</p>
<p>Stay Tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.servicestack.net/mythz_blog/?feed=rss2&amp;p=785</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A Look at F# from C#&#8217;s corner</title>
		<link>http://www.servicestack.net/mythz_blog/?p=765</link>
		<comments>http://www.servicestack.net/mythz_blog/?p=765#comments</comments>
		<pubDate>Tue, 27 Sep 2011 03:49:31 +0000</pubDate>
		<dc:creator>mythz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.servicestack.net/mythz_blog/?p=765</guid>
		<description><![CDATA[For a while now I&#8217;ve been hearing many great things that have been coming out of Microsoft Research&#8217;s popular .NET language F#. For the unfamiliar, F# is a strongly-typed, functional-based language for .NET &#8211; originally created by Don Syme (better known to most as the father of generics in .NET) it has now become a fully supported [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D765"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D765&amp;source=demisbellot&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<div>
<p>For a while now I&#8217;ve been hearing many great things that have been coming out of Microsoft Research&#8217;s popular .NET language F#. For the unfamiliar, F# is a strongly-typed, functional-based language for .NET &#8211; originally created by <a href="http://blogs.msdn.com/b/dsyme/">Don Syme</a> (better known to most as <a href="http://blogs.msdn.com/b/dsyme/archive/2011/03/15/net-c-generics-history-some-photos-from-feb-1999.aspx">the father of generics in .NET</a>) it has now become a fully supported language in .NET with soon to be first-class support in VS.NET.</p>
<p>Despite being deeply inspired by its functional roots, it stands out from other languages in that it also supports imperative and OOP paradigms as well. Boasting both interactive and compile modes, it&#8217;s been holding over C# lately, sporting a more succinct syntax and already comes complete with features like  <a href="http://msdn.microsoft.com/en-us/library/dd233250.aspx">async workflows</a> and an interactive mode we wont see in C# until V.Next.</p>
<p>The <a href="http://blogs.msdn.com/b/fsharpteam/archive/2011/09/14/f-3-0-developer-preview-now-available.aspx">announcement of F# 3.0</a> pushes the envelope even further where the new Type Providers promises to be even more productive by allowing you to build against a strong-typed API (with intelli-sense) against a runtime datasource.</p>
<p>So not wanting to fall too far behind a good thing I&#8217;ve made F# on this years must-learn-list. Before looking at F# I have to admit I thought C# was close to the perfect server-side language with its biggest weaknesses just being the lack of string interpolation and <a href="http://www.airs.com/blog/archives/277">Go&#8217;s-like interfaces</a>. Given that, I was quite surprised to find how much more elegant F# is in a number of ways:</p>
<h3>Type Inference to the Max</h3>
<p>Where some C# developers are still reluctant to use <strong>var</strong> in their works, F# takes type inference to the extreme where you can effectively omit type declarations whenever the type is not ambiguous and can be safely inferred.</p>
<h3>Less code, the better</h3>
<p>I&#8217;m a firm believer <a style="font-size: 13px; font-weight: normal;" href="http://blog.vivekhaldar.com/post/10669678292/size-is-the-best-predictor-of-code-quality">a smaller code base is a good one</a> and we should be striving for a DRY, tight code-base where the solution permits. Having less code means there is less to maintain and less chance for something to go wrong, where a high signal-to-noise ratio is generally more readable as you&#8217;re able to focus more on the solution and less on the needless abstractions that get in the way.</p>
<p><span style="font-size: 13px; font-weight: normal;">In addition to type inference, F# has many features to tackle code boat including:</span></p>
<ul>
<li>Language support for <a href="http://en.wikibooks.org/wiki/F_Sharp_Programming/Tuples_and_Records">tuples</a></li>
<li><a href="http://en.wikibooks.org/wiki/F_Sharp_Programming/Tuples_and_Records">Records</a> and <a href="http://en.wikibooks.org/wiki/F_Sharp_Programming/Discriminated_Unions">Discriminated unions</a> in-place of lightweight classes</li>
<li><a href="http://en.wikibooks.org/wiki/F_Sharp_Programming/Pattern_Matching_Basics">Pattern matching</a> replacing heavy chained and nested <strong>if</strong> and <strong>switch</strong> statements.</li>
<li><a href="http://lorgonblog.wordpress.com/2008/03/30/pipelining-in-f/">Pipelining</a> allowing for readable chained expressions.</li>
<li><a href="http://en.wikibooks.org/wiki/F_Sharp_Programming/Higher_Order_Functions">Currying</a> allowing for functional composition instead of needless abstractions</li>
</ul>
</div>
<p>Out of all its features I believe what promotes the least code bloat is the quality of F#&#8217;s community (see: <a href="http://www.paulgraham.com/pypar.html">The Python Paradox</a>) and its preference to simple, elegant composable solutions.  This is contrast to C#&#8217;s abstraction fetish it copied from Java and its relentless need to cater for the lowest common Drag n&#8217; Drop developer and impress them with 5 minute demos. Although it&#8217;s a subject for another post, this rarely leaves us with quality frameworks or APIs.</p>
<p><span style="font-size: 15px; font-weight: bold;">Functional vs Imperative</span></p>
<div>
<p>Even though F# allows for programming in procedural, Object Orientated and functional paradigms, its roots and optimized syntax lends itself towards functional-style of programming. In many ways functional programming provides more elegant and robust solutions. Luca Bolognese explains this best in his <a href="http://channel9.msdn.com/Blogs/pdc2008/TL11">excellent Intro to F#</a>, where the instincts of a C# programmer attempts to solve a problem imperatively resulting in mutable variables and disjointed logic allowing for moving parts to go wrong.  In his example Luca uses the <strong>&#8216;sum of squares&#8217;</strong> as an example where the budding C# developer would approach it into something like this:</p>
<pre class="brush: csharp; title: ;">
public int Square(int num)
{
	return num * num;
}

public int SumOfSquares(IEnumerable&lt;int&gt; list)
{
	var sum = 0;
	foreach (var num in list)
	{
		sum += Square(num);
	}
	return sum;
}

var nums  = Enumerable.Range(1,100);
Console.WriteLine(&quot;Sum of squares of 1-100: {0}&quot;, SumOfSquares(nums));
</pre>
<p>The F# functional approach would lend it more to the original question, i.e. <strong>square the numbers, then sum them</strong>:</p>
<pre class="brush: csharp; title: ;">
let squares x = x * x
let sumOfSquares nums =
	nums
	|&gt; Seq.map squares
	|&gt; Seq.sum

printfn &quot;Sum of squares of 1-100: %d&quot; (sumOfSquares [1..100])
</pre>
<p>Although oddly enough despite its already succinctness, it can be even further reduced to:</p>
<pre class="brush: csharp; title: ;">
let sumOfSquares nums = nums |&gt; Seq.sumBy squares
</pre>
<p>I recommend watching the rest of Luca&#8217;s video as he goes on to show how the F# solution lends itself to easy parallelization, without interrupting the existing flow of logic.</p>
<p>In a real world problems closer to home, <a href="http://twitter.com/#!/ayende">@ayende</a> recently posted one of his interview questions online asking for <a href="http://ayende.com/blog/108545/the-tax-calculation-challenge">example solutions to calculate israels tax</a>. As expected <a href="http://pastebin.com/zJADQGdx">most</a> <a href="http://pastebin.com/NCmjVJE0">C#</a> <a href="https://gist.github.com/1237076">solutions</a> <a href="https://gist.github.com/1237707">were</a> <a href="https://gist.github.com/9cbe9ab68f75f52eebfb">similarly</a> written the same way complete with mutable variables, tightly coupled solutions &#8211; many of them having custom types and other artefacts.  Comparatively the <a href="http://pastebin.com/g9UDu5vF">few</a> <a href="https://gist.github.com/1244370">F#</a> <a href="https://gist.github.com/1236106">solutions</a> posted had significantly less code, yet was easier to read and maintain.</p>
<p>My attempt at solving this problem in a purely functional style resulted in this <a href="https://gist.github.com/1236106">[gist]</a>:</p>
<pre class="brush: csharp; title: ;">
let taxOf salary taxRates =
	((0m,0)::taxRates, taxRates)
		||&gt; Seq.zip
		 |&gt; Seq.map(fun ((_, prevBand),(rate, band)) -&gt; (prevBand, rate, band))
		 |&gt; Seq.sumBy(fun (prevBand, rate, band) -&gt;
			match salary with
				| x when x &lt; prevBand -&gt; 0m
				| x when x &gt; band -&gt; decimal(band - prevBand) * rate
				| x -&gt; decimal(x - prevBand) * rate
		    )

let israelTaxRates = [
	0.10m, 5070;
	0.14m, 8660;
	0.23m, 14070;
	0.30m, 21240;
	0.33m, 40230;
	0.45m, System.Int32.MaxValue]

let taxOfIsrael salary = israelTaxRates |&gt; taxOf salary

//Usage: taxOfIsrael 5800
</pre>
<p>The nice aspects of this solution was having the tax rates and bands in an easily readable and maintainable collection optimized for the reader (like all other F# solutions) separate from its implementation. The internal logic is neatly coupled together into 3 readable scenarios, making it easy to work out how the tax was calculated.</p>
<p>Another nice feature is being able to easily combine the implementation and input tax rates to create a high order <strong>taxOfIsrael</strong> function that ultimately performs the task. This in-built ability to curry functions makes functional composition a breeze and after using it for a while I can quickly see how it&#8217;s more elegant to OOP programming style in a lot of areas.</p>
<h3>Interactive Mode</h3>
<p>Inside Visual Studio 2010 (or by using <strong>fsi</strong> on the command line) is F# Interactive mode which works very much like Ruby&#8217;s irb or  Pythons interactive mode, it&#8217;s just rare to see this from a typed .NET language, although <a href="http://boo.codehaus.org/Interactive+Interpreter">Boo was likely the first to do this</a>.</p>
<h3>F# open and F# everywhere!</h3>
<p>Despite F# being the latest creation forged in the deep trenches of Microsoft&#8217;s R&amp;D department, F# is surprisingly and arguably the most open of all of Microsofts languages with their entire implementation <a href="https://github.com/fsharp/fsharp">available on GitHub</a> and free to use, released under the liberal and OSS approved <a href="https://github.com/fsharp/fsharp/blob/master/LICENSE">Apache 2.0 licence</a>! This wouldn&#8217;t mean much if it didn&#8217;t immediately work elsewhere however Don Syme and his team have done a good job actively supporting Mono, going as far as reporting blocking Mono bugs, ensuring it continues to work flawlessly. It&#8217;s even being currently distributed with the latest release of Mono on OSX.</p>
<p>Being this open is a treat, we can finally <a href="http://functional-variations.net/crossplatform/">build GTK desktop applications </a>with a typed, fast functional language using Open Source components end-to-end!</p>
<p>I&#8217;m actually surprised how well it works where I&#8217;m doing all current F# development on an OSX Macbook Air, deploying my finished solutions onto <a href="http://www.servicestack.net">http://www.servicestack.net</a> CentOS linux server for hosting.</p>
<h3>Getting Started with F#</h3>
<p>Although not mentioned here, it should be noted F# is great for concurrent programming tasks as well. It is also particular good at creating composable asynchronous work flows &#8211; which happened to be the source of inspiration for C#&#8217;s 5.0 async/await feature.</p>
<p>Getting started with F# is easy where if you have Visual Studio 2010 &#8211; you&#8217;ve already got it! Just create an F# project and your good to go. For all other platforms <a href="http://www.tryfsharp.org/Tools.aspx">follow this link</a>.</p>
<p>For the newbie budding developer, I recommend the following learning resources:</p>
<ul>
<li><a href="http://channel9.msdn.com/Blogs/pdc2008/TL11">Luca Bolognese &#8211; Intro to F#</a> &#8211; fun and entertaining</li>
<li><a href="http://www.tryfsharp.org/Resources/Videos.aspx">More F# Videos</a> &#8211; both introductory and advanced</li>
<li><a href="http://en.wikibooks.org/wiki/Programming:F_Sharp">The F# Wiki</a> &#8211; covers the essential language features</li>
<li><a href="http://www.tryfsharp.org/Resources/Books.aspx">Any of the quality books on F#</a> &#8211; for dead tree lovers</li>
<li><a href="http://cs.hubfs.net/">HubFS </a>- The defacto F# Forum</li>
</ul>
<h4>Blogs</h4>
<div>
<ul>
<li><a href="http://blogs.msdn.com/b/dsyme/">Don Syme</a> &#8211; The Master</li>
<li><a href="http://blogs.msdn.com/b/fsharpteam/">MSDN F# Team Blog</a></li>
<li><a href="http://lorgonblog.wordpress.com/">Inside F#</a> &#8211; Brian McNamara from MSDN Team</li>
<li><a href="http://strangelights.com/blog/">Robert Pickering</a> &#8211; Author of <a href="http://www.amazon.com/Beginning-F-Robert-Pickering/dp/1430223898">Beginning F#</a></li>
<li><a href="http://tomasp.net/blog/">Tomas Petricek</a> &#8211; Co Author of <a href="http://www.amazon.com/gp/product/1933988924/ref=as_li_tf_il?ie=UTF8&amp;tag=httptomasnet-20&amp;linkCode=as2&amp;camp=217145&amp;creative=399369&amp;creativeASIN=1933988924">Real World Functional Programming</a> with Jon Skeet</li>
</ul>
</div>
<h3>Next up: Easy Self Hosted, Cross Platform F# Web Services</h3>
<p>Although not a surprise for a .NET language, I&#8217;m happy to report F# works flawlessly with <a href="http://www.servicestack.net">Service Stack</a> where its thin API doesn&#8217;t get in F#&#8217;s way &#8211; allowing it to easily create elegant self-hosted solutions. In my next instalment I&#8217;ll show how you can easily create an <strong>async+parallel cached twitter proxy</strong> that works cross platform on Windows/OSX and Linux in =~ <strong>100 LOC</strong>.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.servicestack.net/mythz_blog/?feed=rss2&amp;p=765</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>First day on the job, after 1 crazy week!</title>
		<link>http://www.servicestack.net/mythz_blog/?p=748</link>
		<comments>http://www.servicestack.net/mythz_blog/?p=748#comments</comments>
		<pubDate>Fri, 26 Aug 2011 09:26:46 +0000</pubDate>
		<dc:creator>mythz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.servicestack.net/mythz_blog/?p=748</guid>
		<description><![CDATA[Wow what a week! it&#8217;s been an eventful one to remember: there are Rebellions overthrowing dictatorships in Libya, Earthquakes in Washington with tremors being felt in New York and hurricane Irene swirling around keen on paying us a visit anytime now. All this just setting the stage for the sad news I hoped not to hear [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D748"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D748&amp;source=demisbellot&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Wow what a week! it&#8217;s been an eventful one to remember: there are Rebellions overthrowing dictatorships in Libya, Earthquakes in Washington with tremors being felt in New York and hurricane Irene swirling around keen on paying us a visit anytime now. All this just setting the stage for the sad news I hoped not to hear for many more years with Mr. Apple (aka Steve Jobs) bowing out on top, relinquishing command as king of the tech world.</p>
<p>Meanwhile all this is happening I&#8217;ve undergone some radical lifestyle changes as well with just having just moved to the city of New York after a 2 month hiatus from programming, travelling the wrong way round the world from London. I&#8217;m now currently settling into my new apartment in Brooklyn whilst just having finished the first day at my new job after having joined the talented team at: <a href="http://stackexchange.com/">http://stackexchange.com</a>!</p>
<p>My new, New York life is largely thanks to the opportunity I received from the eloquent <a href="http://twitter.com/spolsky">Joel Spolsky</a>. Which was pretty surreal in itself , given I&#8217;ve been following and enjoying his entertaining articles on his <a href="http://joelonsoftware.com/">world famous blog</a> since the dawn of my computing career &gt;10 years ago!</p>
<p>My first call to action at StackExchange will be helping &#8220;Stand Up Matt&#8221; <a href="http://twitter.com/clipperhouse">@clipperhouse</a> and &#8220;Mad Typist&#8221; <a href="http://twitter.com/JasonPunyon">@JasonPunyon</a> (my first impressions &#8211; sorry guys! <img src='http://www.servicestack.net/mythz_blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ) enhance the new StackOverflow Careers 2.0 site &#8211; Something I&#8217;ll be looking forward to as It&#8217;ll have the potential to help and reach a very large audience. This is in stark contrast to the standard enterprise developer positions I&#8217;ve found myself in over the years &#8211; developing custom backend solutions that are usually only destined to support a handful of people.</p>
<h2>Day 1</h2>
<p>With having survived Day 1 (and not having done much), the biggest change I&#8217;ve noticed so far is the view. Where back in London I had a quiet desk next to a peaceful, lifeless cemetery where on a winters day I&#8217;m greeted with a ghostly calming atmosphere:</p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/08/view-digiterre.jpg"><img class="alignnone size-full wp-image-749" title="view-digiterre" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/08/view-digiterre.jpg" alt="" width="720" height="540" /></a></p>
<p>In New York that image is a distant memory where sitting next to a window on the 26th floor, neighbouring skyscrapers hit you in the face:</p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/08/view-ny-sunny.jpg"><img class="alignnone size-full wp-image-751" title="view-ny-sunny" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/08/view-ny-sunny.jpg" alt="" width="720" height="540" /></a></p>
<p>Although this changes very quickly with the bit of rain today, you still get a ghostly picture but instead of snow tipped tombstones &#8211; it&#8217;s the city of New Jersey!</p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/08/view-ny-rainy.jpg"><img class="alignnone size-full wp-image-753" title="view-ny-rainy" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/08/view-ny-rainy.jpg" alt="" width="720" height="540" /></a></p>
<p>That&#8217;s about it for my first day, I&#8217;m told my second will be even better with some in-house Team StackOverflow beer festival on Friday to close off the week!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.servicestack.net/mythz_blog/?feed=rss2&amp;p=748</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dark Pastel Visual Studio Theme</title>
		<link>http://www.servicestack.net/mythz_blog/?p=729</link>
		<comments>http://www.servicestack.net/mythz_blog/?p=729#comments</comments>
		<pubDate>Thu, 26 May 2011 14:06:04 +0000</pubDate>
		<dc:creator>mythz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.servicestack.net/mythz_blog/?p=729</guid>
		<description><![CDATA[Since I&#8217;m pretty happy with the Dark Visual Studio Theme I&#8217;ve been rolling for a long time with I thought I&#8217;d share it with the wider .NET world so others can bask in the glow of an eye friendly dark theme when they&#8217;re doing their midnight code runs! I&#8217;ve had it for so long that I&#8217;m [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D729"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D729&amp;source=demisbellot&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Since I&#8217;m pretty happy with the Dark Visual Studio Theme I&#8217;ve been rolling for a long time with I thought I&#8217;d share it with the wider .NET world so others can bask in the glow of an eye friendly dark theme when they&#8217;re doing their midnight code runs!</p>
<p>I&#8217;ve had it for so long that I&#8217;m no longer sure where it was originally based, but looking at <a href="http://www.hanselman.com/blog/VisualStudioProgrammerThemesGallery.aspx">Scott Hanslemans VS.NET theme gallery</a> it looks like it&#8217;s a mix of <a href="http://blog.wekeroad.com/2007/10/17/textmate-theme-for-visual-studio-take-2/">Rob Conery&#8217;s TextMate</a> and <a href="http://studiostyl.es/schemes/vibrant-ink">John Lam&#8217;s Vibrant Ink</a>.<br />
Over the years where I&#8217;ve felt the contrast could be improved, I&#8217;ve spiced it up with my own unique blend of colours from the pastel famiglia palette.</p>
<p>And since this theme isn&#8217;t complete without a name I&#8217;m calling it&#8230;.</p>
<h2>Dark Pastel</h2>
<p>Here&#8217;s a code screenshot:</p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/05/darkpastel-screenshot2.png"><img class="alignnone size-full wp-image-744" title="darkpastel-screenshot" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/05/darkpastel-screenshot2.png" alt="C# code screenshot" width="650" height="738" /></a></p>
<p>Some Web.config love:</p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/05/darkpastel-screenshot-02.png"><img class="alignnone size-full wp-image-741" title="darkpastel-screenshot-02" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/05/darkpastel-screenshot-02.png" alt="Web.config screenshot" width="650" height="784" /></a></p>
<p>A splash of HTML:</p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/05/darkpastel-screenshot-03.png"><img class="alignnone size-full wp-image-742" title="darkpastel-screenshot-03" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2011/05/darkpastel-screenshot-03.png" alt="HTML screenshot" width="650" height="736" /></a></p>
<h3>And the <a href="http://www.servicestack.net/files/DarkPastel-2011-05.vssettings">all important download</a>.</h3>
<p><span style="color: #ffffff;">.</span></p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.servicestack.net/mythz_blog/?feed=rss2&amp;p=729</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>REST Media Types, SOAP, Heavy frameworks and Literate Programming</title>
		<link>http://www.servicestack.net/mythz_blog/?p=665</link>
		<comments>http://www.servicestack.net/mythz_blog/?p=665#comments</comments>
		<pubDate>Sun, 17 Apr 2011 18:31:51 +0000</pubDate>
		<dc:creator>mythz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.servicestack.net/mythz_blog/?p=665</guid>
		<description><![CDATA[Obviously the title of this post doesn&#8217;t make sense to be all in same article, yet I&#8217;ve still managed to carry an underlying theme interlinking the above topics : -). Effectively it&#8217;s fairy forest through the trees stuff where I&#8217;m hoping to encourage the pursuit of end user value over and above all else. Disadvantages of [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D665"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D665&amp;source=demisbellot&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Obviously the title of this post doesn&#8217;t make sense to be all in same article, yet I&#8217;ve still managed to carry an underlying theme interlinking the above topics : -). Effectively it&#8217;s fairy forest through the trees stuff where I&#8217;m hoping to encourage the <strong>pursuit of end user value</strong> over and above all else.</p>
<h2><span>Disadvantages of Custom Mediatypes</span></h2>
<p>Although I&#8217;m going to focus on Custom Media Types in this instance (since it reflects my most recent public discussion), the essence of my argument can be applied to many other areas, protocols, libraries, patterns, etc being advocated in software development today.</p>
<p>The main problem I have with Custom Media Types, is the same I have with any other technologies <strong>asking me to devote more effort</strong> to produce to what I ultimately conceive as a less valueable output. Where the only time when it proves to be beneficial over raw canonical data forms is when the consuming client has built-in support for the custom media format saving the integration point since the client already understands how to process the response.</p>
<p>Although this post may contain a critique on certain facets of REST, I&#8217;m by no means advocating against it as overall it&#8217;s a far superior more elegant approach to designing services than the SOAP and WS-* stack (which I&#8217;m happy to see now starting to slowly fade out of existence). In this light I instead consider myself more a devils advocate providing critique on parts which provide minimal value yet require significant more effort to implement. So consider this a public service announcement as due to the taboo nature of REST you&#8217;re unlikely to find many posts like this which is partly my motivation for writing it.</p>
<p>There are times when custom mediatypes are useful however what&#8217;s not being discussed in these cases (and what I continue to have issue with) is the amount of airtime given to what I consider a <strong>small % of applicability</strong> and real-world use. This has a tendency to result in a significant body of knowledge flowing around new developers information streams and if they didn&#8217;t know any better would think that this is the right way to go about developing web services. What we&#8217;re going to end up with are solutions looking for problems and a swath of invented custom formats &#8211; more then there deserves to be. Given the unhealthy amount of coverage given to REST frameworks used to flex different parts of REST theory, I fully expect solutions developed just because developers want to obtain full-compliance REST reputation badges implementing non-trivial <strong>CONNEG + Custom Media Types</strong> multi-hop solutions when far simpler, more direct solutions can elegantly solve the same problem space. Of course I fully expect people to argue that a superior solution can be achieved even with full-compliance of REST <strong>HATEOS restrictions</strong>, and I simply want to re-iterate for developers to consider, to understand and weigh all options, and that <strong>Getting Things Done</strong> in the minimum LOC and effort possible is also a worthy goal to strive for, as when we get older, time becomes more precious and being able to hone this skill will ultimately pay dividends later : -)</p>
<h4>Web Services should be optimized for Data Formats</h4>
<p>In my 10+ years as a backend systems developer, I can count on one hand the number of times when creating custom media types has proven beneficial or was a customer requirement. The majority of my time is spent developing systems with a primary purpose of servicing clients, thick, thin or otherwise. In my web services world view, not all media types are created equal and its the popular data formats <strong>XML, JSON, SOAP, CSV</strong>, etc  that are ultimately exposed by web services and consumed by its clients. It&#8217;s these formats I believe Web Service Frameworks should be optimized for as they provide the most utility, re-usability and value.</p>
<p>As expected my real-world experience is also the primary influence on <a href="http://www.servicestack.net">http://www.servicestack.net</a> where the above data formats are built-in and are configured to work with all your services automatically. Your C# logic remains DRY and is fused with the expected HTTP result providing a free logic block to be able to return any C# POCO or throw any C# Exception. At the same time making all services available on all above data formats. These are the traits I&#8217;ve found to be the most productive and ultimately provide a friction-free development experience.</p>
<p>The other notable mediatypes which are actually more prominent than web services data formats are the media types understood by web browsers. By this I mean HTML/CSS/JavaScript /img/vids/etc. The development of web sites have long been the focus for most development platforms where websites have now become the most important deployment target for most new applications. These web formats are first class formats where entire web frameworks are built around and optimized for, which you should be using instead of Web Service Frameworks.</p>
<h3>Custom formats are still important, just not of primary importance</h3>
<p>Despite my criticisms, I still think the production of custom formats is important<strong> when it&#8217;s required</strong>, and <a href="http://www.servicestack.net">ServiceStack</a> actually has very good support for it with one of the <a href="http://www.servicestack.net/ServiceStack.Northwind/vcard-format.htm">DRY-est API&#8217;s</a> you&#8217;re likely to see in accomplishing this task. I just don&#8217;t personally give prominence to this functionality since it&#8217;s <strong>not where I believe web service developers should be speding their time</strong> in implementing solutions with. Although for the interested this is how ServiceStack implements the <a href="http://www.servicestack.net/ServiceStack.Northwind/vcard-format.htm">VCard Format</a>. Where its non-invasive layered API makes it trivial to support any custom media format that is well supported since its the same integrated pipeline the newer built-in <a href="https://github.com/ServiceStack/ServiceStack/wiki/HTML5ReportFormat">HTML</a> and <a href="https://github.com/ServiceStack/ServiceStack/wiki/ServiceStack-CSV-Format">CSV</a> formats are using.</p>
<p>Note: at the lowest HTTP API level in every web framework (e.g. IHttpHandler, HttpServletRequest, etc) this has always been possible, so all web service frameworks are showcasing its high-level API to achieve this end. Some frameworks make this functionality available using APIs mapping directly to REST concepts, ServiceStack however prefers to make it as DRY, typed and expressive as possible.</p>
<h3>Data formats the preferred choice in SOA systems</h3>
<p>A key objective in SOA systems and web services today is to <strong>servicify and free</strong> your data making it as universally available and re-usable as possible. Given these objectives it is common to see SOA systems today make use of <strong>HTTP </strong>for their transport protocol and utilizing either <strong>XML </strong>or <strong>JSON </strong>for their data formats. This is largely because the data formats contain the essence of your data where should they need to at a later date, your clients can use this canonical form of your data and create the custom media types themselves. The same is not true the other way around where if the only format your service provided were custom media formats (e.g. the VCard format) it not only takes much more effort to extract the raw data, but the specific media type will only contain the subset of your contact data as supported by the format. So if your developers only have an option to deliver 1 format for your resource, you&#8217;re best to make it a raw data format since the development of other formats can still be achieved by your clients long after the developers have moved on.</p>
<p>In summary you should only be accessing the specific VCard format (or other specific mediatype) <strong>only </strong>if your client already has built-in support for it. Since it requires more effort on the client and server to implement and access otherwise.</p>
<p>It is therefore important to remain vigilant and keep the <strong>80/20 Rule </strong>in mind (or in the case of custom media formats the <strong>95/5</strong> rule : -) and treat custom media types as <strong>complimentary formats</strong> that you should <strong>only add in addition</strong> to your data formats. When development of your SOA services have finished you want to ensure it&#8217;s data is as accessible and re-usable as possible in the formats that provide the most utility to your current and future consumers of your services, i.e. the data formats.</p>
<h2>The guiding value light</h2>
<p>With the current demise of <a href="http://en.wikipedia.org/wiki/SOAP">SOAP</a>, <a href="http://en.wikipedia.org/wiki/REST">REST</a> is making it&#8217;s way back into the forefront of IT minds.<br />
The value of REST has always been available in HTTP/1.1 since its inception but between the marketing and committees pushing their own agendas, the Enterprise development world was largely oblivious to its possibilities as they were taught if your data didn&#8217;t come in a XML decorated envelope it&#8217;s not a real web service.</p>
<p>Its come-back can largely be attributed to developers and companies ignoring the blind advice of big iron Company&#8217;s and instead discovered that they are better able to provide value by embracing the inherent properties in HTTP rather than the friction-encumbered dev experience of building SOAP web services.</p>
<p>Displacing big iron-backed monolithic standards is hard, it takes courageous companies willing to discard current enterprise teachings who are able to re-think the essence of what they&#8217;re trying to achieve.</p>
<h3>Focusing on max value and min effort</h3>
<p>It&#8217;s therefore important we don&#8217;t repeat the same mistakes and don&#8217;t lose sight of what the value proposition on the technologies we ultimately choose to adopt, can provide. I&#8217;m constantly seeing blind embracing of software process, approach or technology where at the most extreme levels its treated akin to a religion, instead of what it should be: <strong>productive tools serving a means to an end</strong>.</p>
<h4>HATEOS</h4>
<p>REST at its extreme conformance imposes some <a href="http://en.wikipedia.org/wiki/HATEOAS">hefty HATEOS restrictions</a> which coupled with most Hyper media driven applications fixation on XML, does not leave you with a very productive window to develop in. If you see real-world value in conforming to these restrictions then by all means adopt them, I personally don&#8217;t, and since collecting stamps of approvals from the REST community is not my #1 priority, I routinely discard they exist.</p>
<h4>JSON vs XML</h4>
<p>XML is another one of those funny technologies handed down from standard committees as the holy grail data format.  Unfortunately this only holds true when you don&#8217;t have to develop with it, as it&#8217;s a poor programattic fit, making it harder to work with than JSON, that&#8217;s both more verbose and slower as well. A good reference that explores these differences in more detail is Douglas Crockford&#8217;s entertaining talk on <a href="http://www.infoq.com/presentations/Heretical-Open-Source">Heresy &amp; Heretical Open Source</a>.</p>
<p>XML as a interoperable structured data format has its place, at the same time I&#8217;m finding cases where it would be the ideal data format harder to find. I no longer store it in databases, make use of it for efficient messaging or let it go near my mobile or web apps.</p>
<h4>Choosing the right technology</h4>
<p>The way I defend myself from adopting the wrong technology is to take a <strong>cynical view</strong> against all promises, hype and marketing materials. I usually form a picture of the easiest way to develop something and use that as a benchmark to compare other solutions against. The onus then becomes on other frameworks to prove their value by either reducing the amount of effort or code required or in someway enhancing re-usability, performance or promote better maintainability by reducing coupling. If it does not provide any realizable <strong>real-world value</strong> I don&#8217;t spend too much time researching it and continue what I was doing before this Hot Tech Tip landed on my lap.</p>
<p>Basically don&#8217;t take any advice at face value, <strong>understand the benefits</strong> and <strong>amount of effort</strong> to achieve the desired outcome of each approach and choose the one that offers the maximum end user utility given the least effort to implement. <strong>If you don&#8217;t understand the full value</strong> that your architecture/approach/framework is providing, <strong>you won&#8217;t be able to maximize its benefits</strong> and will soon find you&#8217;ve inadvertently subscribed to a solution looking for a problem.</p>
<p>So if you&#8217;re spending a lot of time fighting with your framework just to try to get it to prescribe to some artificial standard or religion it might be time to explore other approaches/technologies. When evaluating technologies think about the concept of <strong>Last principles</strong> where you first look at the ultimate end-user result you want to deliver, then look backwards at the tools, technoligies and frameworks that will best meet this end with the least effort and maximum efficiency.</p>
<h3>Heavy weight libraries and frameworks</h3>
<p>I personally believe that the Java/.NET worlds are plagued with leaky, heavy abstractions that introduce more friction an inertia that they&#8217;re trying to solve. The pain in configuring these monstrosities can be attributed to:</p>
<blockquote><p>&#8220;So much complexity in software comes from trying to make one thing do two things.&#8221;</p>
<p>&#8211; Ryan Singer</p></blockquote>
<p>Whilst the un-intended, unknown or magic behaviour I frequently see at runtime whilst developing in said frameworks I&#8217;m attributing to its poor, leaky abstractions.</p>
<h3>Prefer thin abstractions promoting DRY code</h3>
<p>In recent years I&#8217;ve been more active in proactively shunning heavy frameworks and look to libraries allowing me to write less code and configuration. Configuration is actually a form of inferior code which happens to be more awkward to define object graphs with than your general purpose programming language. What&#8217;s left is a fragile, un-typed mess that you can usually only determine correctness at runtime.</p>
<p>I have many reasons to prefer shorter code-bases which follow my general mantra of <strong>&#8220;You never have to maintain any line of code you didn&#8217;t write&#8221;</strong>. However here a couple of my favourite quotes I&#8217;ve collected on the subject that put this more eloquently than I:</p>
<blockquote><p>&#8220;I happen to hold a hard-won minority opinion about code bases. In particular I believe, quite staunchly I might add, that the worst thing that can happen to a code base is size.&#8221;</p>
<p>&#8211; <a href="http://steve-yegge.blogspot.com/2007/12/codes-worst-enemy.html">Steve Yegge</a></p></blockquote>
<blockquote><p>&#8220;A programmer knows he has achieved perfection not when there is nothing left to add, but when there is nothing left to take away.&#8221;</p>
<p>&#8211; Antoine St Exupery</p></blockquote>
<p>With that said, my general preference is for light-weight development libraries and frameworks with thin abstractions allowing me to capture my logic&#8217;s intent as DRY as possible. Usually this means these libraries have a low artificial construct / concept count whilst remaining expressive at its core.</p>
<h3>The rise of Ruby and Literate Programming</h3>
<p>Despite its poor runtime performance and no sight of any corporate backing, Ruby has been making deep inroads into developers mindshare simply because it allows developers to be more productive. Although the language itself is quite expressive, I&#8217;m attributing it&#8217;s large productivity gains on the communities focus on Simplicity, Convention, DRY-ness and it&#8217;s ultimate goal of its ability to compress logic into pseudo code that runs.<br />
In this goal, it seems either by accident or in a way that was cleverly conceived by the languages author it appears that much of Rubys libraries follow a deep symmetry to Donald Knuth&#8217;s <a href="http://en.wikipedia.org/wiki/Literate_programming">Literate programming</a> which enables programmers to develop programs in the order demanded by the logic and flow of their thoughts.</p>
<h4>Code as literature</h4>
<blockquote><p>&#8220;Meaning belongs to a text or to a program to the extent that it acts upon intelligence in a particular way.&#8221;</p></blockquote>
<blockquote><p>We say that a textual work is &#8220;literary&#8221; if it contains a high density of meaning.</p></blockquote>
<p>The above quotes are from <a href="http://twitter.com/jashkenas">@jashkenas</a> enlightening <a href="http://confreaks.net/videos/379-sunnyconf2010-keynote">talk at Ruby&#8217;s SunnyConf 2010</a> exploring the subject.</p>
<p>Literate programming is an intriguing topic that not only looks to enhance developer productivity but at the same time increases developer enjoyment and satisfaction. I can definitely see its appeal as it seems like a breadth of fresh air especially if you spend your time fighting heavy frameworks in your day job. Having said that Ruby&#8217;s lack of good performance characteristics <a href="https://github.com/mythz/ScalingDotNET">which I consider important</a> keeps me from using the language in any capacity.</p>
<h4>JavaScript&#8217;s star new language &#8211; CoffeeScript</h4>
<p>Luckily <a href="http://jashkenas.github.com/coffee-script/">CoffeeScript</a> is a hot new language that looks to embrace this vision and since its built on JavaScript, can take advantage of the arms race going on amongst browser vendors in recent years trying to make JavaScript as fast as possible.</p>
<p>Unlike other JavaScript frameworks tackling this domain, it&#8217;s not interpreted at runtime and simply compiles 1:1 with efficient JavaScript (in some cases more efficient than a developer would write).</p>
<p>This gives it some unique qualities where it is able to <a href="http://jashkenas.github.com/coffee-script/">run in a browser</a> without any plugins and thanks to <a href="http://nodejs.org/">node.js</a> the same CoffeeScript code can run very efficiently on servers as well.</p>
<p>We&#8217;re now starting to see this powerfull and expressive combination powering new servers like Ruby&#8217;s new <a href="http://pow.cx/">Pow Rack server</a> for OSX.<br />
Its recent inclusion in the default Rails install is causing the biggest rift I recall in recent times <a href="https://github.com/rails/rails/commit/9f09aeb8273177fc2d09ebdafcc76ee8eb56fe33">for a single line of config change</a>.</p>
<p>So while everyone may not be in love with it yet, they at least have an opinion on it <img src='http://www.servicestack.net/mythz_blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://jashkenas.github.com/coffee-script/">What&#8217;s yours?</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.servicestack.net/mythz_blog/?feed=rss2&amp;p=665</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The App Store bubble: How much does an App earn today?</title>
		<link>http://www.servicestack.net/mythz_blog/?p=572</link>
		<comments>http://www.servicestack.net/mythz_blog/?p=572#comments</comments>
		<pubDate>Wed, 15 Sep 2010 04:37:49 +0000</pubDate>
		<dc:creator>mythz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.servicestack.net/mythz_blog/?p=572</guid>
		<description><![CDATA[The rise and fall of Internet riches Within the last 15 years on the rise of the Internet we have seen many a phenomena gracing technology circles promising great riches to early adopters and investors. It first started out with a gold rush land grab for domain names where in this era a 3-letter domain name [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D572"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D572&amp;source=demisbellot&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<h2>The rise and fall of Internet riches</h2>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/gold_rush.jpeg"><img class="size-full wp-image-579 alignleft" style="margin-left: 5px; margin-right: 5px;" title="gold_rush" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/gold_rush.jpeg" alt="" width="100" height="164" /></a>Within the last 15 years on the rise of the Internet we have seen many a phenomena gracing technology circles promising great riches to early adopters and investors. It first started out with a gold rush land grab for domain names where in this era a 3-letter domain name like <strong>sex.com</strong> was able to earn millions a year just by providing a holding page hosting adult-related advertising banners and was eventually sold for <strong>14M</strong>.  Then came the <a href="http://en.wikipedia.org/wiki/Dot-com_company">dotcom</a> boom where anything Internet related were the most sought after prize on the stock market where traffic and the size of your user base was the hard currency of the day and was rewarded with over-inflated valuations never mind that many had no visible path to profitability. The preferred sport of many startups at the time was who had the highest burn-rate which were fueled by expensive <a href="http://en.wikipedia.org/wiki/Aeron_chair">Aeron chairs</a> and Sparc servers.</p>
<h3>The Bigger <em>They Come</em>, The Harder <em>They Fall</em></h3>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/DotComCrash.png"><img class="size-full wp-image-580 alignright" style="margin-left: 5px; margin-right: 5px;" title="DotComCrash" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/DotComCrash.png" alt="" width="193" height="195" /></a>But just as quick as the riches came to dotcom companies, they vanished again almost entirely within one weekend (which this author remembers quite well as an eager investor on the friday before <a href="http://en.wikipedia.org/wiki/Black_Monday_(1987)">black monday</a>). Eventually the market corrected itself and only businesses with viable business models were the focus of cautious investors whose fingers were still smarting from the <a href="http://en.wikipedia.org/wiki/Dot-com_bubble">bursting of their dotcom</a> investments.</p>
<p>In time faith was restored in the online advertising market spurred largely by Google&#8217;s foray into the area of targeted advertising. Confidence was restored in Internet companies and a smaller bubble is starting to emerge that many casual observers are labelling <a href="http://en.wikipedia.org/wiki/Web_2.0">Web 2.0</a>.</p>
<h2>Cometh the App Store, Cometh the riches again</h2>
<p>Out of the all the events to show up on the technology radar recently, none has been as exciting and show as much promise as the introduction of the <a href="http://en.wikipedia.org/wiki/App_Store">App Store</a> by Apple. With the introduction of their revolutionary smart phone, Apple for the first time put the power of a desktop operating system in the palms of technophiles (with above-average discretionary incomes). Although its potential wasn&#8217;t realized until Apple put the first version of the iPhone SDK in developers hands and opened the much publicized App Store on July 10, 2008. Within months of its introduction stories or riches started to be told of hobbyist programmers earning <a href="http://appadvice.com/appnn/2009/02/ishoot-developer-makes-600000-in-one-month/">$600,000 in just 1-month</a> enough to quit their full-time job to pursue a lucrative career in developing mobile apps for the App store. Soon enough a new economy was created and in pretty short order a growing number of developers made it to the <a href="http://www.zdnet.com/blog/apple/the-app-store-millionaire-club/2649">App store millionaire club</a>. This brings us to where we are today where as of September 1, 2010 there were 250,000 third-party applications with over 6.5 billion total downloads generating its developers over USD $1 billion in revenue.</p>
<h3>The reports of App Stores death are greatly exaggerated</h3>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/ipod1letsrock8.jpeg"><img class="alignright size-full wp-image-581" style="margin-left: 5px; margin-right: 5px;" title="ipod1letsrock8" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/ipod1letsrock8.jpeg" alt="" width="309" height="136" /></a>With now over 250,000 applications available for sale and many of them free many people have chimed in with their opinions some proclaiming the <a href="http://www.fastcompany.com/1684020/the-great-app-bubble">app bubble is bursting</a> and the path to easy riches is over while others maintain the App store maintains a fruitful future. Unfortunately the ubiquity of the Internet has made opinions cheap and plentiful where it looks like anyone with a keyboard can pluck 2 numbers out of the air to show a downward trend.</p>
<h3>An App Store Developers story&#8230;</h3>
<p>As a developer on the App Store I wanted to weigh in on the state of the App store with some empirical evidence of my own as it evolves. My story dates back 18 months ago when it took me <strong>3 weeks to learn</strong> enough Objective-C to submit <a href="http://www.ipockettranslator.com/">my first app</a>. Within a couple of weeks, inspired by the success of <a href="http://en.wikipedia.org/wiki/IFart_Mobile">iFart apps</a> I put aside my morals and pursuit of software excellence and ended up submitting my own <a href="http://www.ipockettranslator.com/worlds-smallest-violin">cookie</a> <a href="http://www.ipockettranslator.com/sad-trombone">cutter</a> <a href="http://www.ipockettranslator.com/instant-rimshot">apps</a>. Although my own fart apps didn&#8217;t do nearly as well as notable others <a href="http://www.ipockettranslator.com/">my translator app</a> earned a noticeable side income where it managed to pay off its development effort many times over. Unfortunately around this time I joined my <a href="http://www.mflow.com">first startup</a> and between the all nighters and 12 hour work days my free time was sapped and my once App making machine days were over. That is until my recent resignation which saw the return of my free time and I was finally able to open xcode again after an 18 month hiatus. After tying up some <a href="http://www.servicestack.net/mythz_blog/?p=344">loose</a> <a href="http://www.servicestack.net/mythz_blog/?p=381">ends</a> on my <a href="http://code.google.com/p/servicestack/">open source project</a> I got to work on a new App.</p>
<h2>How much does an App built today earn?</h2>
<p>So that Non-App developers can get an idea of what they can expect when developing an App today, I&#8217;m going to be completely open and transparent about the development and the financial results of my latest App that has just been approved today (14th Sept UK). I will keep this blog updated with live financial results as I get them.</p>
<h3>Coming up with an idea for an App</h3>
<p><a href="http://itunes.apple.com/us/app/word-mate/id390656966?mt=8"><img class="alignleft size-full wp-image-578" style="margin-left: 10px; margin-right: 10px;" title="Word Mate icon" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/WordMate_175x175-75.jpeg" alt="" width="175" height="175" /></a>Developing a successful app in this age can be a tricky balance to get right where the subject and appeal of your app is every much as important as its features and quality. Because of this, I&#8217;m not a true believer of investing a lot of time in developing an App before I see some ROI. So I&#8217;m always on the lookout for small, quick wins with short development cycles. It just so happen that at the time I was seeking inspiration for my new app, I also spent a large portion of my free time playing <a href="http://itunes.apple.com/us/app/words-with-friends/id322852954?mt=8">Words with friends</a> &#8211; an enjoyable, network-enabled SCRABBLE® clone. Although many would see my poor scrabbling skills the result of a long absence from participating in any academic curriculum, I saw it as an opportunity to build an App to improve my scrabble game! (read: cheat) After a quick sanity check to make sure there weren&#8217;t a hundred free apps already available on the App store that did the same thing: <a href="http://itunes.apple.com/us/app/word-mate/id390656966?mt=8">Word Mate</a> was born &#8211; a collection of word finding utilities that help you play SCRABBLE® like a computer <img src='http://www.servicestack.net/mythz_blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3>Development efforts and total cost</h3>
<p><a href="http://itunes.apple.com/us/app/word-mate/id390656966?mt=8">Word Mate</a> took me roughly a <strong>week full-time to develop</strong> which included downloading all the latest SDK&#8217;s and tools, a bit of reading designed to re-ignite my love with the Objective-C language and its Cocoa inspired frameworks as well as creating all the App and website graphics. As the <a href="http://www.ipockettranslator.com/wordmate">website</a> is freely hosted on <a href="http://code.google.com/appengine/">Google App Engine</a> and the only <a href="http://glyphish.com/">3rd party icons</a> used were free, no costs were incurred into making this app other than the <a href="http://developer.apple.com/programs/ios/">$99/year iOS Developer Program fee</a> and my own time.</p>
<h3>App Store submission process</h3>
<p>Although the language and tools haven&#8217;t improved much, the app submission and code-signing process has improved significantly. When it was first released, code-signing your app so it can be submitted to the App store was considered a black-art which thanks to my careful literal following of every word in an online tutorial caused me to be stuck with the embarrassing title of <em>&#8216;iPhone Developer: Demis Bellot&#8217;</em> for the name of my developer profile. Anyway I submitted my app on the<strong> 1st September </strong>and it was only approved at midnight on the <strong>13th September</strong>. Where the QA staff that Mr Jobs says approves most apps within 7 days are? I don&#8217;t know &#8211; I&#8217;ve never had an any of my apps approved within <strong>2 weeks</strong>.</p>
<p>Regardless today will be my first full day on the App Store market. Like all my apps, <strong>Word Mate</strong> will be free for the first week. I like to do this as it gives a chance for my friends and anyone else who wants one a chance to download my app for free. Making an App for free and then charging for it will also give you an idea of the <strong>Free vs Premium</strong> download ratio. From the experience of my first app the difference was about <strong>6-9%</strong> where for every 100 free apps that were downloaded (when it was free) only 6-9 were paid for (when I started charging USD $0.99 for it). It will be interesting to see if that trends continues with Word Mate.</p>
<h2><a name="results"></a>Live Financial Results</h2>
<p>I&#8217;m going to maintain a <strong>live list</strong> of results on the table below, so you can check back on this post to see how it develops. <a href="http://itunesconnect.apple.com">iTunes Connect</a> (where we login to get our sales reports) doesn&#8217;t publish daily results until 12pm GMT the next day. You can follow <a href="http://twitter.com/demisbellot">@demisbellot</a> on twitter to find out as soon as the latest results have been added.</p>
<table>
<thead>
<tr>
<th>Period Ending</th>
<th>Cost</th>
<th>Qty Sold</th>
<th>Earnings</th>
</tr>
</thead>
<tbody>
<tr>
<td>14th Sept</td>
<td>$0.00</td>
<td>118</td>
<td>$0.00</td>
</tr>
<tr>
<td>15th Sept</td>
<td>$0.00</td>
<td>118</td>
<td>$0.00</td>
</tr>
<tr>
<td>16th Sept</td>
<td>$0.00</td>
<td>41</td>
<td>$0.00</td>
</tr>
<tr>
<td>17th Sept</td>
<td>$0.00</td>
<td>28</td>
<td>$0.00</td>
</tr>
<tr>
<td>18th Sept</td>
<td>$0.00</td>
<td>24</td>
<td>$0.00</td>
</tr>
<tr>
<td>19th Sept</td>
<td>$0.00</td>
<td>21</td>
<td>$0.00</td>
</tr>
<tr>
<td>20th Sept</td>
<td>$0.99</td>
<td>15 free/1</td>
<td>$0.99</td>
</tr>
<tr>
<td>21st Sept</td>
<td>$0.99</td>
<td>1</td>
<td>$0.99</td>
</tr>
<tr>
<td>22nd Sept</td>
<td>$0.99</td>
<td>0</td>
<td>$0.00</td>
</tr>
<tr>
<td>23rd Sept</td>
<td>$0.99</td>
<td>2</td>
<td>$1.98</td>
</tr>
<tr>
<td>20-26th Sept</td>
<td>$0.99</td>
<td>4</td>
<td>$3.96</td>
</tr>
<tr>
<td>27 Sept-3rd Oct</td>
<td>$0.99</td>
<td>5</td>
<td>$4.95</td>
</tr>
<tr>
<td>4th-10th Oct</td>
<td>$0.99</td>
<td>2</td>
<td>$1.98</td>
</tr>
<tr>
<td>11th-17th Oct</td>
<td>$0.99</td>
<td>3</td>
<td>$2.97</td>
</tr>
<tr>
<td>18th-24th Oct</td>
<td>$0.99</td>
<td>2</td>
<td>$1.98</td>
</tr>
<tr>
<td>25th-31st Oct</td>
<td>$0.99</td>
<td>5</td>
<td>$4.95</td>
</tr>
<tr>
<td><strong>1st-28th Nov</strong></td>
<td><strong>$0.99</strong></td>
<td><strong>5</strong></td>
<td><strong>$4.95</strong></td>
</tr>
</tbody>
</table>
<p>*NOTE: <a href="http://itunes.apple.com/us/app/word-mate/id390656966?mt=8">Word Mate</a> will be free until 20 Sept 2010, so if you think you might find this app useful now would be a good time to get it for free <img src='http://www.servicestack.net/mythz_blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3>Follow the conversation</h3>
<p>A discussion thread has started in hacker news which you can get involved in at:</p>
<ul>
<li><a href="http://news.ycombinator.com/item?id=1694752">http://news.ycombinator.com/item?id=1694752</a></li>
</ul>
<p>SCRABBLE® is a registered trademark of Hasbro, Inc. in the United States and Canada, and Mattel, inc. elsewhere. I&#8217;m not affiliated with either company.</p>
<p><strong>Update 23/09/210</strong></p>
<p>It&#8217;s just come to my attention that I may have stuffed up the SEO of my app in the App Store as Word Mate can&#8217;t be found with the words &#8216;Word Finder&#8217; or &#8216;Word Cheat&#8217;  2 of the most popular searches for finding like apps. Unfortunately Apple wont let you change it after you&#8217;ve added it so I&#8217;m going to have to submit a new app. Unfortunately SEO is just as important as having a quality app as if users can&#8217;t find it, they can&#8217;t buy it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.servicestack.net/mythz_blog/?feed=rss2&amp;p=572</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Redis vs RavenDB &#8211; Benchmarks for .NET Client NoSQL Solutions</title>
		<link>http://www.servicestack.net/mythz_blog/?p=474</link>
		<comments>http://www.servicestack.net/mythz_blog/?p=474#comments</comments>
		<pubDate>Wed, 08 Sep 2010 20:20:14 +0000</pubDate>
		<dc:creator>mythz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.servicestack.net/mythz_blog/?p=474</guid>
		<description><![CDATA[These Redis vs RavenDB benchmarks have been made into a bar chart for a better visualization. Seeing that Redis v2.0 has been just been released and Oren Eini (aka @ayende) has just checked in performance optimization improvements that show a 2x speed improvement for raw writes in RavenDB, I thought it was a good time to [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D474"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D474&amp;source=demisbellot&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>These <a href="http://www.servicestack.net/benchmarks/">Redis vs RavenDB benchmarks have been made into a bar chart</a> for a better visualization.</p>
<p>Seeing that <a href="http://code.google.com/p/redis/wiki/Redis_2_0_0_Changelog">Redis v2.0</a> has been just been released and Oren Eini (aka <a href="http://twitter.com/ayende">@ayende</a>) has just <a href="http://ayende.com/Blog/archive/2010/09/08/ravendb-performance-optimizations.aspx">checked in performance optimization improvements</a> that show a <strong>2x</strong> speed improvement for raw writes in RavenDB, I thought it was a good time to do a benchmark pitting these 2 popular NoSQL data stores against each other.</p>
<h3><strong><a name="take2"></a><span style="font-weight: normal;">Benchmarks Take 2 &#8211; Measuring write performance</span></strong></h3>
<p>For the best chance of an Apples to Apples comparison I just copied the RavenDB&#8217;s benchmarks solution project and modified it slightly only to slot in the equivalent Redis operations. The modified solution is <a href="https://github.com/ServiceStack/ServiceStack.Benchmarks/blob/master/src/NoSqlPerformance/NoSqlPerformance.ConsoleApp/Program.cs">available here</a>. Redis was also configured to run in its &#8216;most safest mode&#8217; where it keeps an append only transaction log with the <strong>fsync</strong> option so the operation does not complete until the transaction log entry is written to disk. This is so we can get Redis to closely match RavenDB&#8217;s default behaviour. Enabling this behaviour in Redis is simply a matter of uncommenting the lines below in redis.conf:</p>
<blockquote><p>appendonly yes<br />
appendfsync always</p></blockquote>
<p>To use this new configuration simply run <strong>&#8216;redis-server.exe  /path/to/redis.conf&#8217;</strong> on the command line.<br />
Other changes I made for these new set of benchmarks was to remove batching from the Redis benchmark since its an accidental complexity not required or useful for the Redis Client.</p>
<p>Here are the benchmarks with these new changes in place:<br />
<a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/benchmarks-appendfsync.png"><img class="alignnone size-full wp-image-536" title="benchmarks-appendfsync" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/benchmarks-appendfsync.png" alt="" width="668" height="331" /></a></p>
<p>Which for this scenario show that:</p>
<h2 style="color: #093; padding: 0 5px;">Redis is 11.75x faster than RavenDB</h2>
<p>Note: The benchmarks here are of Redis running on a Windows Server through the Linux API emulation layer - <a href="http://www.cygwin.com/">Cygwin</a>. Expect better results when running Redis on Unix servers where it is actively developed and optimized for. It is understood that the Cygwin version of redis-server is <strong>4-10x</strong> slower than the native Linux version so expect results to be much better in production.</p>
<p>I attribute the large discrepancy between Redis and RavenDB due to the fact that Redis doesn&#8217;t use batches so only pays the &#8216;fsync penalty&#8217; once instead of once per batch.</p>
<p>The &#8216;<strong>appendfsync always</strong>&#8216; mode is not an optimal configuration for a single process since Redis has to block to wait for the transaction log entry to be written to disk, a more sane configuration would be &#8216;<strong>appendfsync everysec</strong>&#8216; which writes to the transaction log asynchronously. Running the same benchmark using the default configuration yields the following results:</p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/benchmarks-no-append.png"><img class="alignnone size-full wp-image-537" title="benchmarks-no-append" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/benchmarks-no-append.png" alt="" width="668" height="331" /></a></p>
<p>Which is a 39% improvement over the previous benchmarks where now:</p>
<h2 style="color: #093; padding: 0 5px;">Redis is 16.9x faster than RavenDB</h2>
<p>Which unless I hear otherwise? should make this the fastest NoSQL solution available for .NET or MONO clients.</p>
<p>Measuring raw write performance using Redis is a little unfair since it has a batchful operation <a href="http://code.google.com/p/redis/wiki/MsetCommand">MSET</a> specifically optimized for this task. But that is just good practice, whenever you cross a process boundary you should be batching requests to minimize the number of your calls minimizing latency and maximizing performance.</p>
<p>Even though performance is important, its not the only metric when deciding which NoSQL database to use. If you have a lot of querying and reporting requirements that you don&#8217;t know up front then a document database like <a href="http://ravendb.net/">RavenDB</a>, <a href="http://www.mongodb.org/">MongoDB</a> or <a href="http://couchdb.apache.org/">CouchDB</a> is a better choice. Likewise if you have minimal querying requirements and performance is important than you would be better suited to using <a href="http://code.google.com/p/redis/">Redis</a> &#8211; either way having a healthy array of vibrant choices available benefits everybody.</p>
<h3>Notes about these benchmarks</h3>
<p>Since these benchmarks just writes entities in large batches to a local Redis or RavenDB instance using a single client, I don&#8217;t consider this to be indicative of a *real-world* test rather a measure is raw write performance, i.e. How fast each client can persist 5,163 entities in their respective datastore.</p>
<p>A better *real-world* test would be one that accesses the server over the network using multiple concurrent clients that were benchmarking typical usage of a real-world application rather than just raw writes as done here.</p>
<h3><span style="font-weight: normal;">So why is Redis so fast?</span></h3>
<p>Based on the comments below there appears to be some confusion as to what Redis is and how it works. Redis is a high-performance data structures server written in C that operates predominantly in-memory and routinely persists to disk and maintains an Append-only transaction log file for data integrity &#8211; both of which are configurable.</p>
<p>For redundancy each instance has built-in support for replication so you can turn any redis instance into a slave of another, which can also be trivially configured at runtime. It also features its own Virtual Machine implementation so if your dataset exceeds your available memory, un-frequented values are swapped out to disk whilst the hot values remain in memory.</p>
<p>Like other high-performance network servers e.g. <a href="http://wiki.nginx.org/Main">Nginx</a> (the worlds fastest HTTP server), <a href="http://nodejs.org/">Node.js</a> (a popular, very efficient web framework for JavaScript), <a href="http://memcached.org/">Memcached</a>, etc it achieves maximum efficiency by having each Redis instance run in a single process where all IO is asynchronous and no time is wasted context-switching between threads. To learn more about this architecture, check out Douglas Crockford (of JavaScript and JSON fame) imformative speech <a href="http://www.yuiblog.com/blog/2010/08/30/yui-theater-douglas-crockford-crockford-on-javascript-scene-6-loopage-52-min/">comparing event-loops vs threading</a> for simulating concurrency.</p>
<p>It achieves concurrency by being really fast and achieves integrity by having all operations atomic. You are not just limited to the available transactions either as you can compose any combination of Redis commands together and process them atomically in a single transaction.</p>
<p>Effectively if you wanted to create the fastest NoSQL data store possible you would design it just like Redis and Memcached. Big kudos to <a href="http://twitter.com/antirez">@antirez</a> for his continued relentless pursuit of optimizations resulting in Redis&#8217;s stellar performance.</p>
<h4>The Redis Client,  JSON and the Redis Admin UI</h4>
<p>Behind the scenes the Redis Client automatically stores the entities as JSON string values in Redis. Thanks to the ubiquitous nature of JSON I was easily able to develop a <a href="http://www.servicestack.net/mythz_blog/?p=381">Redis Admin UI</a> which provides a quick way to navigate and introspect your data in Redis. The Redis Admin UI runs on both .NET and Linux using Mono &#8211; A live demo is <a href="http://www.servicestack.net/RedisAdminUI/AjaxClient/#">available here</a>.</p>
<h2>Download Benchmarks</h2>
<p>The benchmarks (minus the dependencies) are available in <a href="https://github.com/ServiceStack/ServiceStack.Benchmarks/blob/master/src/NoSqlPerformance/">ServiceStack&#8217;s svn repo</a>.</p>
<p>I also have a complete download with including all dependencies available here:<br />
<strong><a href="http://servicestack.googlecode.com/files/NoSqlPerformance.zip">http://servicestack.googlecode.com/files/NoSqlPerformance.zip</a> (18MB)</strong></p>
<h2>Gaining in Popularity</h2>
<p>Redis is sponsored by VMWare and has a vibrant pro-community behind it and been gaining a lot of popularity lately. Already with a library for <a href="http://code.google.com/p/redis/wiki/SupportedLanguages">every popular language in active use today</a>, it is gaining momentum outside its Linux roots with <a href="http://twitter.com/antirez/status/24223669996">twitter now starting to make use of it</a> as well as popular .NET shops like the <a href="http://twitter.com/codinghorror/status/22417440038">StackOverflow team taking advantage of it</a>.</p>
<p>Unlike <a href="http://ravendb.net/">RavenDB</a> and <a href="http://www.mongodb.org/">MongoDB</a> which are document-orientated data stores, <a href="http://code.google.com/p/redis/">Redis</a> is a <strong>&#8216;data structures&#8217;</strong> server which although lacks some of the native querying functionalities found in Document DBs, encourage you to leverage its comp-sci data structures to maintain your own custom indexes to satisfy all your querying needs.</p>
<h2>Try Redis in .NET</h2>
<p>If these results have piqued your interest in Redis I invite you to try it out. If you don&#8217;t have a linux server handy, you can still get started by trying one of the <a href="http://code.google.com/p/servicestack/wiki/RedisWindowsDownload">windows server builds</a>.</p>
<p>Included with ServiceStack is a <a href="https://github.com/ServiceStack/ServiceStack.Redis">feature-rich C# client</a> which provides a familiar and easy to use C# API which like the rest of Service Stack runs on .NET and Linux with Mono.</p>
<h4>Useful resources for using the C# .NET Client</h4>
<p>I also have some useful documentation to help you get started:<br />
- <a href="https://github.com/ServiceStack/ServiceStack.Redis/wiki/DesigningNoSqlDatabase">Designing a NoSQL Database using Redis</a><br />
+ <a href="https://github.com/ServiceStack/ServiceStack.Redis/blob/master/tests/ServiceStack.Redis.Tests/Examples/BestPractice/BlogPostBestPractice.cs">A refactored example showing how to use Redis behind a repository pattern</a><br />
- <a href="https://github.com/ServiceStack/ServiceStack.Redis/wiki/MigrationsUsingSchemalessNoSql">Painless data migrations with schema-less NoSQL datastores and Redis</a><br />
- <a href="https://github.com/ServiceStack/ServiceStack.Redis/wiki/RedisTransactions">How to create custom atomic operations in Redis</a><br />
- <a href="https://github.com/ServiceStack/ServiceStack.Redis/wiki/RedisPubSub">Publish/Subscribe messaging pattern in Redis</a><br />
- <a href="https://github.com/ServiceStack/ServiceStack.Redis/wiki/RedisLocks">Achieving High Performance, Distributed Locking with Redis</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.servicestack.net/mythz_blog/?feed=rss2&amp;p=474</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>How to host an HTTP + Web Services server in an iPhone with MonoTouch</title>
		<link>http://www.servicestack.net/mythz_blog/?p=417</link>
		<comments>http://www.servicestack.net/mythz_blog/?p=417#comments</comments>
		<pubDate>Tue, 07 Sep 2010 21:31:31 +0000</pubDate>
		<dc:creator>mythz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.servicestack.net/mythz_blog/?p=417</guid>
		<description><![CDATA[Yep the title of this post is correct! With a little hacking to get around MonoTouch Limitations I&#8217;ve managed to shoe-horn Service Stack&#8217;s HttpListener and host it inside of an iPhone with the help of MonoTouch. Basically, in not so many words I made this happen: Basically the above is the result of hosting a [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D417"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D417&amp;source=demisbellot&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Yep the title of this post is correct! With a little hacking to get around <a href="http://monotouch.net/Documentation/Limitations">MonoTouch Limitations</a> I&#8217;ve managed to shoe-horn Service Stack&#8217;s HttpListener and host it inside of an iPhone with the help of <a href="http://monotouch.net/">MonoTouch</a>. Basically, in not so many words I made this happen:</p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/EmbeddedWebPage-large.png"><img class="alignnone size-full wp-image-418" title="HttpJsonWebServices" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/HttpJsonWebServices.png" alt="" width="477" height="467" /></a></p>
<p>Basically the above is the result of hosting a web server on your iPhone making it possible to view your iPhone content with any web browser. In a addition to a static HTTP server there is also an Embedded version of <a href="http://www.servicestack.net/">Service Stack</a> turning your iPhone into a Web Services server. This happens to be a pretty convenient way to get at your data. As a basic example I created a simple Web Service returning all the contacts in your iPhone Address book:</p>
<pre class="brush: csharp; title: ;">
namespace EmbeddedServiceStack
{
	public class ContactsService : IService&lt;Contacts&gt;
	{
		//Singleton defined in AppHost, Injected by Funq IOC
		public ABAddressBook AddressBook { get; set; }

		public object Execute (Contacts request)
		{
			var response = new ContactsResponse();

			foreach(var person in AddressBook.GetPeople())
			{
				var emails = person.GetEmails().GetValues();
				response.Contacts.Add(new Contact {
					FirstName = person.FirstName,
					LastName = person.LastName,
					Email = emails.Length &gt; 0 ? emails[0] : null,
				});
			}

			return response;
		}
	}
}
</pre>
<p>Which once you start the AppHost&#8217;s HttpListener lets you view your data using REST-ful  HTTP requests like so:</p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/JsonXmlResults.png"><img class="alignnone size-full wp-image-420" title="JsonXmlResults" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/JsonXmlResults.png" alt="" width="598" height="480" /></a></p>
<p>Some of you might be thinking WTF dude why the hell would you want to do this to an iPhone?? Actually I did for a while too! However in a <a href="http://lists.ximian.com/pipermail/monotouch/2010-August/002101.html">recent thread on the mailing list</a> Miguel De Icaza actually identified some <a href="http://tirania.org/blog/archive/2005/Nov-27-1.html">useful use cases where this might be a good idea</a>.</p>
<p>For one reason you can sprinkle a little JavaScript in your HTML page to display the list of Contacts below:</p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/AjaxResultsOutput.png"><img class="alignnone size-full wp-image-421" title="AjaxResultsOutput" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/AjaxResultsOutput.png" alt="" width="632" height="228" /></a></p>
<p>Which granted doesn&#8217;t look like much however this task is infinitely less tedious with JavaScript.</p>
<p>Having thought about for a little more I can think of a few more potential use-cases:</p>
<ul>
<li>Giving you more flexibility to access and export your iPhone&#8217;s data without needing to use iTunes</li>
<li>Develop PhoneGap-like iPhone apps without PhoneGap <img src='http://www.servicestack.net/mythz_blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </li>
<li>Use a full-featured desktop browser to view your iPhone data rather than it&#8217;s constrained mobile interface</li>
<li>Access your iPhone from over the Internet (allowing async callback duplex requests)</li>
<li>Provide easy 2-way communication between iPhone Apps</li>
</ul>
<p>Other potential use-cases heard on the tweet vine:</p>
<ul>
<li>Mobile device management (Landesk like) and Software testing (<a href="http://twitter.com/itdnext">@itdnext</a>)</li>
</ul>
<h2><strong>Developer Notes</strong></h2>
<h3><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/MonoTouch-Solution.png"><img class="alignleft size-full wp-image-438" style="margin: 0 10px 5px 0px;" title="MonoTouch-Solution" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/MonoTouch-Solution.png" alt="" width="285" height="291" /></a>How the Web Server works?</h3>
<p>Basically any url with a Web Service prefix is interpreted as a Web Service and delegated to Service Stack to process.</p>
<p>
http://localhost:8080/<strong>Xml/</strong><br />
http://localhost:8080/<strong>Json/</strong><br />
http://localhost:8080/<strong>Jsv/</strong>
</p>
<p>All other urls are treated like a standard HTTP GET request where it looks for a matching file in the Projects <strong>www/</strong> resource directory and simply copies it to the Response Output Stream. Requests that ends with a &#8216;/&#8217; (i.e. a directory path)  are treated like &#8216;/default.html&#8217;</p>
<p>Note: In order to have your static files packaged and deployed with your application you need to set the <a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/BuildActionContent.png">&#8216;Build Action&#8217; to &#8216;Content&#8217;</a> for each file.<br />
Also if you don&#8217;t see any contacts you need to use the Contact App in the iPhone simulator and add some in yourself.</p>
<h3 style="clear: left;">MonoTouch Quirks</h3>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/09/BuildActionContent.png"></a></p>
<p>Since I found the JsonDataContractSerializer in Mono to be unreliable I&#8217;ve had to write and included my own <a href="http://www.servicestack.net/mythz_blog/?p=344">Json Serializer</a> whose heavily reliance on generics requires some extra attention when running in an <strong>No JIT</strong> environment like MonoTouch. Basically we have to tell the MonoTouch compiler what concrete generic classes to generate &#8211; which we do by Registering all DTO&#8217;s like so:</p>
<pre class="brush: csharp; title: ;">
private void RegisterDtoTypes_RequiredWhenTheresNoJit()
{
	Register.Type&lt;Hello&gt;();
	Register.Type&lt;HelloResponse&gt;();
	Register.Type&lt;Contacts&gt;();
	Register.Type&lt;ContactsResponse&gt;();
	Register.Type&lt;Contact&gt;();
}
</pre>
<h2>Download the Example project</h2>
<div id="_mcePaste">For those interested, the above sample project and all the Embedded ServiceStack libraries required to build your own iPhone HTTP+Webservices solution is available at:</div>
<p><a href="http://servicestack.googlecode.com/files/MonoTouch-EmbeddedServiceStack.zip"><strong><span style="color: #0000ff;">http://servicestack.googlecode.com/files/MonoTouch-EmbeddedServiceStack.zip</span></strong></a></p>
<p>Since I only have the trial version of MonoTouch I have only been able to verify that this works in the iPhone Simulator. So if anyone with the full version of MonoTouch gets this running on an iOS device &#8211; can you let me know. Feel free to file any issues you run into at the projects website: <a href="https://github.com/ServiceStack/MonoTouch.Examples/issues">http://code.google.com/p/servicestack/issues/list</a></p>
<p>Happy Hacking!</p>
<h3>Further Reading</h3>
<p>A tutorial showing you how to create and call web services from MonoTouch is available here:<br />
<a href="http://www.servicestack.net/monotouch/remote-info/">http://www.servicestack.net/monotouch/remote-info/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.servicestack.net/mythz_blog/?feed=rss2&amp;p=417</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing the Redis Admin UI</title>
		<link>http://www.servicestack.net/mythz_blog/?p=381</link>
		<comments>http://www.servicestack.net/mythz_blog/?p=381#comments</comments>
		<pubDate>Thu, 26 Aug 2010 11:22:54 +0000</pubDate>
		<dc:creator>mythz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.servicestack.net/mythz_blog/?p=381</guid>
		<description><![CDATA[Confident that I&#8217;ve optimized ServiceStack&#8217;s JSON web services performance enough with the adoption of my latest efforts developing .NET&#8217;s fastest JSON Serializer, I&#8217;m now turning my attention towards creating apps that take advantage of it. I&#8217;m a firm believer that performance is one of, if not the most important feature in developing an App that most [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D381"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.servicestack.net%2Fmythz_blog%2F%3Fp%3D381&amp;source=demisbellot&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/03/redis.png"><img class="alignleft size-full wp-image-128" style="margin-left: 5px; margin-right: 5px;" title="redis.png" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/03/redis.png" alt="" width="112" height="86" /></a>Confident that I&#8217;ve optimized ServiceStack&#8217;s JSON web services performance enough with the adoption of my latest efforts developing <a href="http://www.servicestack.net/mythz_blog/?p=344">.NET&#8217;s fastest JSON Serializer</a>, I&#8217;m now turning my attention towards creating apps that take advantage of it.</p>
<p>I&#8217;m a firm believer that performance is one of, if not <strong>the most important feature</strong> in developing an App that most users will love and use on a regular basis.  It&#8217;s the common trait amongst all the apps and websites I regularly use and is why I&#8217;m continually seeking software components and/or techniques that can help make my software run faster; or whenever there is no alternative to develop them myself. Although having said this I&#8217;m not a complete perf maniac and find that its important to strike a balance between productivity, utility and performance &#8211; which is what has effectively kept me tied to C# language for all my server development.</p>
<p><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/03/nosql_thumb.gif"><img class="alignright size-full wp-image-126" title="nosql_thumb.gif" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/03/nosql_thumb.gif" alt="" width="180" height="120" /></a></p>
<h3>Redis, Sweet Redis</h3>
<p>One of the exciting movements that have occurred in recent times is the introduction of NoSQL suite of data persistence solutions. There are numerous impressive NoSQL solutions out there but the one that I have been most interested in is <strong>Redis</strong> which from the <a href="http://code.google.com/p/redis/">projects website</a>:</p>
<blockquote><p>is an advanced key-value store. It is similar to memcached but the dataset is not volatile, and values can be strings, exactly like in memcached, but also lists, sets, and ordered sets. All this data types can be manipulated with atomic operations to push/pop elements, add/remove elements, perform server side union, intersection, difference between sets, and so forth.</p></blockquote>
<p>I found this fascinating since it provides an extremely fast data-store (that gets routinely persisted) supporting rich data-structures that can be safely accessed by multiple app servers concurrently since all operations are atomic. Sweet just what I always wanted &#8211; although to make it productive I developed a <a href="https://github.com/mythz/ServiceStack.Redis">C# Redis Client</a> that apart from supporting Redis&#8217;s entire feature-set also provides a <a href="https://github.com/mythz/ServiceStack.Redis/wiki/IRedisTypedClient">high-level typed API</a> that can persist any <a href="https://github.com/mythz/ServiceStack.Redis/wiki/DesigningNoSqlDatabase">.NET POCO Type</a> which gets persisted as JSON in Redis.</p>
<h2>The Redis Admin UI</h2>
<p>One of the disadvantages that comes with making use of a shiny new tech is that there is sometimes not a lot of tooling available for it. Despite its <a href="http://groups.google.com/group/redis-db">vibrant community</a> this is also true for Redis where although it sports a rich command-line interface (Unix software is good like this) the GUI admin tools are somewhat lacking. Not to worry, I actually needed a project to work on to learn about <a href="http://code.google.com/closure/library/">Google&#8217;s closure-library</a> anyway so this ended up being a pretty good fit.</p>
<h3>Screenshots</h3>
<p>Before we get into more detail its probably a good idea to showcase some of screenshots of where its currently at:<br />
Note: You can also try it out live: <a href="http://www.servicestack.net/RedisAdminUI/AjaxClient/">http://www.servicestack.net/RedisAdminUI/AjaxClient/</a></p>
<div id="attachment_399" class="wp-caption alignnone" style="width: 512px"><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/08/Admin_Tab.png"><img class="size-full wp-image-399 " style="border: 0px initial initial;" title="Admin Tab" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/08/Admin_Tab.png" alt="" width="502" height="420" /></a><p class="wp-caption-text">Admin tab showing redis instance info</p></div>
<div id="attachment_400" class="wp-caption alignnone" style="width: 512px"><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/08/View_Key_Group.png"><img class="size-full wp-image-400" title="View Key Group" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/08/View_Key_Group.png" alt="" width="502" height="420" /></a><p class="wp-caption-text">Aggregate view of complex types</p></div>
<div id="attachment_401" class="wp-caption alignnone" style="width: 512px"><a href="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/08/View_Complex_Type.png"><img class="size-full wp-image-401 " title="View Complex Type" src="http://www.servicestack.net/mythz_blog/wp-content/uploads/2010/08/View_Complex_Type.png" alt="" width="502" height="420" /></a><p class="wp-caption-text">View single complex type</p></div>
<h3>Redis Web Services</h3>
<p>In order to be able to access Redis from a web page some JSON web services are in order. I could&#8217;ve just implemented the services required by the Admin UI although I wanted to flex some <a href="http://www.servicestack.net">ServiceStack</a> muscle so decided to create web services for all of Redis&#8217;s operations which on final count totalled near <strong>100</strong> web services that I ended up knocking out over a single weekend. One of the benefits of using ServiceStack to develop your web services is that you get SOAP, XML, JSON and JSV endpoints for free. So after spending the next couple of days creating unit tests to provide 100% coverage, the back-end was complete &#8211; thus giving Redis CouchDB-like powers by allowing it to be accessed from any HTTP client.</p>
<p>Those interested in the Redis Web Services component can check out a live preview &#8211; with the complete list of available web services are available here:</p>
<p><a href="http://www.servicestack.net/RedisAdminUI/Public/Metadata">http://www.servicestack.net/RedisAdminUI/Public/Metadata</a></p>
<p>And some examples on how to call them:</p>
<div id="_mcePaste"><a href="http://www.servicestack.net/RedisAdminUI/Public/Json/SyncReply/GetServerInfo">http://www.servicestack.net/RedisAdminUI/Public/Json/SyncReply/GetServerInfo</a> (JSON)</div>
<div id="_mcePaste"><a href="http://www.servicestack.net/RedisAdminUI/Public/Xml/SyncReply/SearchKeys?Pattern=urn:c*">http://www.servicestack.net/RedisAdminUI/Public/Xml/SyncReply/SearchKeys?Pattern=urn:c*</a> (XML)</div>
<h3>Ajax UI</h3>
<div>With the web services in place, it is now possible to build pure static html/js/css ajax apps talking directly to the servers&#8217; JSON data services &#8211; with no other web framework required!</div>
<div>The closure-library although not as terse or as initially productive as jQuery really shines in building large applications. It has a good framework for developing and re-using JavaScript classes and modules and comes with a set of rich, well-tested, cross-browser-compatible widgets. So within a couple of weeks of hacking on the client I was able to churn out a fairly useful featureset:</div>
<div>
<ul>
<li>A TreeView displaying a heirachal view of the filtered redis keyset</li>
<li>Deep linking support so you can refresh, save or send a link of the entry you&#8217;re looking at</li>
<li>Back and forward button support</li>
<li>A tabular, aggregate view of all your &#8216;grouped keys&#8217;</li>
<li>An auto-complete filter to filter the tabular data</li>
<li>Updating and deleting of string values</li>
<li>Identifying the type, viewing and deleting of all keys</li>
<li>An admin interface to view redis server stats and the ability to destroy and rebuild the entire redis instance</li>
</ul>
</div>
<h4>Restrictions and Assumptions</h4>
<p>In order to provide a useful Generic UI I&#8217;ve had to make a few assumptions on conventions used. Coincidentally these also happen to be the same conventions that the <a href="https://github.com/mythz/ServiceStack.Redis">ServiceStack&#8217;s C# Redis Client</a> uses when storing data <img src='http://www.servicestack.net/mythz_blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<ol>
<li>Keys parts should be separated with a &#8216;:&#8217;</li>
<li>Keys within the same group are expected to be of the same type</li>
<li>Complex types are stored as JSON</li>
</ol>
<p>There are likely to be others I&#8217;ve subconsciously used so I&#8217;ll make an effort to keep this list of assumptions live.</p>
<h2>Download and installation</h2>
<p>Like the rest of ServiceStack the Redis Admin UI is Open source released under the liberal <a href="http://www.opensource.org/licenses/bsd-license.php">new BSD licence</a>.</p>
<p>In keeping with tradition with most of my software, the Redis Admin UI works cross-platform on Windows with .NET and Linux and OSX using <a href="http://www.mono-project.com/Main_Page">Mono</a> (Live demo is hosted on CentOS/Nginx).<br />
I&#8217;ve had an attempt at some basic installation instructions that are included in the downloaded and <a href="https://github.com/mythz/ServiceStack.RedisWebServices/blob/master/src/RedisWebServices.Host/INSTALL.txt">viewable online</a>.</p>
<p>The latest version is hosted on Service Stacks code project site at the following url:</p>
<p><a href="https://github.com/downloads/mythz/ServiceStack.RedisWebServices/RedisAdminUI.zip"><strong><span style="color: #0000ff;">https://github.com/downloads/mythz/ServiceStack.RedisWebServices/RedisAdminUI.zip</span></strong></a></p>
<p>The Admin UI is highly customizable and very hackable since its written all in Java Script, so if you are interested in customizing the UI for your own purposes I invite you get started by downloading the <a href="https://github.com/mythz/ServiceStack.RedisWebServices">development version</a> from svn trunk.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.servicestack.net/mythz_blog/?feed=rss2&amp;p=381</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

