<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Ducas' World</title>
	<atom:link href="http://blog.duc.as/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.duc.as</link>
	<description>This weblog is my life in a nutshell</description>
	<lastBuildDate>Mon, 07 Jan 2013 21:47:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.duc.as' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Ducas' World</title>
		<link>http://blog.duc.as</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.duc.as/osd.xml" title="Ducas&#039; World" />
	<atom:link rel='hub' href='http://blog.duc.as/?pushpress=hub'/>
		<item>
		<title>A Raspberry Pi Build Light for TeamCity in Mono</title>
		<link>http://blog.duc.as/2012/09/20/a-raspberry-pi-build-light-for-teamcity-in-mono/</link>
		<comments>http://blog.duc.as/2012/09/20/a-raspberry-pi-build-light-for-teamcity-in-mono/#comments</comments>
		<pubDate>Thu, 20 Sep 2012 01:21:42 +0000</pubDate>
		<dc:creator>ducas</dc:creator>
				<category><![CDATA[Dev Stuff]]></category>

		<guid isPermaLink="false">http://blog.duc.as/?p=286</guid>
		<description><![CDATA[Some Background… After I bought my Raspberry Pi I went through a little period of uncertainty that most other owners have, asking myself “how do I make this thing useful?” It didn’t take long before one of my colleagues created a GitHub repository for a little project that had been sitting around for a while [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=286&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h2>Some Background…</h2>
<p>After I bought my Raspberry Pi I went through a little period of uncertainty that most other owners have, asking myself “how do I make this thing useful?” It didn’t take long before one of my colleagues created a GitHub repository for a little project that had been sitting around for a while &#8211; <a href="https://github.com/Readify/TeamFlash">TeamFlash</a>.</p>
<p>TeamFlash is a build light client app for TeamCity. It monitors the build server to find the status of the latest build and flashes a light in a different colour depending on that status. Having a little bit of electronics know-how, I wanted to see if I could make my Raspberry Pi into a standalone build light.</p>
<p>First up, I knew there had to be someone that’s interfaced with the GPIO ports. Within a few seconds of deciding to search I stumbled upon the <a href="http://elinux.org/RPi_Low-level_peripherals">RPi Low-level peripherals</a> page. This has a sample of driving the GPIO using C# linking to the <a href="https://github.com/cypherkey/RaspberryPi.Net/">RaspberryPi.Net GitHub repository</a>. It has one moving part – <a href="http://www.open.com.au/mikem/bcm2835/index.html">Mike McCauley’s BCM2835 library</a>. Brilliant! Now to get it working…</p>
<h2>Getting Started</h2>
<p>The RapsberryPi.Net README has instructions on <a href="https://github.com/cypherkey/RaspberryPi.Net/#using-gpiomem">how to compile the BCM2835 library</a> into a statically linked library named <strong>libbcm2835.so</strong>. To use GPIO from Mono I simply:</p>
<ol>
<li>Compiled the BCM2835 library</li>
<li>Compiled the RaspberryPi.Net project</li>
<li>Took the output of both and added them to my Dependencies folder</li>
<li>Added <strong>RaspberryPi.Net.dll</strong> to my project as a reference</li>
<li>Added <strong>libbcm2835.so</strong> to my project as a linked file and changed its build action to <strong>Copy if newer</strong></li>
</ol>
<p>Now I can write code like:</p>
<p><pre class="brush: csharp;">
var led = new GPIOMem(GPIO.GPIOPins.GPIO01);
led.Write(true);
Thread.Sleep(1000);
led.Write(false);
</pre></p>
<h2>Running TeamFlash on YOUR Pi</h2>
<p>Here’s how you can get TeamFlash working on your Raspberry Pi.</p>
<h3>Step 1 – Wiring it up</h3>
<p>I’ve got some standard LEDs from an old Arduino kit, so I’ve hooked each of those in serial with a 330 Ohm resistor to ensure the forward current is within the correct range.</p>
<p><a href="http://ducas.files.wordpress.com/2012/09/rpi_teamflash_fritzing_visual.jpg"><img class="alignnone size-full wp-image-289" title="Raspberry Pi TeamFlash Fritzing Visual" src="http://ducas.files.wordpress.com/2012/09/rpi_teamflash_fritzing_visual.jpg?w=604" alt="Raspberry Pi TeamFlash Fritzing Visual"   /></a><a href="http://ducas.files.wordpress.com/2012/09/rpi_teamflash_fritzing_schematic.jpg"><img class="alignnone size-full wp-image-288" title="Raspberry Pi TeamFlash Fritzing Schematic" src="http://ducas.files.wordpress.com/2012/09/rpi_teamflash_fritzing_schematic.jpg?w=604" alt="Raspberry Pi TeamFlash Fritzing Schematic"   /></a></p>
<h3>Step 2 – Boot Raspbian</h3>
<p>Go to <a href="http://www.raspberrypi.org/downloads">http://www.raspberrypi.org/downloads</a> and get the latest release of Raspbian. Follow the instructions and get it up and running.</p>
<h3>Step 3 – Install the Required Components</h3>
<p>To get it all going you’ll need to install mono. If you want to build it on the Pi, install git and mono-complete:</p>
<p><pre class="brush: bash;">
sudo apt-get install git
sudo apt-get install mono-complete
</pre></p>
<p>Otherwise the mono-runtime will suffice:</p>
<p><pre class="brush: bash;">
sudo apt-get install mono-runtime
</pre></p>
<h3>Step 4 – Get TeamFlash</h3>
<p>Again, if you want to compile the app on the Pi:</p>
<p><pre class="brush: bash;">
git clone https://github.com/ducas/TeamFlash.git
cd TeamFlash
xbuild
</pre></p>
<p>Otherwise you can clone the repository and compile it on your desktop/laptop and just move the output (contents of TeamFlash/bin/Debug) around on a USB key.</p>
<h3>Step 6 – Configure TeamFlash</h3>
<p>Edit the serverUrl, username and password values in <strong>TeamFlash.exe.config</strong> (in the output directory of the build – TeamFlash/bin/Debug). If you’re looking for an easy way to do this on the Pi, try using nano:</p>
<p><pre class="brush: bash;">
nano TeamFlash.exe.config
</pre></p>
<p>When using nano, simply change the appropriate values and hit Ctrl + X to exit &#8211; you will be prompted to save.</p>
<h3>Step 7 – Run TeamFlash</h3>
<p><pre class="brush: bash;">
sudo mono TeamFlash.exe
</pre></p>
<h3>Step 8 – Profit!</h3>
<p>And that’s it! When your build is:</p>
<ol>
<li>Good – the green light will stay lit</li>
<li>Broken – the red light will flash on and off</li>
<li>Investigating – the red and yellow lights will flash sequentially</li>
</ol>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ducas.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ducas.wordpress.com/286/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=286&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.duc.as/2012/09/20/a-raspberry-pi-build-light-for-teamcity-in-mono/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3f24b4673f800e38ec198a6289901b1d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ducas</media:title>
		</media:content>

		<media:content url="http://ducas.files.wordpress.com/2012/09/rpi_teamflash_fritzing_visual.jpg" medium="image">
			<media:title type="html">Raspberry Pi TeamFlash Fritzing Visual</media:title>
		</media:content>

		<media:content url="http://ducas.files.wordpress.com/2012/09/rpi_teamflash_fritzing_schematic.jpg" medium="image">
			<media:title type="html">Raspberry Pi TeamFlash Fritzing Schematic</media:title>
		</media:content>
	</item>
		<item>
		<title>Unit Testing and the .NET Micro Framework</title>
		<link>http://blog.duc.as/2012/04/05/unit-testing-and-the-net-micro-framework/</link>
		<comments>http://blog.duc.as/2012/04/05/unit-testing-and-the-net-micro-framework/#comments</comments>
		<pubDate>Thu, 05 Apr 2012 01:11:40 +0000</pubDate>
		<dc:creator>ducas</dc:creator>
				<category><![CDATA[.NET Micro Framework]]></category>
		<category><![CDATA[Dev Stuff]]></category>
		<category><![CDATA[mfunit]]></category>
		<category><![CDATA[netmf]]></category>

		<guid isPermaLink="false">https://ducas.wordpress.com/?p=272</guid>
		<description><![CDATA[Recently I decided to take up a new hobby… writing code for small things. So, being a .NET developer, I decided the easiest way to crack this nut is to use .NET Micro Framework (or NETMF). Getting started with NETMF is fairly easy for a .NET developer. You go to www.netmf.com, download and install the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=272&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Recently I decided to take up a new hobby… writing code for small things. So, being a .NET developer, I decided the easiest way to crack this nut is to use .NET Micro Framework (or NETMF).</p>
<p>Getting started with NETMF is fairly easy for a .NET developer. You go to <a href="http://www.netmf.com">www.netmf.com</a>, download and install the SDK and you create new projects using the new templates.</p>
<p>One thing that’s missing from NETMF is the ability to unit test your projects. Because the core is not the same as the desktop core there are no unit testing tools. Searching a bit I found a few people using some patchy solutions involving referencing code files in regular unit testing projects. While this may work for some, I don’t believe it’s the most accurate test as the framework implementations are rather different. This drew me to creating my own solution…</p>
<h2>Introducing MFUnit!</h2>
<p>MFUnit is a simple .NET Micro Framework Unit Testing Library. It uses convention based discovery to find and run your tests.</p>
<h3>Open Source</h3>
<p>MFUnit is open source &#8211; <a href="https://github.com/ducas/MFUnit">https://github.com/ducas/MFUnit</a>. Check it out! You’ll find a readme page with more detailed information and source code, including a test project that uses MFUnit to test the Assert class.</p>
<h3>Installation</h3>
<p>1. Create a NETMF Console Project</p>
<p>2. …</p>
<p><a href="http://nuget.org/packages/MFUnit" target="_blank"><img style="background-image:none;padding-left:0;padding-right:0;padding-top:0;border-width:0;" title="Install-Package MFUnit" border="0" alt="Install-Package MFUnit" src="http://ducas.files.wordpress.com/2012/04/image.png?w=359&#038;h=70" width="359" height="70"></a></p>
<p>3. Profit!</p>
<p>Installing this package will create a class named TestProgram. Simply delete Program.cs, write your tests and you’re on your way.</p>
<h3>Conventions</h3>
<ol>
<li>Test fixtures/classes must end with <strong>Tests</strong>
<li>Test methods (or facts) must be <strong>public void </strong>methods</li>
</ol>
<h3>Asserting</h3>
<p>MFUnit comes with an Assert library that supports the following methods:</p>
<ul>
<li>Fail
<li>AreEqual
<li>IsTrue
<li>IsFalse
<li>IsNull
<li>IsNotNull
<li>Throws</li>
</ul>
<h3>Example</h3>
<p>The following class will be discovered by the test runner and the methods will be executed.</p>
<p><pre class="brush: csharp;">
public class AssertTests
{
    public void AssertIsNull_ShouldPass_WhenActualIsNull()
    {
        Assert.IsNull(null);
    }

    public void AssertIsNull_ShouldFail_WhenActualIsNotNull()
    {
        Assert.IsNull(1);
    }
}
</pre></p>
<p>The first method will pass, but the second will fail. The Output Debug window will contain the following text:</p>
<pre>PASS AssertTests.AssertIsNull_ShouldFail_WhenActualIsNull
    #### Exception MFUnit.AssertException - 0x00000000 (3) ####
    #### Message: Expected: "null", Actual: "not null".
    #### MFUnit.Assert::Fail [IP: 0005] ####
    #### MFUnit.Assert::IsNull [IP: 000f] ####
    #### MFUnit.Tests.AssertTests::AssertIsNull_ShouldPass_WhenActualIsNull [IP: 0008] ####
    #### System.Reflection.MethodBase::Invoke [IP: 0000] ####
    #### MFUnit.TestRun::Execute [IP: 00b6] ####
A first chance exception of type 'MFUnit.AssertException' occurred in MFUnit.dll
FAIL AssertTests.AssertIsNull_ShouldPass_WhenActualIsNotNull: Expected: "null", Actual: "not null".
</pre>
<h3>GUI</h3>
<p>Currently the only GUI is a simple Pass/Fail count.</p>
<p><a href="http://ducas.files.wordpress.com/2012/04/image1.png"><img style="background-image:none;padding-left:0;padding-right:0;padding-top:0;border-width:0;" alt="MFUnit GUI" border="0" src="http://ducas.files.wordpress.com/2012/04/image1.png?w=405&#038;h=654" width="405" height="654"></a></p>
<p>Depending on whether this picks up and how many people request it, I may put some effort into listing the appropriate tests and making the information navigable.</p>
<p>Also, once VS11 is a bit closer to release, I may add a plugin for the test runner.</p>
<h2>Enjoy!</h2>
<p>Hopefully this is useful to others out there. If you have any suggestions feel free to leave comments. If you want to contribute I’ll happily accept <strong>GOOD</strong> pull requests.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ducas.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ducas.wordpress.com/272/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=272&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.duc.as/2012/04/05/unit-testing-and-the-net-micro-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3f24b4673f800e38ec198a6289901b1d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ducas</media:title>
		</media:content>

		<media:content url="http://ducas.files.wordpress.com/2012/04/image.png" medium="image">
			<media:title type="html">Install-Package MFUnit</media:title>
		</media:content>

		<media:content url="http://ducas.files.wordpress.com/2012/04/image1.png" medium="image">
			<media:title type="html">MFUnit GUI</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Web API Validation with jQuery Validate</title>
		<link>http://blog.duc.as/2012/02/28/using-web-api-validation-with-jquery-validation/</link>
		<comments>http://blog.duc.as/2012/02/28/using-web-api-validation-with-jquery-validation/#comments</comments>
		<pubDate>Mon, 27 Feb 2012 22:12:28 +0000</pubDate>
		<dc:creator>ducas</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Dev Stuff]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[ASP.NET Web API]]></category>
		<category><![CDATA[MVC 4]]></category>
		<category><![CDATA[validation errors]]></category>

		<guid isPermaLink="false">http://blog.duc.as/?p=263</guid>
		<description><![CDATA[Building on my last post about validating your model with Web API, if you&#8217;re calling a Web API controller from JavaScript you may need to parse the validation result and display it on the screen. Most people using MVC would be using the jQuery Validate plugin that&#8217;s been included with the default template for quite [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=263&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Building on <a href="http://blog.duc.as/2012/02/27/validating-your-model-with-web-api/">my last post about validating your model with Web API</a>, if you&#8217;re calling a Web API controller from JavaScript you may need to parse the validation result and display it on the screen.</p>
<p>Most people using MVC would be using the jQuery Validate plugin that&#8217;s been included with the default template for quite a while now. While most validations are performed using JavaScript adapters, some are only performed server side. As a result, the regular unobtrusive JavaScript adapters will not catch this before the post occurs. This means that you if you are using JavaScript requests with Web API to handle data manipulation you will need to somehow manually handle the validation errors that will be returned.</p>
<p>Plugging into jQuery Validation is actually quite easy… To validate a form, simply select the form using jQuery and call <strong>.validate()</strong> on it – e.g.</p>
<p><pre class="brush: jscript;">
var validator = $('.main-content form').validate();
</pre></p>
<p>This will return a <strong>validator</strong> object will a few handy methods on it. Two of which are <strong>valid()</strong> and <strong>showErrors()</strong>. The <strong>valid</strong> method will return a Boolean value indicating whether the form is valid or not and the <strong>showErrors</strong> method will show any validation errors on the current form. The <strong>showErrors</strong> method also accepts an object that defines any additional error messages you wish to display – e.g. to display the message &#8220;The title is incorrect&#8221; for a property named Title:</p>
<p><pre class="brush: jscript;">
validator.showErrors({ Title: 'The title is incorrect.' });
</pre></p>
<p>Now, assuming I a view with the following mark-up inside the form, I should see a validation error:</p>
<p><pre class="brush: xml;">
&lt;div class=&quot;editor-label&quot;&gt;@Html.LabelFor(model =&gt; model.Title)&lt;/div&gt;
&lt;div class=&quot;editor-field&quot;&gt;
    @Html.TextBoxFor(model =&gt; model.Title)
    @Html.ValidationMessageFor(model =&gt; model.Title)
&lt;/div&gt;
</pre></p>
<p style="text-align:center;"><img class="aligncenter" src="http://ducas.files.wordpress.com/2012/02/022712_0443_usingwebapi1.png?w=401&#038;h=201" alt="" width="401" height="201" /><strong><br />
</strong></p>
<p>But how do we connect this to Web API…? Well, if you&#8217;ve <a href="http://blog.duc.as/2012/02/27/validating-your-model-with-web-api/">read my previous post</a> you&#8217;ll recall that calling a Web API controller&#8217;s PUT action that&#8217;s decorated with the ValidateFilter attribute I created will return a collection of validation errors if the model is not valid. To test this, I&#8217;ll modify my TodoApiController from the previous post as follows:</p>
<p><pre class="brush: csharp;">
[ValidateFilter]
public void Put(int id, TodoItem value)
{
    if (value.Title == &quot;hi there&quot;)
        ModelState.AddModelError(&quot;Title&quot;, &quot;The title is incorrect.&quot;);

    if (!ModelState.IsValid) return;

    db.Entry(value).State = EntityState.Modified;
    db.SaveChanges();
}
</pre></p>
<p>I should now receive a validation error whenever I try to update an item with the title &#8220;hi there&#8221;. Let&#8217;s write some jQuery to submit my form:</p>
<p><pre class="brush: jscript;">
function updateItem(form, url) {
    var validator = form.validate(),
        serialized = form.serializeArray()
        data = { };

    if (!validator.valid()) { return; }

    // turn the array of form properties into a regular JavaScript object
    for (var i = 0; i &lt; serialized.length; i++) {
        data[serialized[i].name] = serialized[i].value;
    }

    $.ajax({
        type: 'PUT', // Update Action
        url: url, // API Url e.g. http://localhost:9999/api/TodoApi/1
        data: data, // e.g. { TodoItemId: 1, Title: 'hi there', IsDone: false }
        dataType: 'JSON',
        success: function () { alert('success'); },
        error: function (jqXhr) { extractErrors(jqXhr, validator); }
    });

}
</pre></p>
<p>Now let&#8217;s look at extractErrors:</p>
<p><pre class="brush: jscript;">
function extractErrors(jqXhr, validator) {

    var data = JSON.parse(jqXhr.responseText), // parse the response into a JavaScript object
        errors = { };

    for (var i = 0; i &lt; data.length; i++) { // add each error to the errors object
        errors[data[i].key] = data[i].value;
    }

    validator.showErrors(errors); // show the errors using the validator object
}
</pre></p>
<p>Lastly, attaching to the form&#8217;s <strong>submit</strong> event will call this whenever the Enter key is hit or the Submit button is clicked:</p>
<p><pre class="brush: jscript;">
$('.main-content form').submit(function () {
    updateItem($(this), '/api/TodoApi/' + $('#TodoItemId').val());
});
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ducas.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ducas.wordpress.com/263/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=263&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.duc.as/2012/02/28/using-web-api-validation-with-jquery-validation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3f24b4673f800e38ec198a6289901b1d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ducas</media:title>
		</media:content>

		<media:content url="http://ducas.files.wordpress.com/2012/02/022712_0443_usingwebapi1.png" medium="image" />
	</item>
		<item>
		<title>Validating your model with Web API</title>
		<link>http://blog.duc.as/2012/02/27/validating-your-model-with-web-api/</link>
		<comments>http://blog.duc.as/2012/02/27/validating-your-model-with-web-api/#comments</comments>
		<pubDate>Sun, 26 Feb 2012 21:55:32 +0000</pubDate>
		<dc:creator>ducas</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Dev Stuff]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[ASP.NET Web API]]></category>
		<category><![CDATA[controller implementation]]></category>
		<category><![CDATA[MVC 4]]></category>
		<category><![CDATA[validation errors]]></category>

		<guid isPermaLink="false">http://blog.duc.as/?p=216</guid>
		<description><![CDATA[One of the great things about ASP.NET 4.5&#8242;s Web API is that it&#8217;s built on the same (or similar) principles as MVC. This means that you get a lot of cool things out of your API controllers from MVC – like Action Filters. While building my first Web API controller, I wanted to ensure that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=216&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>One of the great things about ASP.NET 4.5&#8242;s Web API is that it&#8217;s built on the same (or similar) principles as MVC. This means that you get a lot of cool things out of your API controllers from MVC – like Action Filters.</p>
<p>While building my first Web API controller, I wanted to ensure that a creation or an update of an item was only done if that item was valid. I also wanted to pass any validation errors back to the client. This looks quite difficult at first because the Put and Post functions on an ApiController can&#8217;t return a result. Action Filters to the rescue!</p>
<p>With a simple action filter attribute, you can ensure that your models are validated and the errors are returned in a simple format to the client by decorating the appropriate methods.</p>
<p><strong>Note: </strong>Code also available on Gist - <a href="https://gist.github.com/1920999">https://gist.github.com/1920999</a></p>
<p><pre class="brush: csharp;">
public class ValidateFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        var modelState = actionExecutedContext.ActionContext.ModelState;
        if (!modelState.IsValid)
        {
            var errors = modelState
                .Where(s =&gt; s.Value.Errors.Count &gt; 0)
                .Select(s =&gt; new KeyValuePair&lt;string, string&gt;(s.Key, s.Value.Errors.First().ErrorMessage))
                .ToArray();

            actionExecutedContext.Result = new HttpResponseMessage&lt;KeyValuePair&lt;string, string&gt;[]&gt;(
                errors,
                HttpStatusCode.BadRequest
            );
        }
    base.OnActionExecuted(actionExecutedContext);
}
</pre></p>
<p>Now, for the controller implementation…</p>
<p><pre class="brush: csharp;">
public class TodoApiController : ApiController
{
    private BetterMobileSpaContext db = new BetterMobileSpaContext();

    // GET /api/todoapi
    public IEnumerable&lt;TodoItem&gt; Get()
    {
        return db.TodoItems.ToList();
    }

    // GET /api/todoapi/5
    public TodoItem Get(int id)
    {
        return db.TodoItems.Find(id);
    }

    // POST /api/todoapi
    [ValidateFilter]
    public void Post(TodoItem value)
    {
        if (!ModelState.IsValid) return;

        db.TodoItems.Add(value);
        db.SaveChanges();
    }

    // PUT /api/todoapi/5
    [ValidateFilter]
    public void Put(int id, TodoItem value)
    {
        if (!ModelState.IsValid) return;

        db.Entry(value).State = EntityState.Modified;
        db.SaveChanges();
    }

    // DELETE /api/todoapi/5
    public void Delete(int id)
    {
        TodoItem todoitem = db.TodoItems.Find(id);
        db.TodoItems.Remove(todoitem);
        db.SaveChanges();
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }
}
</pre></p>
<p>Now a Create (PUT) and an Update (POST) request will validate the model before invoking the appropriate action. Calling Create from using a JSON request with an invalid model would look something like this:</p>
<p><strong>Request<br />
</strong></p>
<p>Method: PUT</p>
<p>Body: { Title: &#8221;, IsDone: false }</p>
<p><strong>Response<br />
</strong></p>
<p>Status Code: 400 (Bad Request)</p>
<p>Body: [{ "key": "Title", "value": "The Title field is required" }]</p>
<p>Using a valid model will simply result in a 200 (OK) response with no body.</p>
<p><strong>NOTE: </strong>while writing this post I stumbled on these two blog posts that did the same thing and adapted my code:</p>
<ul>
<li><a href="http://weblogs.asp.net/cibrax/archive/2012/02/23/validating-your-models-in-asp-net-web-api.aspx">http://weblogs.asp.net/cibrax/archive/2012/02/23/validating-your-models-in-asp-net-web-api.aspx</a></li>
<li><a href="http://blog.alexonasp.net/post/2012/02/16/ASPNET-MVC-4-public-beta-including-ASPNET-Web-API.aspx">http://blog.alexonasp.net/post/2012/02/16/ASPNET-MVC-4-public-beta-including-ASPNET-Web-API.aspx</a></li>
</ul>
<p><strong>EDIT 2012-02-27: </strong>Updated code to replace ValidationError type with KeyValuePair and changed filter to be after action execution so controller can perform any extra validation.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ducas.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ducas.wordpress.com/216/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=216&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.duc.as/2012/02/27/validating-your-model-with-web-api/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3f24b4673f800e38ec198a6289901b1d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ducas</media:title>
		</media:content>
	</item>
		<item>
		<title>Project Liike (aka. Microsoft Patterns &amp; Practices do Mobile Web)</title>
		<link>http://blog.duc.as/2011/12/02/project-liike-aka-microsoft-patterns-practices-do-mobile-web/</link>
		<comments>http://blog.duc.as/2011/12/02/project-liike-aka-microsoft-patterns-practices-do-mobile-web/#comments</comments>
		<pubDate>Fri, 02 Dec 2011 05:50:33 +0000</pubDate>
		<dc:creator>ducas</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.duc.as/?p=199</guid>
		<description><![CDATA[Microsoft have started a new Patterns &#38; Practices project name Liike (LEEE-keh) with the aim of delivering guidance for building mobile web solutions. http://liike.github.com/ How do they plan to do this&#8230;? Well they&#8217;ve got a few FTE&#8217;s who are creating a mobile version of a previous project as a reference implementation so they can make the mistakes we&#8217;ve all [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=199&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Microsoft have started a new Patterns &amp; Practices project name Liike (LEEE-keh) with the aim of delivering guidance for building mobile web solutions.</p>
<p><a title="Project Liike" href="http://liike.github.com/" target="_blank">http://liike.github.com/</a></p>
<h3><strong>How do they plan to do this&#8230;?</strong></h3>
<p><strong></strong>Well they&#8217;ve got <a title="Project Liike - Team" href="http://liike.github.com/team/" target="_blank">a few FTE&#8217;s</a> who are creating a mobile version of<a title="Project Silk" href="http://silk.codeplex.com/" target="_blank"> a previous project</a> as a reference implementation so they can make the mistakes we&#8217;ve all made in the past. They&#8217;ve also taken on <a title="Project Liike - Advisory Board" href="http://liike.github.com/advisors/members/" target="_blank">an advisory board</a> consisting of a few members of the community (including myself) for some ideas and extra guidance.</p>
<p>One thing that&#8217;s been made clear so far is that <strong>reusable code is not a major deliverable</strong>. There are many people out there who&#8217;ve done a bang-up job of building UI frameworks and plugins for mobile web, so they don&#8217;t want to re-invent the wheel &#8211; they just want to reduce the squeak in yours by giving you the oil you need to run smoothly.</p>
<h3><strong>So, how can you help&#8230;?</strong></h3>
<p>1. There&#8217;s a uservoice site available for you to throw your ideas for what you think are the most important challenges: <a title="Liike on uservoice" href="http://liike.uservoice.com/forums/136038-mobile-web-dev-guidance" target="_blank">http://liike.uservoice.com/forums/136038-mobile-web-dev-guidance</a></p>
<p>2. Start a conversation with myself or anyone else on the advisory board! I&#8217;m always available on <a href="http://twitter.com/#!/ducas">twitter</a> and am happy to take comments on my blog. If you want to get me on email, just leave a comment on this post and I&#8217;ll get back to you.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ducas.wordpress.com/199/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ducas.wordpress.com/199/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=199&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.duc.as/2011/12/02/project-liike-aka-microsoft-patterns-practices-do-mobile-web/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3f24b4673f800e38ec198a6289901b1d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ducas</media:title>
		</media:content>
	</item>
		<item>
		<title>Using the System Tray to show progress in Windows Phone 7 Mango</title>
		<link>http://blog.duc.as/2011/10/08/using-the-system-tray-to-show-progress-in-windows-phone-7-mango/</link>
		<comments>http://blog.duc.as/2011/10/08/using-the-system-tray-to-show-progress-in-windows-phone-7-mango/#comments</comments>
		<pubDate>Fri, 07 Oct 2011 23:16:23 +0000</pubDate>
		<dc:creator>ducas</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.duc.as/?p=190</guid>
		<description><![CDATA[Before Mango it was a little difficult to put a generic status message at the top of your page. The Mango tools have made this a bit easier by giving developers (more) access to the System Tray. That&#8217;s this part: You are still a bit limited in what you can do (i.e. you can&#8217;t actually [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=190&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Before Mango it was a little difficult to put a generic status message at the top of your page. The Mango tools have made this a bit easier by giving developers (more) access to the System Tray. That&#8217;s this part:</p>
<p><img src="http://ducas.files.wordpress.com/2011/10/100711_2316_1.png?w=604" alt="" /></p>
<p>You are still a bit limited in what you can do (i.e. you can&#8217;t actually add or remove icons), but there&#8217;s a lot more flexibility than before.</p>
<p>You can access the system tray either in code or XAML using the <a title="Microsoft.Shell.SystemTray on MSDN" href="http://msdn.microsoft.com/en-us/library/microsoft.phone.shell.systemtray(v=VS.92).aspx">Microsoft.Shell.SystemTray</a> class. This class has the following dependency properties:</p>
<ul>
<li>IsVisible</li>
<li>Opacity</li>
<li>BackgroundColor</li>
<li>ForegroundColor</li>
<li>ProgressIndicator</li>
</ul>
<p>While it&#8217;s quite exciting to be able to style the status bar, I cried out of joy when I saw the ProgressIndicator property. Why…? Because now I can add progress information to the top of my pages quickly and easily! <span style="font-family:Wingdings;">J</span></p>
<p>So, I want to add a downloading message and progress bar to the top of my page (above the application title) as follows:</p>
<p><img src="http://ducas.files.wordpress.com/2011/10/100711_2316_2.png?w=604" alt="" /></p>
<p>Using XAML, I can add text and a progress bar to a page by dropping the following into the page:</p>
<p><pre class="brush: xml;">
&lt;shell:SystemTray.ProgressIndicator&gt;
    &lt;shell:ProgressIndicator IsIndeterminate=&quot;true&quot; IsVisible=&quot;True&quot; Text=&quot;Click me...&quot; /&gt;
&lt;/shell:SystemTray.ProgressIndicator&gt;
</pre></p>
<p>Or, using code, I can accomplish the same thing by dropping this into my code:</p>
<p><pre class="brush: csharp;">
ProgressIndicator progress = new ProgressIndicator
{
    IsVisible = true,
    IsIndeterminate = true,
    Text = &quot;Downloading details...&quot;
};
SystemTray.SetProgressIndicator(this, progress);
</pre></p>
<p>Feel free to download my sample application showing how to manipulate the System Tray:</p>
<p><a id="skyd_embd_pic" target="_top" href="https://skydrive.live.com/self.aspx/Public/Windows%20Phone/SystemTraySample.zip?cid=12bab4bf59b6545b&amp;sc=documents" title="Open SystemTraySample.zip"><br />
        <img style="border:0;display:block;margin-right:auto;margin-left:auto;" alt="Open SystemTraySample.zip" src="https://secure.wlxrs.com/9!gjCOhzHcZ6fOPYZXGQtg/images/icons/Large/Zip.png"><br />
    </a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ducas.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ducas.wordpress.com/190/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=190&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.duc.as/2011/10/08/using-the-system-tray-to-show-progress-in-windows-phone-7-mango/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3f24b4673f800e38ec198a6289901b1d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ducas</media:title>
		</media:content>

		<media:content url="http://ducas.files.wordpress.com/2011/10/100711_2316_1.png" medium="image" />

		<media:content url="http://ducas.files.wordpress.com/2011/10/100711_2316_2.png" medium="image" />

		<media:content url="https://secure.wlxrs.com/9!gjCOhzHcZ6fOPYZXGQtg/images/icons/Large/Zip.png" medium="image">
			<media:title type="html">Open SystemTraySample.zip</media:title>
		</media:content>
	</item>
		<item>
		<title>Pushing to Windows Phone 7 devices using MetroPimp</title>
		<link>http://blog.duc.as/2011/08/09/pushing-to-wp7-devices-using-metropimp/</link>
		<comments>http://blog.duc.as/2011/08/09/pushing-to-wp7-devices-using-metropimp/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 22:44:01 +0000</pubDate>
		<dc:creator>ducas</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.duc.as/2011/08/09/pushing-to-your-devices-using-metropimp/</guid>
		<description><![CDATA[Recently I released a little open source project with the aim of making it easier for developers to write services that push information to Windows Phone 7 devices called MetroPimp. This library is available via nuget and on bitbucket. Based on a blog post I wrote when WP7 was still in beta, MetroPimp provides a simple [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=180&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Recently I released a little open source project with the aim of making it easier for developers to write services that push information to Windows Phone 7 devices called MetroPimp.</p>
<p>This library is available via <a title="nuget.org - MetroPimp" href="http://nuget.org/List/Packages/MetroPimp" target="_blank">nuget</a> and on <a title="bitbucket - MetroPimp" href="https://bitbucket.org/ducas/metropimp" target="_blank">bitbucket</a>.</p>
<p><a href="http://ducas.files.wordpress.com/2011/08/intsall-package_metropimp.png"><img class="alignnone size-medium wp-image-182" title="intsall-package_metropimp" src="http://ducas.files.wordpress.com/2011/08/intsall-package_metropimp.png?w=300&#038;h=62" alt="" width="300" height="62" /></a></p>
<p>Based on <a title="Push Notifications in WP7" href="http://blog.duc.as/2010/08/13/push-notifications-in-windows-phone-7/" target="_blank">a blog post I wrote when WP7 was still in beta</a>, MetroPimp provides a simple and consistent API that allows you to push Toast, Tile (single and double sided) and Raw push notifications to WP7 devices using the Microsoft Push Notification Service (MPNS).</p>
<p>As developers who have tried this already may know, there is quite a bit of work that goes into setting up push notifications. First you have to register for notifications on the device by opening a channel. Then you have to get the URI provided by MPNS and send it to a service of your own. Lastly, using this URI you need to form XML packets and craft HTTP requests with the right headers to push the data to the device.</p>
<p>MetroPimp simplifies the last step of this process by providing a model that represents the messages you want to send to devices, a single method call to handle serializing the message and sending it up the wire and a simple result which, in the case of failure, identifies the reason for the failure and provides informative message.</p>
<p>Enough talking… show us the code!!!</p>
<p>The main entry point of MetroPimp is the <strong>Pusher</strong> class (which can be mocked via the IPusher interface). It has a single method named <strong>Send</strong> that accepts a <strong>Message</strong> and returns a <strong>SendMessageResponse</strong>. To create a Pusher, simply new it up (or inject it using your preferred IOC container).</p>
<p><pre class="brush: csharp;">
var pusher = new Pusher();
</pre></p>
<p>The following sections will define the classes you can use to push various notification formats to a device. For more information on message formats, please refer to <a href="http://msdn.microsoft.com/en-us/library/hh202945(v=VS.92).aspx">Sending Push Notifications for Windows Phone on MSDN</a>.</p>
<h2>Raw</h2>
<p>To send raw data to the phone (i.e. a notification that is not a toast or tile update), create an instance of <strong>Raw</strong> and send it using the pusher.</p>
<p><pre class="brush: csharp;">
var rawMessage = new Raw {
    Uri = /* insert MPNS uri here */,
    Content = &quot;hello world!&quot;
    };
pusher.Send(rawMessage);
</pre></p>
<p>MPNS does not limit you to sending strings in the raw message. However, seeing as just about anything can be represented as a string, I decided this may be more universal. Under the covers, MetroPimp simply converts the string to its UTF8 representation and drops it into the request body.</p>
<p>For more information on sending and receiving raw notifications, refer to <a href="http://msdn.microsoft.com/en-us/library/hh202977(v=vs.92).aspx">How to: Send and Receive Raw Notifications for Windows Phone on MSDN</a>.</p>
<h2>Toast</h2>
<p>Sending a toast message is similar to sending a raw message in that you simply create an instance of a <strong>Toast</strong> object and pass it into <strong>Send</strong>. Toast has 3 fields that differ it from a raw:</p>
<ul>
<li><strong>Text1 </strong>– The<strong><br />
</strong>first bit of bold text that appears in the toast (required)</li>
<li><strong>Text2</strong> – The second bit of text that appears in the toast (optional)</li>
<li><strong>Param</strong> – A parameter string to be passed to the application if the user taps the notification (optional)</li>
</ul>
<p><pre class="brush: csharp;">
var toastMessage = new Toast {
    Uri = /* insert MPNS uri here */,
    Text1 = &quot;Hello World!&quot;,
    Text2 = &quot;This is a toast.&quot;,
    Param = &quot;helloWorldToasted&quot;
    };
pusher.Send(toastMessage);
</pre></p>
<p>For more information on sending and receiving toast notifications, refer to <a href="http://msdn.microsoft.com/en-us/library/hh202967(v=vs.92).aspx">How to: Send and Receive Toast Notifications for Windows Phone on MSDN</a>.</p>
<h2>Tile</h2>
<p>Tile notifications can be specified to be either single or double sided tiles. As double sided tiles are only supported by WP7 Mango, the functionality has been split into two classes. Sending a single sided tile is done by specifying properties available on the <strong>Tile</strong> class.</p>
<ul>
<li><strong>BackgroundImageUri</strong> – The URI to the background image for the tile. Can be either embedded or remote. (required)</li>
<li><strong>Title </strong>– The text to use as the title of the tile. (required)</li>
<li><strong>Count</strong> – The number to show in the blue bubble. Not defining or using 0 will clear the bubble. (optional)</li>
</ul>
<p><pre class="brush: csharp;">
var tileMessage= new Tile {
    Uri = /* insert MPNS uri here */,
    BackgroundImageUri = &quot;background.png&quot;,
    Title = &quot;Hello World&quot;,
    Count = 9
    };
pushed.Send(tileMessage);
</pre></p>
<p>Double sided tiles are sent by specifying properties on the <strong>DoubleSidedTile</strong> class. This class has the same set of properties as <strong>Tile</strong> for the front side of the tile, along with the following properties for the back side:</p>
<ul>
<li><strong>BackBackgroundImageUri</strong> – The URI to the background image for the back of the tile.</li>
<li><strong>BackTitle </strong>– The text to use as the title for the back of the tile.</li>
<li><strong>BackContent </strong>– The text to display over the top of the background image on the back of the tile.</li>
</ul>
<p><pre class="brush: csharp;">
var doubleSidedTileMessage = new DoubleSidedTile {
    Uri = /* insert MPNS uri here */,
    BackgroundImageUri = &quot;background.png&quot;, 
    Title = &quot;Hello World&quot;, 
    Count = 9, 
    BackBackgroundImageUri = &quot;back_background.png&quot;,
    BackTitle = &quot;Hello Back&quot;,
    BackContent = &quot;This is the back&quot;
    };
pushed.Send(doubleSidedTileMessage);
</pre></p>
<p>For more information on sending and receiving toast notifications, refer to <a href="http://msdn.microsoft.com/en-us/library/hh202970(v=VS.92).aspx">How to: Send and Receive Tile Notifications for Windows Phone on MSDN</a>.</p>
<h2>Auxiliary Properties</h2>
<p>Raw, Toast, Tile and DoubleSidedTile all inherit the base Message class. This class provides the following optional properties to give you greater control over your notification messages:</p>
<ul>
<li><strong>Id</strong> – a GUID value representing the message identifier.</li>
<li><strong>DeliveryInterval </strong>– Defines when the message should be delivered to the device. This can either be immediate (default), within 450 seconds or within 900 seconds.</li>
</ul>
<h2>SendMessageResponse</h2>
<p>As soon as you&#8217;ve started trying to send notifications to devices, you&#8217;ll want to know if it gets through and/or why it failed. To handle this, <strong>Pusher.Send </strong>returns a <strong>SendMessageResponse</strong> object with the following properties:</p>
<ul>
<li><strong>ErrorMessage</strong> – The message returned from MPNS on the HTTP response.</li>
<li><strong>MessageId </strong>– The<strong><br />
</strong>identifier of the message. Only included if specified when sending.</li>
<li><strong>HttpStatusCode</strong> – The HTTP status code (e.g. 200, 400, 401, etc.) of the HTTP response returned from MPNS.</li>
<li><strong>HttpStatusDescription </strong>– The description of the HTTP status code returned from MPNS.</li>
<li><strong>StatusCode </strong>– The actual status of the notification&#8217;s delivery returned from MPNS (i.e. Received, Queue Full, Suppressed or Dropped).</li>
<li><strong>DeviceConnectionStatusCode </strong>– The status of the device&#8217;s connection to MPNS (i.e. Connected, Temporarily Disconnected, Inactive or Disconnected).</li>
<li><strong>SubscriptionStatusCode </strong>– The status of the device&#8217;s subscription to MPNS (i.e. Active or Expired).</li>
<li><strong>DetailsStatusDescription </strong>– The detailed description of the notification message&#8217;s status given the HTTP status code, MPNS status code, connection and subscription status according to the MSDN documentation.</li>
</ul>
<p>For more information on response codes, refer to <a href="http://msdn.microsoft.com/en-us/library/ff941100(v=VS.92).aspx">Push Notification Service Response Codes for Windows Phone on MSDN</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ducas.wordpress.com/180/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ducas.wordpress.com/180/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=180&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.duc.as/2011/08/09/pushing-to-wp7-devices-using-metropimp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3f24b4673f800e38ec198a6289901b1d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ducas</media:title>
		</media:content>

		<media:content url="http://ducas.files.wordpress.com/2011/08/intsall-package_metropimp.png?w=300" medium="image">
			<media:title type="html">intsall-package_metropimp</media:title>
		</media:content>
	</item>
		<item>
		<title>Back button broken for URL hashes in IE on WP7 Mango</title>
		<link>http://blog.duc.as/2011/07/13/back-button-broken-for-url-hashes-in-ie-on-wp7-mango/</link>
		<comments>http://blog.duc.as/2011/07/13/back-button-broken-for-url-hashes-in-ie-on-wp7-mango/#comments</comments>
		<pubDate>Wed, 13 Jul 2011 06:39:00 +0000</pubDate>
		<dc:creator>ducas</dc:creator>
				<category><![CDATA[Dev Stuff]]></category>
		<category><![CDATA[Windows Phone 7]]></category>
		<category><![CDATA[jQuery Mobile]]></category>
		<category><![CDATA[WP7]]></category>

		<guid isPermaLink="false">https://ducas.wordpress.com/2011/07/13/back-button-broken-for-url-hashes-in-ie-on-wp7-mango/</guid>
		<description><![CDATA[I’ve been on a little twitter rant recently about this, and thought I’d use my blog as another distribution medium. Feel free to leave comments here, here (connect forum) or here (jQuery Mobile forum). Here’s the content of my connect forum post on the matter: Mango seems to have brought along with it a broken [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=176&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I’ve been on a little <a href="http://twitter.com/ducas">twitter</a> rant recently about this, and thought I’d use my blog as another distribution medium.</p>
<p>Feel free to leave comments here, <a href="http://forums.create.msdn.com/forums/p/87118/523084.aspx#523084">here (connect forum)</a> or here <a href="http://forum.jquery.com/topic/back-broken-in-windows-phone-7-mango">(jQuery Mobile forum)</a>.</p>
<p>Here’s the content of my connect forum post on the matter:</p>
<blockquote><p>Mango seems to have brought along with it a broken browser&#8230;</p>
<p>When you link to an anchor on your page using a hash, the back button doesn&#8217;t seem to work too well.</p>
<p>For example, go to <a href="http://jquerymobile.com/demos/1.0b1/">http://jquerymobile.com/demos/1.0b1/</a>. Those in the know will realise why&#8230; To put it simply, jQuery Mobile uses hash changes to navigate between &#8220;pages&#8221; in a single or multiple page web application. It uses the hash changed events to determine when to use javascript to request the next page, load it into the DOM and perform an animation to display the next page.</p>
<p>Navigating forward on a jQuery Mobile site works perfectly as expected. It&#8217;s when you hit the back button that things go wrong. On a desktop browser, going from the landing page to &#8220;Into to jQuery Mobile&#8221; swipes in the intro page and hitting back swipes it out again to show the landing page. However, on Mango, hitting the back button when on the intro page does nothing. If you were on another site before you went the the demo landing page, then hitting the back button again will take you back to the previous site.</p>
<p>I have been working on an embedded web application recently and this has been driving me crazy! I&#8217;m seeing a Navigated event being raised by the WebBrowser control when it goes to the second page in the application, but back buttons (and manually invoking history.back() and history.go(-1) in javascript) just don&#8217;t do anything.</p>
<p>This seems to be a breaking change to me and would potentially mean I push to have Windows Phone 7 dropped as a targetted platform for the (relatively high traffic) website I am working on. An embarrassing idea seeing as I pushed for it to be targetted&#8230; <img src='http://s0.wp.com/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> </p></blockquote>
<p><strong>UPDATE 14 July 2011</strong> &#8211; It&#8217;s been noted that the jQuery Mobile docs site mentioned does work in previous builds of WP7, running IE 7 Mobile. This verifies that this issue has been introduced with IE9 Mobile on WP7 Mango.</p>
<p><strong>UPDATE II 14 July 2011</strong> - The issue is a little deeper than I initially realized. If you define a simple page with an anchor at the top of the page referencing a div at the bottom of the page then we see some more exotic behaviour. Clicking the link and hitting back will work the first time. However, you&#8217;ll notice that in the address bar the hash is not removed from the URL. This means that clicking the link and hitting back again will get the browser into a tangle. Here is the HTML snippet I used:</p>
<p><pre class="brush: xml;">
&lt;a href=&quot;#bottom&quot;&gt;bottom&lt;/a&gt;
&lt;div style=&quot;height: 1000px&quot;&gt;&lt;/div&gt;
&lt;a id=&quot;bottom&quot; href=&quot;#&quot; onclick=&quot;javascript:history.back();return false;&quot;&gt;back&lt;/a&gt;
</pre></p>
<p><strong>UPDATE III October 2011</strong> - The issue appears to have been fixed in Mango RTM. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ducas.wordpress.com/176/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ducas.wordpress.com/176/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=176&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.duc.as/2011/07/13/back-button-broken-for-url-hashes-in-ie-on-wp7-mango/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3f24b4673f800e38ec198a6289901b1d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ducas</media:title>
		</media:content>
	</item>
		<item>
		<title>Making MVC 3 a little more&#8230; dynamic</title>
		<link>http://blog.duc.as/2011/06/07/making-mvc-3-a-little-more-dynamic/</link>
		<comments>http://blog.duc.as/2011/06/07/making-mvc-3-a-little-more-dynamic/#comments</comments>
		<pubDate>Tue, 07 Jun 2011 11:33:34 +0000</pubDate>
		<dc:creator>ducas</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">https://ducas.wordpress.com/?p=165</guid>
		<description><![CDATA[The other day I ran into a little problem. I wanted to be able to post some JSON to a web service and have it accept a whole bunch of data (not exactly the technical term) that was not predefined. Given this very vague problem, I decided I wanted to use ASP .NET MVC 3. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=165&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The other day I ran into a little problem. I wanted to be able to post some JSON to a web service and have it accept a whole bunch of data (not exactly the technical term) that was not predefined.</p>
<p>Given this very vague problem, I decided I wanted to use ASP .NET MVC 3. So starting with File\New Project, I added a method to my HomeController as follows:</p>
<p><pre class="brush: csharp;">
[HttpPost]
public ActionResult DoSomething(string a, string b, dynamic c)
{
    return new EmptyResult();
}
</pre></p>
<p>The thought behind this was that I wanted to supply two required properties (a and b) and basically have a dynamic bag for everything else. Also, I didn’t want to be restricted to a single layer of properties. Instead, I wanted to be able to pass a deep tree and have it totally accessible.</p>
<p>Then I pulled up fiddler and set up a request with the following details:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td valign="top" width="196">Method</td>
<td valign="top" width="420">POST</td>
</tr>
<tr>
<td valign="top" width="196">URL</td>
<td valign="top" width="420"><a href="http://localhost:2643/Home/DoSomething">http://localhost:2643/Home/DoSomething</a></td>
</tr>
<tr>
<td valign="top" width="196">Request Headers</td>
<td valign="top" width="420">User-Agent: Fiddler</p>
<p>Content-Type: application/json</td>
</tr>
<tr>
<td valign="top" width="196">Request Body</td>
<td valign="top" width="420">{ a: &#8220;Hello&#8221;, b: &#8220;World&#8221;, c: { d: &#8220;this&#8221;, e: &#8220;is&#8221;, f: &#8220;dynamic&#8221; } }</td>
</tr>
</tbody>
</table>
<p><a href="http://ducas.files.wordpress.com/2011/06/image.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="fiddler request builder" src="http://ducas.files.wordpress.com/2011/06/image_thumb.png?w=401&#038;h=332" alt="image" width="401" height="332" border="0" /></a></p>
<p>When I hit execute and set a breakpoint on the action, I received the following values in my locals:</p>
<p><a href="http://ducas.files.wordpress.com/2011/06/clip_image002.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="debugging: a = &quot;Hello&quot;, b =&quot;World&quot; c = {object}" src="http://ducas.files.wordpress.com/2011/06/clip_image002_thumb.png?w=621&#038;h=61" alt="clip_image002" width="621" height="61" border="0" /></a></p>
<p>As expected, the JsonValueProviderFactory has kicked in and populated the values of a and b using the JSON provided. However, it cannot match c properly so simply throws an object at it that is not dynamic and does not have values on it, hence useless.</p>
<p>After some searching, I found a few valid solutions. The most useful one was <a href="http://www.amazedsaint.com/2011/02/aspnet-mvc-dynamic-json-jquery.html">this blog post by Anoop Madhusundanan</a>. In this post, he describe the process of using a model binder and a custom model binder attribute to identify parameters of an action method that are to use the model binder. This seemed like a great solution for me, but had a couple of little problems… Most importantly, Anoop’s solution does not allow for multiple parameters on an action method or mapping the parameter to the property in the JSON object.</p>
<p>I came up with a very similar way of solving this problem. I created a class named DynamicJsonBinder which implements IModelBinder, just like Anoop. The main difference with my solution is that I provided a way to ensure that the parameter being populated with the dynamic object is mapped based on the name of the parameter. This is done by using a switch on the attribute called MatchName, which will cause the binder to look at the parameter name and find the matching property in the JSON object to return.</p>
<p>Here’s the attribute:<br />
<pre class="brush: csharp;">
using System.Web.Mvc;

public class DynamicJsonAttribute : CustomModelBinderAttribute
{
    public override IModelBinder GetBinder()
    {
        return new DynamicJsonBinder(MatchName);
    }

    public bool MatchName { get; set; }
}
</pre><br />
And here’s the model binder:<br />
<pre class="brush: csharp;">
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Web.Helpers;
using System.Web.Mvc;

public class DynamicJsonBinder : IModelBinder
{
    private readonly bool matchName;

    public DynamicJsonBinder(bool matchName)
    {
        this.matchName = matchName;
    }

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var contentType = controllerContext.HttpContext.Request.ContentType;
        if (!contentType.StartsWith(&quot;application/json&quot;, StringComparison.OrdinalIgnoreCase))
            return null;

        string bodyText;
        using (var stream = controllerContext.HttpContext.Request.InputStream)
        {
            stream.Seek(0, SeekOrigin.Begin);
            using (var reader = new StreamReader(stream))
                bodyText = reader.ReadToEnd();
        }

        if (string.IsNullOrEmpty(bodyText)) return null;

        var desiralized = Json.Decode(bodyText);

        if (!matchName) return desiralized;

        var members = desiralized.GetDynamicMemberNames() as IEnumerable&amp;lt;string&amp;gt;;
        return members == null
            || members.Contains(bindingContext.ModelName)
            ? desiralized[bindingContext.ModelName] : null;
    }
}</pre><br />
So if by adding a DynamicJson attribute to the c parameter on the action method, we’ll get the following:<br />
<pre class="brush: csharp;">
public ActionResult DoSomething(string a, string b, [DynamicJson] dynamic c)
{
    return new EmptyResult();
}
</pre><br />
Debugging into this with the same post request as earlier:</p>
<p><a href="http://ducas.files.wordpress.com/2011/06/clip_image004.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="debugging: recursive full object" src="http://ducas.files.wordpress.com/2011/06/clip_image004_thumb.jpg?w=568&#038;h=190" alt="clip_image004" width="568" height="190" border="0" /></a></p>
<p>We see that c has been populated with a DynamicJsonObject (the result of the call to Json.Decode) and that it has recursively mapped the properties under the JSON object to dynamic object. However, the value is the entire JSON object, that is it’s not mapped to the c property.</p>
<p>To enable name matching we get the following code:<br />
<pre class="brush: csharp;">
[HttpPost]
public ActionResult DoSomething(string a, string b, [DynamicJson(MatchName = true)] dynamic c)
{
    return new EmptyResult();
}
</pre><br />
Debugging we get:</p>
<p><a href="http://ducas.files.wordpress.com/2011/06/clip_image006.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="debugging: recursive mapped property" src="http://ducas.files.wordpress.com/2011/06/clip_image006_thumb.jpg?w=567&#038;h=133" alt="clip_image006" width="567" height="133" border="0" /></a></p>
<p>And we see that the property has been matched correctly and the correct value is passed through to the parameter.</p>
<p>Using these two simple classes and a bit of dynamic know-how, I’ve managed to post anything to my web service and have it dynamically accessible. This basically means we have the equivalent of a property bag on steroids that can be queried and manipulated in the same way as any dynamic object. We can even re-serialize the dynamic object to JSON and store it as is if required.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ducas.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ducas.wordpress.com/165/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=165&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.duc.as/2011/06/07/making-mvc-3-a-little-more-dynamic/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3f24b4673f800e38ec198a6289901b1d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ducas</media:title>
		</media:content>

		<media:content url="http://ducas.files.wordpress.com/2011/06/image_thumb.png" medium="image">
			<media:title type="html">fiddler request builder</media:title>
		</media:content>

		<media:content url="http://ducas.files.wordpress.com/2011/06/clip_image002_thumb.png" medium="image">
			<media:title type="html">debugging: a = &#34;Hello&#34;, b =&#34;World&#34; c = {object}</media:title>
		</media:content>

		<media:content url="http://ducas.files.wordpress.com/2011/06/clip_image004_thumb.jpg" medium="image">
			<media:title type="html">debugging: recursive full object</media:title>
		</media:content>

		<media:content url="http://ducas.files.wordpress.com/2011/06/clip_image006_thumb.jpg" medium="image">
			<media:title type="html">debugging: recursive mapped property</media:title>
		</media:content>
	</item>
		<item>
		<title>A Day in the Life of a Metro-veloper</title>
		<link>http://blog.duc.as/2010/08/25/a-day-in-the-life-of-a-metro-veloper/</link>
		<comments>http://blog.duc.as/2010/08/25/a-day-in-the-life-of-a-metro-veloper/#comments</comments>
		<pubDate>Wed, 25 Aug 2010 01:01:38 +0000</pubDate>
		<dc:creator>ducas</dc:creator>
				<category><![CDATA[Dev Stuff]]></category>
		<category><![CDATA[Windows Phone 7]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WP7]]></category>

		<guid isPermaLink="false">https://ducas.wordpress.com/2010/08/25/a-day-in-the-life-of-a-metro-veloper/</guid>
		<description><![CDATA[This is a follow-up post to my Windows Phone 7 presentation last week at the SDDN. I have uploaded my powerpoint deck to SlideShare. Some of the sample apps I used are available on MSDN. And there was a recent video on youtube of an awesome golfing app that really shows the power of the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=135&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>This is a follow-up post to <a href="http://sydney.sddn.org.au/2010/08/08/sddn-sydney-august-meeting-16th-of-august/">my Windows Phone 7 presentation last week at the SDDN</a>.</p>
<p>I have uploaded my powerpoint deck to <a href="http://www.slideshare.net/ducasf/a-day-in-the-life-of-a-metroveloper">SlideShare</a>.</p>
<p>Some of the sample apps I used are <a href="http://msdn.microsoft.com/en-us/library/ff431744(VS.92).aspx">available on MSDN</a>.</p>
<p>And there was a recent <a href="http://www.youtube.com/watch?v=wM5LHgSpecw">video on youtube of an awesome golfing app</a> that really shows the power of the WP7 UX.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ducas.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ducas.wordpress.com/135/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.duc.as&#038;blog=1202116&#038;post=135&#038;subd=ducas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.duc.as/2010/08/25/a-day-in-the-life-of-a-metro-veloper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3f24b4673f800e38ec198a6289901b1d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ducas</media:title>
		</media:content>
	</item>
	</channel>
</rss>
