<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jayway Team Blog &#187; .Net</title>
	<atom:link href="http://blog.jayway.com/tag/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Tue, 07 Feb 2012 10:49:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>A quick note about exit codes from powershell</title>
		<link>http://blog.jayway.com/2012/01/19/a-quick-note-about-exit-codes-from-powershell/</link>
		<comments>http://blog.jayway.com/2012/01/19/a-quick-note-about-exit-codes-from-powershell/#comments</comments>
		<pubDate>Thu, 19 Jan 2012 12:27:30 +0000</pubDate>
		<dc:creator>Jakob Nilsson-Ehle</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[powershell]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11874</guid>
		<description><![CDATA[This may be an extreme edge case, but since I spent a few hours on something rather trivial, I though I should share it. When running Invoke-Command from powershell invoked via command line – be wary of the curly braces. What is the difference between the following two commands? powershell.exe -Command "&#38; {invoke-command {throw 'error'}}" [...]]]></description>
			<content:encoded><![CDATA[<p>This may be an extreme edge case, but since I spent a few hours on something rather trivial, I though I should share it. When running <code>Invoke-Command</code> from powershell invoked via command line – be wary of the curly braces.</p>
<p>What is the difference between the following two commands?</p>
<blockquote><p><code>powershell.exe -Command "&amp; {invoke-command {throw 'error'}}"</code></p></blockquote>
<blockquote><p><code>powershell.exe -Command "&amp; invoke-command {throw 'error'}"</code></p></blockquote>
<p>As it turns out, the first one will exit with error code 0, the second one will exit with error code 1. This in turn is very important if you want to integrate some powershell command into your build process, and want to make sure that the build does or does not fail if the invoked command fails. An example from real life would be stopping and starting a web server, such as</p>
<blockquote><p><code>powershell.exe -Command "&amp; invoke-command -ComputerName MYSERVER {Import-Module WebAdministration; Stop-Website Default}"</code></p></blockquote>
<p>In my case I needed to do automatic deploy to a web server from a CI system, and thus it was important to mark the build as failed if my commands to the web server didn't get through. Since I am somewhat of a beginner to powershell, it took a while to find that wrapping the command in curly braces was the cause.</p>
<p>I hope this is of some use if you find your build succeeding even though your powershell commands failed.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/01/19/a-quick-note-about-exit-codes-from-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with the Search charm in Windows 8</title>
		<link>http://blog.jayway.com/2012/01/09/working-with-the-search-charm-in-windows-8/</link>
		<comments>http://blog.jayway.com/2012/01/09/working-with-the-search-charm-in-windows-8/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 08:00:00 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[windows 8]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11505</guid>
		<description><![CDATA[I actually attended BUILD. I sat there, bombarded with so much information about Windows 8 and Metro style applications that I just went into my happy place, franticly taking notes on all that I should investigate later on. That very long and almost unreadable list contained, amongst many others, the keywords – contracts and charms. [...]]]></description>
			<content:encoded><![CDATA[<p>I actually attended <a href="http://www.buildwindows.com/" target="_blank">BUILD</a>. I sat there, bombarded with so much information about Windows 8 and Metro style applications that I just went into my happy place, franticly taking notes on all that I should investigate later on. That very long and almost unreadable list contained, amongst many others, the keywords – contracts and charms. To be perfectly honest I didn’t really grasp the concept at first. Implement contracts in order to make your application available to charms… say what now? My best way to actually understand something really follows the same pattern every time (although sometimes my progress stops at confusion).</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/Presentation1.png" rel="lightbox"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px; border-width: 0px;" title="Thought process" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/Presentation1_thumb.png" alt="Thought process" width="609" height="226" border="0" /></a></p>
<p>This time was no different, so when I finally reached some sort of understanding I ended up with this blog post. I’ll try to explain charms and contracts. I also want to show how you can use a charm, more specifically the search charm, to extend your application into Windows 8.</p>
<h2>Charms and contract - no comprende?</h2>
<p>Let’s start with charms. As it is, you get five charms in Windows 8. You have Search,<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/charms.png" rel="lightbox"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; float: right; padding-top: 0px; border-width: 0px;" title="The charms" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/charms_thumb.png" alt="The charms" width="43" height="240" align="right" border="0" /></a> Share, Start (you can’t really do anything with this one, it just shows the home screen), Devices and Settings. They can either be accessed by sliding in from the right hand side or, if you are using a mouse, you can find them in the bottom left. You can think of charms as a more powerful version of the traditional start menu. A start menu that you can use to extend your application into the operating system.</p>
<p>What about contracts then? Contracts are what connect your application to the charms. You just select the required contract in your appmanifest and then voilà. You can write all of your code without doing this, but then will get an <a href="http://msdn.microsoft.com/en-us/library/system.accessviolationexception.aspx" target="_blank">AccessViolationException</a> when running your code - which tends to go against best practice.</p>
<h2>Implementing the search charm</h2>
<p>So, I started with a basic implementation of the search charm. As a test application I had my conference application that I wrote for <a href="http://oredev.org/2011" target="_blank">Øredev</a>. First up, declare the contract in order to avoid that nagging exception. Just open up your <em>Package.appxmanifest</em> file and declare your application as one that can interact with the search charm.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/011.png" rel="lightbox"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px; border-width: 0px;" title="Signing the contract" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/01_thumb1.png" alt="Signing the contract" width="653" height="302" border="0" /></a></p>
<p>If we start our application now and then press the search charm we will see our own little Øredev application, at the very top with the ugly icon, in the list for applications implementing the search contract. That’s basically all one need to know about contracts.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/021.png" rel="lightbox"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px; border-width: 0px;" title="Contract implemented" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/02_thumb1.png" alt="Contract implemented" width="654" height="368" border="0" /></a></p>
<p>Now we’re all set up to start coding. In <em>App.xaml.cs</em>, add the following code.</p>
<pre class="brush: csharp; ruler: true; gutter: false;">protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    ActivateSearchCharm();
    ShowCollection();
    Window.Current.Activate();
}

private void ActivateSearchCharm()
{
    var pane = SearchPane.GetForCurrentView();
    pane.QuerySubmitted += QuerySubmitted;
    pane.SuggestionsRequested += SuggestionsRequested;
    pane.ResultSuggestionChosen += ResultSuggestionChosen;
}

protected override void OnSearchActivated(SearchActivatedEventArgs args)
{
    // the first page in a collection of many - just for testing
    ShowSplit(_sampleData.GroupedCollections.First(), args.QueryText);
}</pre>
<p>What we get here is basically three different events and one override that you should handle in order to implement the search charm.</p>
<ul>
<li>Event – QuerySubmitted</li>
<li>Event – SuggestionsRequested</li>
<li>Event – ResultSuggestionChosen</li>
<li>Override – OnSearchActivated</li>
</ul>
<p>We start with the override of <em>OnSearchActivated</em>. This will trigger if our application is not in the foreground and you swipe out the right pane, press the search charm and then tap the application. In the screenshot below you can see what happened when I did just that. In this case I just show a plain view containing all the talks for the Agile track, naturally, one should navigate to something more suitable in a real application.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/031.png" rel="lightbox"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px; border-width: 0px;" title="OnSearchActived done" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/03_thumb1.png" alt="OnSearchActived done" width="650" height="366" border="0" /></a></p>
<p>We continue with the implementation of <em>QuerySubmitted</em>. This event will fire when the user enters a query and then press enter. I to remind any and all that this code is only intended to make my example work, I would not implement any real search functionality this way.</p>
<pre class="brush: csharp; ruler: true; gutter: false;">private void QuerySubmitted(SearchPane sender, SearchPaneQuerySubmittedEventArgs args)
{
    var items = page.Items as SampleDataCollection;
    page.Items = items.OfType&lt;SampleDataItem&gt;()
                      .Where(a =&gt; a.Description.Contains(args.QueryText));
}</pre>
<p>Right, so we pick out all the items bound to the page. Then we pick out any item that has a description that contains the query string. To test my code I simply entered “someone” and tapped enter.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/05.png" rel="lightbox"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px; border-width: 0px;" title="My very first query" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/05_thumb.png" alt="My very first query" width="654" height="368" border="0" /></a></p>
<p>As you can see, all other sessions, not containing the word “someone” are removed, only showing the session that match the search criteria.</p>
<p>This was basically all that I expected from the search charm. But there’s actually one more thing to the it that can really make your application shine. The secret sauce? <em>SuggestionsRequested</em> and <em>ResultSuggestionChosen</em>.</p>
<pre class="brush: csharp; ruler: true; gutter: false;">private void SuggestionsRequested(SearchPane sender, SearchPaneSuggestionsRequestedEventArgs args)
{
    var suggestions = args.Request.SearchSuggestionCollection;
    var items = page.Items
                    .OfType&lt;SampleDataItem&gt;()
                    .Where(i =&gt; i.Category.StartsWith(args.QueryText, StringComparison.OrdinalIgnoreCase));

    foreach (var item in items)
    {
        suggestions.AppendResultSuggestion(

                    item.Category,
                    item.Title,
                    item.Title,
                    StreamReference.CreateFromUri(new Uri(item.ImagePath)),
                    item.Title);
    }
}

private void ResultSuggestionChosen(SearchPane sender, SearchPaneResultSuggestionChosenEventArgs args)
{
    var items = page.Items as SampleDataCollection;
    page.Items = items.OfType&lt;SampleDataItem&gt;()
                      .Where(a =&gt; a.Title == args.Tag));
}</pre>
<p>So, this is what happens. When the user start to write in the search field, <em>SuggestionsRequested</em> is called, once called we can find any partial matches for the query string. In my case I match against everything that is the start of <em>Category</em>. Then I add those results to the search charm with <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.search.searchsuggestioncollection.appendresultsuggestion" target="_blank"><em>AppendResultSuggestion(string text, string detailText, string tag, StreamReference image, string imageAlternateText)</em></a>. This will give us this very neat behavior.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/Untitled1.png" rel="lightbox"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px; border: 0px;" title="Awesomeness" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/Untitled_thumb1.png" alt="Awesomeness" width="652" height="367" border="0" /></a></p>
<p>If the user starts writing a word we can send suggested items to the search charm. If the user taps on one of them it will trigger <em>ResultSuggestionChosen</em> where we will get the <em>Tag</em> for the selected item allowing us to display it. Also notice that “Joha” gets highlighted in the suggestion list; this is done automagically by Windows 8.</p>
<h2>Possibilities</h2>
<p>Personally - I’m very excited about this. Charms really take one step closer to really erase the borders between the OS and your application. Much like what Microsoft has done with Windows Phone. I believe that this is the right way to go and I look forward to see it evolve.</p>
<p>But - there’s always a but. Don’t implement it if your application doesn’t have the need for it. It can be pretty annoying to have several applications taking up space in the search pane without having any real reason for doing so.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/01/09/working-with-the-search-charm-in-windows-8/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>In the async world &#8211; no one can hear you scream</title>
		<link>http://blog.jayway.com/2011/12/12/in-the-async-world-no-one-can-hear-you-scream/</link>
		<comments>http://blog.jayway.com/2011/12/12/in-the-async-world-no-one-can-hear-you-scream/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 09:05:00 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[windows 8]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11405</guid>
		<description><![CDATA[I wrote my first Windows 8 Metro application right before Øredev 2011. It was a small application that basically just displayed all tracks and speakers at the conference. I had the luxury of having access the raw conference xml data from the server, but one thing that I have learnt from conferences is that the [...]]]></description>
			<content:encoded><![CDATA[<p>I wrote my first Windows 8 Metro application right before <a href="http://oredev.org/2011">Øredev 2011</a>. It was a small application that basically just displayed all tracks and speakers at the conference. I had the luxury of having access the raw conference xml data from the server, but one thing that I have learnt from conferences is that the Wi-Fi, always, without exceptions - suck. So my plan was to download the xml files, deploy them with the application and then read them from disk… this is my story.</p>
<p>The working title was actually “Allowing Windows 8 Metro applications to access files”, but I think that this one has more <em>Omph!</em> to it.</p>
<h2>Someone moved my cheese!</h2>
<p>If this was a <em>normal</em> application and I wanted to load a xml file from disk, I would probably do something like this. </p>
<pre class="brush: csharp; ruler: true; gutter: false;">XDocument xDocument = null;
using(var fileStream = File.OpenRead(@&quot;C:\data.xml&quot;))
{
    xDocument = XDocument.Load(fileStream);
} </pre>
<p>But .NET Framework 4.5 and WinRT is something new and really different. Reading files from disk just are not what it used to be. Just start to write <em>System.IO.</em> and you get – well, not much. </p>
<p>With WinRT, any operation that potentially can run longer than 50 ms has been converted to an async method. So, when it comes to reading a file you get a bunch of them. After some frantic googling and experimentation (without ReSharper and with an American keyboard) I managed to create this async file reading method. </p>
<pre class="brush: csharp; ruler: true; gutter: false;">private async Task&lt;XDocument&gt; ReadFileAsync(string fileName)
{
    var file = await KnownFolders.DocumentsLibrary.GetFileAsync(fileName);
    var readable = await file.OpenAsync(FileAccessMode.Read);
    uint size = (uint)readable.Size - 1;
    var stream = readable.GetInputStreamAt(0);
    var reader = new DataReader(stream);
    await reader.LoadAsync(size);
    var result = reader.ReadString(size);
    return XDocument.Parse(result);
}</pre>
<p>Not quite as streamlined is it? I don’t know about you, but when I look at this, I certainly feel that I have a lot of new stuff to learn. So, did it work?</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/sad_panda1.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="Sad panda" border="0" alt="Sad panda" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/sad_panda_thumb1.png" width="240" height="226" /></a></p>
<p>No. It did not.</p>
<h2>May I <u>please</u> access a file?</h2>
<p>To be a little more precise, nothing happened at all. Well, something did happen. An exception was thrown when I tried to read a file. But since Visual Studio 2011 is not by default set to always break for any thrown CLR exception I only got a line in my output window. With hindsight I probably should have looked there directly, but I didn’t. So I noticed this after quite some time.</p>
<pre class="brush: plain; ruler: true; gutter: false;">WinRT information: Access to this location requires a corresponding capability.
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll</pre>
<p>What it basically means is that you need to ask nicely before accessing any file. Also, you need to specify which kind of files you want to access and where you would like to access them. You can do this by opening your <em>Package.appxmanifest</em> found in your solution directory. </p>
<p>Since I had placed my xml files in “My Documents”, I first needed to add the capability to read from that folder. (click on the image to see a bigger version)</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/01.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Step 1" border="0" alt="Step 1" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/01_thumb.png" width="649" height="300" /></a></p>
<p>The next step was to declare my application association with xml files. In the tab <em>Declarations</em> you first chose to add <em>File Type Associations</em>. </p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/02.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Step 2" border="0" alt="Step 2" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/02_thumb.png" width="648" height="300" /></a></p>
<p>Now you need to specify that it is a xml file that you want to read.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/03.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Step 3" border="0" alt="Step 3" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/03_thumb.png" width="648" height="300" /></a></p>
<p>You can enter any name that you want and as file type I just entered “.xml”. Pressed F5 and launched my application. So did it work?</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/track-page.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="Track page" border="0" alt="Track page" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/track-page_thumb.png" width="318" height="179" /></a></p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/session-page.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="Session page" border="0" alt="Session page" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/session-page_thumb.png" width="317" height="179" /></a></p>
<p>Yes. Yes it did. </p>
<h2>To be perfectly honest</h2>
<p>I’m not still not happy with my lack of understanding with how file access actually works. Right now it just seems overly complex to me. Important to note is that both Windows 8 Metro application development and WinRT is in an extremely early stage. A lot can still change.</p>
<p>Also - thanks to <a href="http://blog.jayway.com/author/hakanreis/" target="_blank">Håkan</a> that helped me out with the application design. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/12/in-the-async-world-no-one-can-hear-you-scream/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WP7 getting started (6) &#8211; Make your application come alive</title>
		<link>http://blog.jayway.com/2011/11/16/wp7-getting-started-6-make-your-application-come-alive/</link>
		<comments>http://blog.jayway.com/2011/11/16/wp7-getting-started-6-make-your-application-come-alive/#comments</comments>
		<pubDate>Wed, 16 Nov 2011 14:36:55 +0000</pubDate>
		<dc:creator>Anders Poulsen</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10894</guid>
		<description><![CDATA[This is the fifth in a series of blog posts describing how to get started with Windows Phone 7 development. It is written based on my own experience getting started with Windows Phone 7 development. The previous entry, where I demonstrated how to use databound controls in xaml based webservice is available here. The purpose of [...]]]></description>
			<content:encoded><![CDATA[<p>This is the fifth in a series of blog posts describing how to get started with Windows Phone 7 development. It is written based on my own experience getting started with Windows Phone 7 development.</p>
<p>The previous entry, where I demonstrated how to use databound controls in xaml based webservice is available <a title="WP7 getting started (5) – Using databound controls" href="http://blog.jayway.com/2011/11/07/wp7-getting-started-5-using-databound-controls-to-display-an-rss-feed/" target="_blank">here</a>.</p>
<p>The purpose of this post is to provide an overview of methods that will allow your application to seem to "run in the background" eventhough Windows Phone doesn't actually allow it.</p>
<p>These methods are not hacks, they are well-documented and intended for the purpose that I describe here. I just couldn't find a good overview for this purpose anywhere else, so I decided to try to summarize the documentation from <a title="msdn.microsoft.com" href="http://msdn.microsoft.com">msdn</a>.</p>
<h2>Overview</h2>
<p>There are a number of techniques that can be used to make your application (seem to) do stuff, eventhough it is in the background:</p>
<ul>
<li>Tiles</li>
<li>Tile schedule</li>
<li>Push notifications</li>
<li>Alarms and reminders</li>
<li>Scheduled tasks</li>
<li>Background audio</li>
<li>Background file transfer</li>
</ul>
<h2>Tiles</h2>
<p>Tiles are the big squares that make up the start-page.</p>
<p><img class="alignnone size-full wp-image-10896" title="live-tiles-150x150" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/live-tiles-150x150.jpg" alt="Example of tiles" width="150" height="150" /></p>
<p>An application can have to kinds of tiles:</p>
<ul>
<li>Application tile<br />
Created by user when he "pins" the application to the start screen.<br />
Each application can have exactly 1 application tile on the start screen.<br />
When the users taps the application tile, the application is launched to the normal startpage.</li>
<li>Secondary tiles<br />
Created in code from the application.<br />
Each application can have any number of secondary tiles.<br />
A secondary tile can act as a deep link into the application, so it can bypass the normal startpage.</li>
</ul>
<div>Tiles have two sides: front and back.</div>
<div><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/tiles-front-and-back.png" rel="lightbox"><img class="alignnone size-full wp-image-10898" title="tiles front and back" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/tiles-front-and-back.png" alt="" width="383" height="300" /></a></div>
<p>If you set one or more of the properties on the back of the tile, Windows Phone will flip back and forth between the front and back of the tile with a nice animation, making your app look alive.</p>
<p>In project settings you can set the title and background image of your application tile. If you want to set the count or any of the back content, you can do this programmatically when the application runs or by editing /Properties/WMAppManifest.xml in your project.</p>
<p>All properties of secondary tiles are set programmatically.</p>
<p>Fore more information on tiles see <a title="Tiles for Windows Phone 7" href="http://msdn.microsoft.com/en-us/library/hh202960(VS.92).aspx" target="_blank">Tiles for Windows Phone 7</a>.</p>
<h2> Tile schedule</h2>
<p>You can create a(ny number of) ShellTileSchedule that will update your application tile or any of your secondary tiles.</p>
<p>The schedule can run once, a number of times or indefinitely.</p>
<p>The schedule can run hourly, daily, weekly or monthly.</p>
<p>When you create the schedule, you supply a RemoteImageUri, from which the phone will attempt to fetch a new background image for the frontpage of the tile.</p>
<p>You can not change anything else on the tile.</p>
<p>For more information on tile schedules see <a title="How to: Schedule Tile Update For Windows Phone" href="http://msdn.microsoft.com/en-us/library/ff769548(VS.92).aspx" target="_blank">How to: Schedule Tile Updates for Windows Phone</a></p>
<h2>Push notifications agents</h2>
<p>Push notifications provide a way for a third party developers to push messages to the phone.</p>
<p>Types of push notifications:</p>
<ul>
<li>Toast<br />
a toast message is shown on the top of the screen. If the user taps the toast, the application is launched.<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/toast.png" rel="lightbox"><img class="alignnone size-full wp-image-10905" title="toast" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/toast.png" alt="" width="618" height="295" /><br />
</a>Toast messages are not shown if the application is running.</li>
<li>Tile<br />
Updates the application tile or any of the secondary tiles, with the supplied values. This could include (but is not limited to) a new count, or urls to new images.</li>
<li>Raw<br />
Raw messages do not in themselves trigger any UI and are only delivered if the application is running.</li>
</ul>
<p>Push notifications cannot start your application or trigger any processing except for download of images for the tiles.</p>
<p>For more information about push notifications see <a title="Push Notifications For Windows Phone" href="http://msdn.microsoft.com/en-us/library/ff402537(VS.92).aspx" target="_blank">Push Notifications for Windows Phone</a></p>
<h2>Alarms and reminders</h2>
<p>By setting alarms and reminders, you can launch the phones default UI for alarm or reminder at a specified time (accuracy &lt; 1 minute).</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/AlarmReminder.png" rel="lightbox"><img class="alignnone size-full wp-image-10982" title="AlarmReminder" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/AlarmReminder.png" alt="" width="654" height="332" /></a></p>
<p>&nbsp;</p>
<p>In short, alarms are meant to be loud and insisting (like an alarm clock) and reminders are more discreet (like the reminder for a calendar appointment).</p>
<p>For more information about alarms and reminders see <a title="Alarms and reminders overview for Windows Phone" href="http://msdn.microsoft.com/en-us/library/hh202946(VS.92).aspx" target="_blank">Alarms and reminders overview for Windows Phone</a></p>
<h2>Background agents</h2>
<h3>Scheduled task</h3>
<p>Scheduled tasks associated to your application, allow you to execute code eventhough your application is not running. Scheduled tasks cannot have UI or launch applications, but may trigger tile update or toast notifications.</p>
<p>Scheduled tasks are restricted by requirements for memory usage, time until completion, available APIs, battery level, device limit on total allowed scheduled tasks etc.</p>
<p>If these restrictions are not met the task will not run or be terminated.</p>
<p>You have the choise between two types of tasks</p>
<ul>
<li>Periodic task<br />
- Runs regularly (every 30 minutes +- 10 minutes)<br />
- May only run for 25 seconds</li>
<li>Ressource intensive task<br />
- Runs when certain conditions are met: external power+high battery, wifi, screen lock, no call etc<br />
- May run for 10 minutes</li>
</ul>
<p>Tasks need to be rescheduled by the application every 2 weeks. They cannot reschedule themselves. If a task fails two consecutive times it will be be unscheduled.</p>
<p>The restrictions may cause a scheduled task to never be run.</p>
<p>For more information about scheduled tasks see <a title="Background agents for Windows Phone" href="http://msdn.microsoft.com/en-us/library/hh202961(VS.92).aspx" target="_blank">Background agents for Windows Phone</a>.</p>
<h3>Background audio</h3>
<p>An AudioPlayerAgent is a specialized background agent, that allows you to control playback of local or streamed audio through the Zune Media Queue eventhough your application is not running.</p>
<p>The restrictions listed for scheduled tasks do not apply to AudioPlayerAgents.</p>
<p>For more information about background audio see <a title="Background Audio Overview for Windows Phone" href="http://msdn.microsoft.com/en-us/library/hh394039(VS.92).aspx" target="_blank">Background Audio Overview for Windows Phone</a></p>
<h2>Background file transfer</h2>
<p>Background file transfer allows your application to queue a number of up- or downloads that will be executed in the background, regardless of wether the application is running in the foreground. The system manages the queue and decides wether it will process the queued items.</p>
<p>There are restrictions on the number of requests per application and per device as well as the size of the files.</p>
<p>Upload files must not exceed 5 MB.</p>
<p>Download file size limits range from 20 MB to unlimited.  The limits are determined by the <a href="http://msdn.microsoft.com/en-us/library/microsoft.phone.backgroundtransfer.transferpreferences(VS.92).aspx" target="_blank">TransferPreferences</a> property, which indicates the conditions that should be met, for the transfer to take place. The conditions are a combination of external power and/or wifi connection.</p>
<p>Background file transfers are automatically suspended and resumed based on wether the conditions are met.</p>
<p>For more information about background file transer see <a title="Background File Transfers for Windows Phone" href="http://msdn.microsoft.com/en-us/library/hh202953(VS.92).aspx" target="_blank">Background File Transfers for Windows Phone</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/16/wp7-getting-started-6-make-your-application-come-alive/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Web.config Transformations and XML Namespaces</title>
		<link>http://blog.jayway.com/2011/11/14/web-config-transformations-and-xml-namespaces/</link>
		<comments>http://blog.jayway.com/2011/11/14/web-config-transformations-and-xml-namespaces/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 12:45:15 +0000</pubDate>
		<dc:creator>Mads Troest</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[namespace]]></category>
		<category><![CDATA[NLog]]></category>
		<category><![CDATA[transformation]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[Web.config]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10849</guid>
		<description><![CDATA[In the project I'm currently working on, we use Web.config transformations to adapt a base configuration to a particular deployment environment. I was adding a transformation to adapt our NLog configuration for the various environments, when I ran into a problem. I'd added the following transformation, intended to set the log level to Warning on [...]]]></description>
			<content:encoded><![CDATA[<p>In the project I'm currently working on, we use <a href="http://msdn.microsoft.com/en-us/library/dd465326.aspx" target="_blank">Web.config transformations</a> to adapt a base configuration to a particular deployment environment.</p>
<p>I was adding a transformation to adapt our NLog configuration for the various environments, when I ran into a problem. I'd added the following transformation, intended to set the log level to Warning on the given deloyment:</p>
<pre class="brush: xml;">&lt;nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"&gt;
  &lt;rules&gt;
    &lt;logger name="*" minlevel="Warn"
      xdt:Transform="SetAttributes(minlevel)" xdt:Locator="Match(name)"
    /&gt;
  &lt;/rules&gt;
&lt;/nlog&gt;</pre>
<p>However, the original fragment kept being passed through without modification. I tried various modes of matching (incidentally, the online <a href="http://webconfigtransformationtester.apphb.com/" target="_blank">Web Config Transformation Tester</a> is a good tool for such tinkering with transformations) to no avail, until I decided to try and remove the NLog namespace from the transformation:</p>
<pre class="brush: xml;">&lt;nlog&gt;
  &lt;rules&gt;
    &lt;logger name="*" minlevel="Warn"
      xdt:Transform="SetAttributes(minlevel)" xdt:Locator="Match(name)"
    /&gt;
  &lt;/rules&gt;
&lt;/nlog&gt;</pre>
<p>And lo and behold; it worked.</p>
<p>That could have been the end of it, but I decided to dig a bit deeper, since we have the NLog schema in our solution and properly referencing it allows us to have IntelliSense within the web.config.</p>
<p>Eventually, as an experiment, I tried associating a namespace prefix with the NLog namespace at the top level, and then explicitly qualify the NLog elements with that prefix, rather than relying on specifying a default namespace on the NLog element:</p>
<pre class="brush: xml;">&lt;configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"
  xmlns:nlog="http://www.nlog-project.org/schemas/NLog.xsd"
&gt;

  &lt;nlog:nlog&gt;
    &lt;nlog:rules&gt;
      &lt;nlog:logger name="*" minlevel="Warn"
        xdt:Transform="SetAttributes(minlevel)" xdt:Locator="Match(name)"
      /&gt;
    &lt;/nlog:rules&gt;
  &lt;/nlog:nlog&gt;

&lt;/configuration&gt;</pre>
<p>Success!</p>
<h2>Conclusion</h2>
<p>Explicitly prefixing elements from foreign XML namespaces in config transformations must be described as a workaround, since semantically the first and the third NLog fragments are equivalent.</p>
<p>In spite of this flaw in the web.config transformations implementation, this workaround allows you to get the benefits of IntelliSense and better validation when you have the schema for NLog or any other foreign fragment available.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/14/web-config-transformations-and-xml-namespaces/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WP7 app update and NeutralResourcesLanguage</title>
		<link>http://blog.jayway.com/2011/11/10/wp7-app-update-and-neutralresourceslanguage/</link>
		<comments>http://blog.jayway.com/2011/11/10/wp7-app-update-and-neutralresourceslanguage/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 19:23:24 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[marketplace]]></category>
		<category><![CDATA[windows phone]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10846</guid>
		<description><![CDATA[The Windows Phone Marketplace was updated with new features in July 2011, one has to do with default language. The previous process to submit an app required you to define the default language when submitting the app, the new version checks the default language in the uploaded xap. The problem An app created before July [...]]]></description>
			<content:encoded><![CDATA[<p>The Windows Phone Marketplace was updated with new features in July 2011, one has to do with default language. The previous process to submit an app required you to define the default language when submitting the app, the new version checks the default language in the uploaded xap.</p>
<h2>The problem</h2>
<p>An app created before July 18th 2011 will not have the AssemblyInfo attribute NeutralResourcesLanguage and submitting an update to this app will give you the error:</p>
<p><font face="Courier New">Error 2003: The [NeutralResourceLanguage] attribute is missing on the entry assembly.</font></p>
<h2>The fix</h2>
<p>So, the fix for this is simple – add the attribute in AssemblyInfo.cs. (can also be done through selecting in a drop down in app properties)</p>
<p><font face="Courier New">[assembly: NeutralResourcesLanguage(&quot;en-us&quot;)]</font></p>
<h2>The quirk</h2>
<p>English it not always English. There is something called location groups. If you’re lucky – you’ll now pass through submission. If you’re not, you’ll end up with:</p>
<p><font face="Courier New">Error 1047: An update cannot support fewer languages than the previous app instance supported.</font></p>
<p>Whoah, what is this? For me, this was because I had stated the language as <strong>English (International)</strong> when submitting the first time. The rules are:</p>
<table border="0" cellspacing="0" cellpadding="5" width="600">
<tbody>
<tr>
<td valign="top" width="300"><strong>Stated on first submit</strong></td>
<td valign="top" width="300"><strong>Needed in AssemblyInfo.cs</strong></td>
</tr>
<tr>
<td valign="top" width="300">English (International)</td>
<td valign="top" width="300">“en”</td>
</tr>
<tr>
<td valign="top" width="300">English</td>
<td valign="top" width="300">“en-us” or “en-ca”</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>I learned this from the MSDN forum page <a href="http://http://forums.create.msdn.com/forums/t/87638.aspx">helpful tips on language processes during app submission</a>. To quote: <em>If the parent instance was marked as “English (International)”, you need to use [NeutralResourcesLanguage(“en”)], if it was “English”, use [NeutralResourcesLanguage(“en-US”)] or [NeutralResourcesLanguage(“en-CA”)], in other cases use two-letter language name.</em></p>
<h2>Summary</h2>
<p>My final statement ended up as:</p>
<p><font face="Courier New">[assembly: NeutralResourcesLanguage(&quot;en-us&quot;)]</font></p>
<p>This bit me when submitting updates – I really hope this helps you avoid or find the problem quickly <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/wlEmoticon-smile.png" /></p>
<p>Bye!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/10/wp7-app-update-and-neutralresourceslanguage/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WP7 getting started (5) &#8211; Using databound controls</title>
		<link>http://blog.jayway.com/2011/11/07/wp7-getting-started-5-using-databound-controls-to-display-an-rss-feed/</link>
		<comments>http://blog.jayway.com/2011/11/07/wp7-getting-started-5-using-databound-controls-to-display-an-rss-feed/#comments</comments>
		<pubDate>Mon, 07 Nov 2011 08:40:17 +0000</pubDate>
		<dc:creator>Anders Poulsen</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10784</guid>
		<description><![CDATA[This is the fifth in a series of blog posts describing how to get started with Windows Phone 7 development. It is written based on my own experience getting started with Windows Phone 7 development. The previous entry, where I demonstrated how to retrieve and data from a REST based webservice is available here. In that [...]]]></description>
			<content:encoded><![CDATA[<p>This is the fifth in a series of blog posts describing how to get started with Windows Phone 7 development. It is written based on my own experience getting started with Windows Phone 7 development.</p>
<p>The previous entry, where I demonstrated how to retrieve and data from a REST based webservice is available <a title="WP7 Getting started (4) – Displaying data from webservice" href="http://blog.jayway.com/2011/11/03/getting-started-with-windows-phone-7-development-4-displaying-data-from-webservice/">here</a>.</p>
<p>In that blog post I created a fairly naive application, which retrieves som Json data and manually assigns values to some labels on screen.</p>
<p>In this post I will demonstrate how to use Visual Studios databound application template to create an application, that can display the contents of an RSS feed.</p>
<h2>Background</h2>
<p>If, like me, you suddenly have a profound interest in the subject of having twins, you might create an application that displays all the latest stories from <a href="http://www.having-twins.com/">http://www.having-twins.com/</a>.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/ApplicationIdea.png" rel="lightbox"><img class="alignnone size-full wp-image-10821" title="ApplicationIdea" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/ApplicationIdea.png" alt="" width="600" height="377" /></a></p>
<p>A more likely example could be that you have an existing website/community or similar and would like to create a simple mobile app from it. You could then create an RSS feed on your site and then create an RSS driven application.</p>
<p>Fortunately for the lazy programmer, Microsoft has created a couple of project templates, that make it simple to get started.</p>
<h2>Simple Datebound Application</h2>
<p>Since this is going to be an app that displays a list of news entries drawn from a single source, I will use the template "Windows Phone Databound Application".</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/ProjectType.png" rel="lightbox"><img class="alignnone size-full wp-image-10786" title="The &quot;Databound Application&quot; project type" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/ProjectType.png" alt="" width="600" /></a></p>
<p>Lets examine the project that was created for us. The main application screen has the basic Windows Phone 7 application layout, with the top third of the screen reserved for application and page name, and below there is a list of items, each with a title and a summary. When the users taps on an item, he is taken to the details screen.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/CompleteApplicationpng.png" rel="lightbox"><img class="alignnone size-medium wp-image-10792" title="CompleteApplicationpng" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/CompleteApplicationpng-300x199.png" alt="" width="300" height="199" /></a></p>
<h3>Design datasource</h3>
<p>First thing you might notice is, that the design view of the template application is filled with example data already:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/Example-of-design-data.png" rel="lightbox"><img class="alignnone size-medium wp-image-10791" title="Example of design data" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/Example-of-design-data-182x300.png" alt="" width="182" height="300" /></a></p>
<p>Now, where did that come from? Well, if we examine the xaml for the view, we'll find that Visual Studio has added a d:DataContext declaration, that points to the file MainViewModelSampleData.</p>
<pre>&lt;phone:PhoneApplicationPage
    (...)
    d:DataContext="{d:DesignData SampleData/MainViewModelSampleData.xaml}"
    (...)
&gt;</pre>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/Illustration-of-MainViewModelSampleData1.png" rel="lightbox"><img class="alignnone size-full wp-image-10800" title="Illustration of MainViewModelSampleData" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/Illustration-of-MainViewModelSampleData1.png" alt="" width="600" height="232" /></a></p>
<p>This sample data corresponds to the example viewmodels MainViewModel and MainViewModel.Items.<br />
Using this metod you can define your own example data or use the autogenerated data to see what your views will look like when you design them in Visual Studio or Expression Blend. Expression blend even has the ability to generate data for you, once you have defined your custom ViewModel.</p>
<p>Secondly, the controls are bound to properties in the datamodel using standard xaml-based databinding syntax {Binding PropertyName}.</p>
<pre>    &lt;!--Data context is set to sample data above and LayoutRoot contains the root grid where all other page content is placed--&gt;
    &lt;Grid x:Name="LayoutRoot"&gt;
        (...)
        &lt;Grid&gt;
            &lt;ListBox ItemsSource="{Binding Items}"&gt;
                &lt;ListBox.ItemTemplate&gt;
                    &lt;DataTemplate&gt;
                      &lt;StackPanel&gt;
                          &lt;TextBlock Text="{Binding LineOne}" TextWrapping="NoWrap" /&gt;
                          &lt;TextBlock Text="{Binding LineTwo}" TextWrapping="NoWrap" /&gt;
                      &lt;/StackPanel&gt;
                    &lt;/DataTemplate&gt;
                &lt;/ListBox.ItemTemplate&gt;
            &lt;/ListBox&gt;
        &lt;/Grid&gt;
    &lt;/Grid&gt;</pre>
<p>Notice that the ListBox binds to Items, which is an ObservableCollection&lt;ItemViewModel&gt; on MainViewModel and each &lt;TextBlock&gt; within the &lt;ListBox.ItemTemplate&gt; then binds to properties LineOne and LineTwo on the ItemViewModel.</p>
<h3>Runtime datasource</h3>
<p>When you run your application, you'll notice that the running app displays another set of  data:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/Example-of-runtime-data.png" rel="lightbox"><img class="alignnone size-medium wp-image-10804" title="Example of runtime data" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/Example-of-runtime-data-182x300.png" alt="" width="182" height="300" /></a></p>
<p>The "runtime one", "runtime two", etc data is default template data generated in MainViewModel.LoadData, which is called from MainPage.MainPage_Loaded.</p>
<pre>/// &lt;summary&gt;
/// Creates and adds a few ItemViewModel objects into the Items collection.
/// &lt;/summary&gt;
public void LoadData()
{
    // Sample data; replace with real data
    this.Items.Add(new ItemViewModel() { LineOne = "runtime one", LineTwo = "Maecenas praesent accumsan bibendum", LineThree = "Facilisi faucibus habitant inceptos interdum lobortis nascetur pharetra placerat pulvinar sagittis senectus sociosqu" });
    (...)
    this.Items.Add(new ItemViewModel() { LineOne = "runtime sixteen", LineTwo = "Nascetur pharetra placerat pulvinar", LineThree = "Pulvinar sagittis senectus sociosqu suscipit torquent ultrices vehicula volutpat maecenas praesent accumsan bibendum" });

    this.IsDataLoaded = true;
}</pre>
<p>To keep this example as simple as possible, the only thing I'll change is which data we put into the items collection, so to download the RSS feed and use that data instead, the above lines are changed into.</p>
<pre>/// &lt;summary&gt;
/// Creates and adds a few ItemViewModel objects into the Items collection.
/// &lt;/summary&gt;
public void LoadData()
{
    var webClient = new WebClient();
    webClient.DownloadStringCompleted += webClient_DownloadStringCompleted;
    webClient.DownloadStringAsync(new Uri("http://www.having-twins.com/Twins.xml"));
}

private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null) return;

    var reader = XmlReader.Create(new StringReader(e.Result));
    SyndicationFeed feed = SyndicationFeed.Load(reader);

    foreach (var item in feed.Items)
    {
        Items.Add(new ItemViewModel(){LineOne = item.Title.Text.Trim(), LineTwo = item.Summary.Text.Trim()});
    }
    this.IsDataLoaded = true;
}</pre>
<p>This code downloads the rss-feed from http://www.having-twins.com/Twins.xml, parses it using SyndicationFeed (you must manually reference it from \Program Files\Microsoft SDKs\Silverlight\v4.0\Libraries\Client\System.ServiceModel.Syndication.dll) and uses the Title and Summary texts from that feed to populate the LineOne and LineTwo properties of the ItemViewModel.</p>
<p>When you run the app in the emulator, you'll get a nice view like this (you'll need to set TextWrapping to NoWrap on the TextBlocks):</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/TwInfoMainPage.png" rel="lightbox"><img class="alignnone size-medium wp-image-10809" title="TwInfoMainPage" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/TwInfoMainPage-182x300.png" alt="" width="182" height="300" /></a></p>
<h2>Starting a browser</h2>
<p>Finally, the feed from having-twins.com provides a link to the article and not the actual article, so when you click on an item in the list, we should start a webbrowser and go directly to the article on the website.</p>
<p>First we need to add a property to store the item url on the ItemViewModel:</p>
<pre>private Uri _uri;
public Uri Uri
{
    get
    {
        return _uri;
    }
    set
    {
        if (value != _uri)
        {
            _uri = value;
            NotifyPropertyChanged("Uri");
        }
    }
}</pre>
<p>Next we need to extract the url and store it per item, so we'll change the line of code in webClient_DownloadStringCompleted to:</p>
<pre>Items.Add(new ItemViewModel(){LineOne = item.Title.Text.Trim(), LineTwo = item.Summary.Text.Trim(), Uri = item.Links.First().Uri});</pre>
<p>The final step is to start the webbrowser. This is done in MainListBox_SelectionChanged, where we replace the code that opens the details view:</p>
<pre>// Navigate to the new page
NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative));</pre>
<p>with code that opens a browser:</p>
<pre>var webBrowserTask = new WebBrowserTask {Uri = ((ItemViewModel) MainListBox.SelectedItem).Uri};
webBrowserTask.Show();</pre>
<p>So now, when you tap on an item in the list, the browser will open and go directly to the article mentioned in the rss-feed.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/BrowserLaunched.png" rel="lightbox"><img class="alignnone size-full wp-image-10816" title="BrowserLaunched" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/BrowserLaunched.png" alt="" width="597" height="334" /></a></p>
<p>Naturally, you could error handling, offline caching of content, splash screen etc. but that is beyond the scope of this demonstration.</p>
<p>This concludes this example of how to use the standard databound template to create an app that displays latest news (in form of an rss-feed) from a website.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/07/wp7-getting-started-5-using-databound-controls-to-display-an-rss-feed/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>WP7 Getting started (4) &#8211; Displaying data from webservice</title>
		<link>http://blog.jayway.com/2011/11/03/getting-started-with-windows-phone-7-development-4-displaying-data-from-webservice/</link>
		<comments>http://blog.jayway.com/2011/11/03/getting-started-with-windows-phone-7-development-4-displaying-data-from-webservice/#comments</comments>
		<pubDate>Thu, 03 Nov 2011 14:08:45 +0000</pubDate>
		<dc:creator>Anders Poulsen</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[windows phone 7]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10762</guid>
		<description><![CDATA[This is the fourth in a series of blog posts describing how to get started with Windows Phone 7 development. It is written based on my own experience getting started with Windows Phone 7 development. The previous entry, where I demonstrated how to store and retrieve view states between application deactivation and activation is available [...]]]></description>
			<content:encoded><![CDATA[<p>This is the fourth in a series of blog posts describing how to get started with Windows Phone 7 development. It is written based on my own experience getting started with Windows Phone 7 development.</p>
<p>The previous entry, where I demonstrated how to store and retrieve view states between application deactivation and activation is available <a title="Getting started with Windows Phone 7 development (3) – Lifecycle management" href="http://blog.jayway.com/2011/11/01/getting-started-with-windows-phone-7-development-3-lifecycle-management/">here</a>.</p>
<p>In this blog post I will demonstrate how to fetch data from a simple REST based web service and use it in an application, that many, many people have been waiting for.</p>
<h2>Background</h2>
<p>In Copenhagen there is a famous neon billboard from 1953 showing a hen laying eggs.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/IrmaHønen.jpg" rel="lightbox"><img class="alignnone size-full wp-image-10763" title="IrmaHønen" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/IrmaHønen.jpg" alt="" width="354" height="224" /></a></p>
<p>It just so happens that there is a REST api available, where one can query the status of the egglaying.</p>
<p>If you load</p>
<pre>http://sevengoslings.net/~fangel/hvormangeaeg/eggs_laid/json</pre>
<p>You will get the status in json format</p>
<pre>{"eggs":105300654,"on":902667014,"currently_laying_eggs":false}</pre>
<p>When I made the request,  the hen had been working for 902667014 seconds, it had layd 105.300.654 eggs and was not currently laying any eggs (it was not dark outsite).</p>
<p>The status is also available in xml, php-serialized and LOL (don't ask). The complete developers api is documented at <a href="http://sevengoslings.net/~fangel/hvormangeaeg/developers">http://sevengoslings.net/~fangel/hvormangeaeg/developers</a>.</p>
<h2> The application</h2>
<p>In the following, I'm assuming that you have either read the previous posts or have sufficient knowledge of how to create a new Windows Phone 7 based application.</p>
<p>I have created a new Windows Phone project using the simple "Windows Phone Application" template.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/Project-type.png" rel="lightbox"><img class="alignnone size-full wp-image-10767" title="Project type" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/Project-type.png" alt="" width="600" /></a></p>
<p>In the grid called ContentPanel, I've added a few TextBlocks to display the status and Rectangles to serve as dividers between the TextBlocks.</p>
<pre>&lt;!--ContentPanel - place additional content here--&gt;
&lt;Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"&gt;
    &lt;Grid.RowDefinitions&gt;
        &lt;RowDefinition Height="Auto"&gt;&lt;/RowDefinition&gt;
        &lt;RowDefinition Height="20"&gt;&lt;/RowDefinition&gt;
        &lt;RowDefinition Height="Auto"&gt;&lt;/RowDefinition&gt;
        &lt;RowDefinition Height="20"&gt;&lt;/RowDefinition&gt;
        &lt;RowDefinition Height="Auto"&gt;&lt;/RowDefinition&gt;
    &lt;/Grid.RowDefinitions&gt;
    &lt;TextBlock Grid.Row="0" x:Name="txbHenAge" TextWrapping="Wrap"&gt;&lt;/TextBlock&gt;
    &lt;Rectangle Grid.Row="1" Width="300" Height="2" Stroke="White" Fill="White"&gt;&lt;/Rectangle&gt;
    &lt;TextBlock Grid.Row="2" x:Name="txbEggCount" TextWrapping="Wrap"&gt;&lt;/TextBlock&gt;
    &lt;Rectangle Grid.Row="3" Width="300" Height="2" Stroke="White" Fill="White"&gt;&lt;/Rectangle&gt;
    &lt;TextBlock Grid.Row="4" x:Name="txbEggLayingStatus" TextWrapping="Wrap"&gt;&lt;/TextBlock&gt;
&lt;/Grid&gt;</pre>
<p>To retrieve the egg-laying status, I'll use the WebClient class, which uses a simple event -based system to make requests and receive responses. For more details on how to use the WebClient class, you might check out <a href="http://create.msdn.com/en-US/education/quickstarts/Accessing_a_REST_Web_Service" target="_blank">Accessing a REST web service quick start on create.msdn.com</a>.</p>
<h2>Sending the request</h2>
<p>In my page constructor I'll add:</p>
<pre>_webClient = new WebClient();
_webClient.DownloadStringCompleted += _webClient_DownloadStringCompleted;
_webClient.DownloadStringAsync(new Uri("http://sevengoslings.net/~fangel/hvormangeaeg/eggs_laid/json"));</pre>
<p>First I create a new instance of WebClient. Then I provide a method to handle the DownloadStringCompleted event, and finally I call DownloadStringAsync with the URI that I want to load.</p>
<h2>Handling the response</h2>
<p>In the method handling the DownloadStringCompleted event I have to parse the received Json. For that purpose I'm using <a href="http://json.codeplex.com/" target="_blank">Json.NET</a>.</p>
<p>First I create class to model the data I expect to receive:</p>
<pre>public class IrmaHenStatus
{
    public int eggs { get; set; }
    public long on { get; set; }
    public bool currently_laying_eggs { get; set; }
}</pre>
<p>Then I apply JsonConvert.DeserializeObject to the received Json:</p>
<pre>void _webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    IrmaHenStatus result = JsonConvert.DeserializeObject&lt;IrmaHenStatus&gt;(e.Result);
    ...</pre>
<p>Add a bit of error handling:</p>
<pre>if (e.Error != null)
{
    // Do something meaningfull if the response was not OK</pre>
<p>Add strings and a helper method to turn the number of seconds into human readable format:</p>
<pre>string HenAgeText= "The hen has been laying eggs for {0}.";
string EggCountText = "During that time, the hen has layed {0} eggs.";
string NetworkErrorText = "A network error occured!";
string EggLayingOngoing = "The hen is currently laying eggs";
string EggLayingPaused = "The hen is currently not laying any eggs";</pre>
<pre>private string FormatEggLayingTime(long time)
{
    var seconds = time;
    var elapsedDays = (int) (seconds/(60*60*24));
    seconds = seconds % (60*60*24);

    var elapsedHours = (int) (seconds/(60*60));
    seconds = seconds%(60*60);

    var elapsedMinutes = (int) (seconds/60);
    var elapsedSeconds = seconds%60;

    string returnValue = string.Format("{0} days, {1} hours, {2} minutes and {3} seconds", elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
    return returnValue;
}</pre>
<p>And we are now ready to update the UI</p>
<pre>txbEggCount.Text = string.Format(EggCountText, result.eggs.ToString("N"));
txbHenAge.Text = string.Format(HenAgeText, FormatEggLayingTime(result.on));
txbEggLayingStatus.Text = result.currently_laying_eggs ? EggLayingOngoing : EggLayingPaused;</pre>
<p>The final result may not be very impressive, but it does illustrate quite nicely how an app can display data retrieved from a REST based webservice.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/AppWithStatus.png" rel="lightbox"><img class="alignnone size-full wp-image-10772" title="AppWithStatus" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/AppWithStatus.png" alt="" width="417" height="746" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/03/getting-started-with-windows-phone-7-development-4-displaying-data-from-webservice/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>WP7 Marketplace Beta &#8211; new app downloadable delay</title>
		<link>http://blog.jayway.com/2011/11/03/wp7-marketplace-beta-new-app-downloadable-delay/</link>
		<comments>http://blog.jayway.com/2011/11/03/wp7-marketplace-beta-new-app-downloadable-delay/#comments</comments>
		<pubDate>Thu, 03 Nov 2011 07:06:47 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[marketplace]]></category>
		<category><![CDATA[windows phone]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10754</guid>
		<description><![CDATA[Have you seen the new (since fall 2011) ways to publish a Windows Phone app to Marketplace? In addition to regular publishing, you can now publish as private beta or targeted. Neither will make the app discoverable in the Marketplace, Beta is time limited and does not include the full certification requirements. MSDN has a [...]]]></description>
			<content:encoded><![CDATA[<p>Have you seen the new (since fall 2011) ways to publish a Windows Phone app to Marketplace? In addition to regular publishing, you can now publish as <em>private beta </em>or <em>targeted</em>. Neither will make the app discoverable in the Marketplace, Beta is time limited and does not include the full certification requirements. MSDN has a really good <a href="http://http://msdn.microsoft.com/en-us/library/hh334586(v=VS.92).aspx">Marketplace submission comparison: Application Distribution Options.</a></p>
<p>Now, onto the topic of the hour: <strong>Beta submission</strong>.</p>
<h2></h2>
<h2>Empirical timing results</h2>
<p>I have during the past months submitted numerous apps to the Marketplace as beta – and come to the conclusion: (this probably will just be true for the near future AND the region I’m in – Sweden)</p>
<p>1) Beta submission takes <strong>4 hours </strong>to complete – the app then becomes “published”</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/image.png" rel="lightbox"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/image_thumb.png" width="575" height="291" /></a></p>
<p>2) It takes another <strong>8 hours</strong> before the app becomes available for download!</p>
<h2>Error when trying to download right after submission completed</h2>
<p>Before the 8 hours, hitting the deep link gives Marketplace error: 805a0194. An explanation of the error can be found in this <a href="http://stackoverflow.com/questions/7777822/marketplace-windows-phone-beta-test-error-code-805a0194/7777955#7777955">StackOverflow response</a>: it’s a 404 – not found.</p>
<p>Why is it like this? I don’t know. Probably propagation of the xap package onto download servers. Annoying – but more bearable once you see the system in it.</p>
<p>Go publish those apps!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/03/wp7-marketplace-beta-new-app-downloadable-delay/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>WP7 getting started (3) &#8211; Lifecycle management</title>
		<link>http://blog.jayway.com/2011/11/01/getting-started-with-windows-phone-7-development-3-lifecycle-management/</link>
		<comments>http://blog.jayway.com/2011/11/01/getting-started-with-windows-phone-7-development-3-lifecycle-management/#comments</comments>
		<pubDate>Tue, 01 Nov 2011 09:44:28 +0000</pubDate>
		<dc:creator>Anders Poulsen</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[windows phone 7]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10702</guid>
		<description><![CDATA[This is the third in a series of blog posts describing how to get started with Windows Phone 7 development. It is written based on my own experience getting started with Windows Phone 7 development. The previous entry, where I created a simple app for collecting feedback on how a presentation went is available here. Application [...]]]></description>
			<content:encoded><![CDATA[<p>This is the third in a series of blog posts describing how to get started with Windows Phone 7 development. It is written based on my own experience getting started with Windows Phone 7 development.</p>
<p>The previous entry, where I created a simple app for collecting feedback on how a presentation went is available <a title="Getting started with Windows Phone 7 development (2)" href="http://blog.jayway.com/2011/10/31/getting-started-with-windows-phone-7-development-2/">here</a>.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/CompleteFinalFirstApp.png" rel="lightbox"><img class="alignnone size-medium wp-image-10703" title="CompleteFinalFirstApp" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/CompleteFinalFirstApp-300x167.png" alt="" width="300" height="167" /></a></p>
<h2>Application life cycle</h2>
<p>An obvious problem with the app created in the previous post is that it reset the counters every time the app is started.</p>
<p>This means that the counters are reset if the phone receives an incoming call, if it goes to sleep or if somebody accidentally presses the Start button. This is of course very inconvenient.</p>
<p>To address this problem, we need to look at application life cycle management. Here is <a href="http://create.msdn.com/en-US/education/quickstarts/Running_your_App_in_the_Background_(Tombstoning)" target="_blank">a good throrough description</a>.</p>
<p>The issue at hand is called tombstoning. Since Windows Phone doesn't allow apps to run in the background, our application process gets killed, when the application doesn't occupy the UI.</p>
<p>The user can then either start a new instance of the application (in which case the counters SHOULD be reset) or navigate "back" into the application (in which case the counters should NOT be reset).</p>
<p>So to resume at the point, where we left off, we have to save our state information, so it can be reloaded if the application gets reactivated.</p>
<p>There are two ways to save information, application state and page state.</p>
<h3>Application state</h3>
<p>Application state is the state of the application that is not related to a specific page in the application. It could e.g. be login information.</p>
<p>The application has a set of events that can be used to handle/save/restore application state:</p>
<pre>// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}

// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}

// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}

// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}</pre>
<h3>Page state</h3>
<p>Page state is the state of a single page, typically UI-related such as content of textboxes or scroll-position of a scroll view.</p>
<pre>protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    // this.State is a dictionary, where one can store page state information
    base.OnNavigatedTo(e);
}</pre>
<pre>protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    // this.State is a dictionary, containing previously stored page state information
    base.OnNavigatedFrom(e);
}</pre>
<p>These methods are called every time a page is navigated to or from, so if the application gets deactivated, you can store page state information in OnNavigatedFrom and restore it in OnNavigatedTo.</p>
<h2> Using Page state to save counters</h2>
<p>In this case the counters are page-specific, so they will be treated as page-state information for now.</p>
<p>The following code will save the counter values during deactivation and restore them during reactivation. You might notice that there is room for some improvement here, if one were to refactor the code a bit, but I choose not to in order to keep the example as simple and illustrative as possible.</p>
<pre>private const string StateHappyCount = "happyCount";
private const string StateNeitherCount = "neitherCount";
private const string StateSadCount = "sadCount";</pre>
<pre>protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    _happyCount = (int)(State.ContainsKey(StateHappyCount) ? State[StateHappyCount] : 0);
    _neitherCount = (int)(State.ContainsKey(StateNeitherCount) ? State[StateNeitherCount] : 0);
    _sadCount = (int)(State.ContainsKey(StateSadCount) ? State[StateSadCount] : 0);

    base.OnNavigatedTo(e);
}

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    State[StateHappyCount] = _happyCount;
    State[StateNeitherCount] = _neitherCount;
    State[StateSadCount] = _sadCount;

    base.OnNavigatedFrom(e);
}</pre>
<p>When you test the application, be sure to distinguish between wether the app is deactivated or closed and wether it is reactivated or launched.</p>
<p>An app is closed, when the user backs out from the main screen with the back button. Otherwise it is deactivated (tombstoned).</p>
<p>An app is launched, when it is started from the start screen (regardless of wether it was previously deactivated), otherwise it is activated. The State dictionary is empty, when an application is launched.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/01/getting-started-with-windows-phone-7-development-3-lifecycle-management/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>WP7 getting started (2) &#8211; A simple application</title>
		<link>http://blog.jayway.com/2011/10/31/getting-started-with-windows-phone-7-development-2/</link>
		<comments>http://blog.jayway.com/2011/10/31/getting-started-with-windows-phone-7-development-2/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 13:10:27 +0000</pubDate>
		<dc:creator>Anders Poulsen</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[windows phone 7]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10669</guid>
		<description><![CDATA[This is the second in a series of blog posts describing how to get started with Windows Phone 7 development. It is written based on my own experience getting started with Windows Phone 7 development. The previous entry about installing the tools is available here.  Idea for an app The app I'd like to create [...]]]></description>
			<content:encoded><![CDATA[<p>This is the second in a series of blog posts describing how to get started with Windows Phone 7 development. It is written based on my own experience getting started with Windows Phone 7 development.</p>
<p>The previous entry about installing the tools is available <a title="Getting started with Windows Phone 7 development (1)" href="http://blog.jayway.com/2011/10/31/getting-started-with-windows-phone-7-development-1/">here</a>.</p>
<h2> Idea for an app</h2>
<p>The app I'd like to create is a simple tool, that one might use if one was conducting a course on, say, Windows Phone development.</p>
<p>The idea is that as people leave the room, the can indicate if they were satisfied with the presentation they just witnessed by simple pressing a red or green smiley on the screen of a phone, held by a person in the doorway.</p>
<p>The user interface would look something like this drawing:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/First-scetch.png" rel="lightbox"><img class="alignnone size-medium wp-image-10676" title="First scetch" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/First-scetch-300x187.png" alt="" width="300" height="187" /></a></p>
<p>Below each smiley is a number indicating how many people pressed each smiley.</p>
<h2>Creating the UI</h2>
<p>Unless you are creating games using XNA, you will be creating your userinterface using XAML. If you do not know XAML, then <a href="http://create.msdn.com/en-US/education/quickstarts/Creating_the_Windows_Phone_User_Interface_(XAML)" target="_blank">this is a good introduction to XAML on Windows Phone</a>.</p>
<p>The following is the definition of the UI:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/CompleteFirstAppUI1.png" rel="lightbox"><img class="alignnone size-full wp-image-10685" title="CompleteFirstAppUI" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/CompleteFirstAppUI1.png" alt="" width="650" /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>The top half of the screen is a graphical editor, while the botttom half is the XAML editor.</p>
<p>The UI of this application consists of three buttons filling the entire screen. Each button has a smiley (a character from the windings character set) and a count.</p>
<p>The buttons are arranged using a StackPanel with orientation=Horizontal, so they line up next to each other.</p>
<p>Below is shown the complete XAML code for this application:</p>
<pre>&lt;phone:PhoneApplicationPage
    x:Class="PhoneApp1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="728" d:DesignHeight="480"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Landscape" Orientation="Landscape"
    shell:SystemTray.IsVisible="True"&gt;

    &lt;StackPanel x:Name="TitlePanel" Margin="0,0,0,0" Background="Black" Orientation="Horizontal" &gt;
        &lt;Button Name="btnHappy" Background="Green" BorderBrush="{x:Null}" Padding="0" Width="242" Tap="btnHappy_Tap"&gt;
            &lt;StackPanel OpacityMask="Black"&gt;
                &lt;TextBlock Text="J" FontFamily="Wingdings" FontSize="200" /&gt;
                &lt;TextBlock Name="txtHappyCount" TextAlignment="Center" /&gt;
            &lt;/StackPanel&gt;
        &lt;/Button&gt;
        &lt;Button Name="btnNeither"  Background="Orange" BorderBrush="{x:Null}" Padding="0" Width="242" Tap="btnNeither_Tap"&gt;
            &lt;StackPanel OpacityMask="Black"&gt;
                &lt;TextBlock Text="K" FontFamily="Wingdings" FontSize="200" /&gt;
                &lt;TextBlock Name="txtNeitherCount" TextAlignment="Center" /&gt;
            &lt;/StackPanel&gt;
        &lt;/Button&gt;
        &lt;Button Name="btnSad" Background="Red" BorderBrush="{x:Null}" Padding="0" Width="242" Tap="btnSad_Tap"&gt;
            &lt;StackPanel OpacityMask="Black"&gt;
                &lt;TextBlock Text="L" FontFamily="Wingdings" FontSize="200" /&gt;
                &lt;TextBlock Name="txtSadCount" TextAlignment="Center" /&gt;
            &lt;/StackPanel&gt;
        &lt;/Button&gt;
    &lt;/StackPanel&gt;
&lt;/phone:PhoneApplicationPage&gt;</pre>
<p>The &lt;phone:PhoneApplicationPage&gt; part of the xaml is standard for a page in a Windows Phone application.</p>
<h2>Coding the functionality</h2>
<p>During initialization, the  counters on the UI should be initialized to 0.</p>
<p>When you click on a button, the Tap event occurs and the method defined on each button is called. The Tap method will increment the tap counter and update the UI. The complete code looks like this:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/FirstApplicationCodeBehind.png" rel="lightbox"><img class="alignnone size-full wp-image-10687" title="FirstApplicationCodeBehind" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/FirstApplicationCodeBehind.png" alt="" width="612" height="727" /></a></p>
<p>(If you're annoyed by the fact that I've only posted a picture of the code, so you cant copy/paste it: It is intentional. I'd like to force you to do a little bit of coding yourself <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h2>Testing the finished app</h2>
<p>Finally, press F5, press the buttons and verify that the counters works like they should.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/CompleteFinalFirstApp.png" rel="lightbox"><img class="alignnone size-full wp-image-10694" title="CompleteFinalFirstApp" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/CompleteFinalFirstApp.png" alt="" width="500" /></a></p>
<p>&nbsp;</p>
<p>The emulator starts with the phone in portrait mode, but you can turn it using the button on the toolbar in the top-right corner:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/TurnToLandscap.png" rel="lightbox"><img class="alignnone size-full wp-image-10695" title="TurnToLandscap" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/TurnToLandscap.png" alt="" width="60" height="57" /></a></p>
<p>You might also notice the strange numbers in the top of the screen:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/DebugInfo.png" rel="lightbox"><img class="alignnone size-full wp-image-10696" title="DebugInfo" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/DebugInfo.png" alt="" width="238" height="52" /></a></p>
<p>These numbers are performance metrics that would come in handy if you were a game developer. For now, you can just ignore them. They only show up, when the emulator is in debug mode.</p>
<p>That really is all there is to it!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/31/getting-started-with-windows-phone-7-development-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WP7 getting started (1) &#8211; Installing tools</title>
		<link>http://blog.jayway.com/2011/10/31/getting-started-with-windows-phone-7-development-1/</link>
		<comments>http://blog.jayway.com/2011/10/31/getting-started-with-windows-phone-7-development-1/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 09:09:10 +0000</pubDate>
		<dc:creator>Anders Poulsen</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[windows phone 7]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10650</guid>
		<description><![CDATA[This is the first in a series of blog posts describing how to get started with Windows Phone 7 development. It is written based on my own experience getting started with Windows Phone 7 development. The purpose is both to help others get started but also to show how simple it really is, to get [...]]]></description>
			<content:encoded><![CDATA[<p>This is the first in a series of blog posts describing how to get started with Windows Phone 7 development. It is written based on my own experience getting started with Windows Phone 7 development.</p>
<p>The purpose is both to help others get started but also to show how simple it really is, to get started developing for Windows Phone 7.</p>
<h2>Where to find everything</h2>
<p>The best online ressource for all-thing Windows Phone 7 I have found is <a href="http://create.msdn.com" target="_blank">create.msdn.com</a>. Here you'll find everything you need to know/download.</p>
<h2>Install</h2>
<p>First thing you need is to download the SDK: <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=27570" target="_blank">download here</a>. It will install everything you need, including Visual Studio 2010 Express if necessary. NOTE: If you already have Visual Studio 2010 without Service Pack 1, prepare yourself or a looooong installation process. The Service Pack 1 installer goes on for hours with no cpu-load or activity on the harddrive. No, it isn't broken or crashed. It really does work that way! Leave it overnight and you'll be pleasently suprised the next day.</p>
<h3>Confirm that it works</h3>
<p>Now that you've installed the Windows Phone SDK, it is time to spin up the bad boy and see if it works.</p>
<p>Start Visual Studio, select new project</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/New-project.png" rel="lightbox"><img class="alignnone size-medium wp-image-10654" title="New project" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/New-project-300x181.png" alt="" width="300" height="181" /></a></p>
<p>Select the template "Windows Phone Application".</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/Project-type1.png" rel="lightbox"><img class="alignnone size-full wp-image-10659" title="Project type" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/Project-type1.png" alt="" width="600" /></a></p>
<p>Press F5 to start debugging and wait for the emulator to finish loading your app.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/Blank-project-emulator.png" rel="lightbox"><img class="alignnone size-medium wp-image-10663" title="Blank project emulator" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/Blank-project-emulator-167x300.png" alt="" width="167" height="300" /></a></p>
<p>Congratulations. You have now created your first application and started it in the emulator.</p>
<p>You now have all the tools necessary to start coding your very own app.</p>
<h2>Next steps</h2>
<p>You next steps will be to learn more about application development for Windows Phone 7 and think of an actual app to develop.</p>
<p>A good place to start is the <a href="http://create.msdn.com/en-US/education/quickstarts" target="_blank">quickstarts part of create.msdn.com</a>.</p>
<p>One very interesting ressource in my opinion is this documentation on <a href="http://msdn.microsoft.com/en-us/library/hh202915(VS.92).aspx">User Experience Design Guidelines</a>, which will help you ensure your application looks and feels wp7-like.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/31/getting-started-with-windows-phone-7-development-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Implicit styles in Windows Phone 7</title>
		<link>http://blog.jayway.com/2011/10/18/implicit-styles-in-windows-phone-7/</link>
		<comments>http://blog.jayway.com/2011/10/18/implicit-styles-in-windows-phone-7/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 13:56:02 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[blend 4]]></category>
		<category><![CDATA[windows phone]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10574</guid>
		<description><![CDATA[Coming from WPF and Silverlight for the desktop into Silverlight for Windows Phone, which is Silverlight 3, can leave you longing for some features – one that I missed was Implicit Styles. But, with the Mango (7.1) release of WP7 we now have Silverlight 4! What are implicit styles? A style that has a target [...]]]></description>
			<content:encoded><![CDATA[<p>Coming from WPF and Silverlight for the desktop into Silverlight for Windows Phone, which is Silverlight 3, can leave you longing for some features – one that I missed was <strong>Implicit Styles.</strong> But, with the Mango (7.1) release of WP7 we now have Silverlight 4!</p>
<h2>What are implicit styles?</h2>
<p>A style that has a target type but no x:Key is treated as implicit and will be applied to all descendant elements in the visual tree.</p>
<p><img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://t0.gstatic.com/images?q=tbn:ANd9GcTVrpOjk-hFI1bx6K86uENmtTM9dPpFmeHJbrwnKF3WDj8-rLNX" /></p>
<h2>Why should I use an implicit style?</h2>
<p>I think it’s very nice to not have to set the style on each and every control in a section of your app that you want exactly the same look on. Instead just create an implicit style in one of the parent elements and let the good times roll <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/wlEmoticon-smile.png" /></p>
<h2>What does an implicit style look like in XAML?</h2>
<pre class="brush: xml; first-line: 2;">&lt;Grid Grid.Row=&quot;1&quot; VerticalAlignment=&quot;Top&quot;&gt;
    &lt;Grid.RowDefinitions&gt;
        &lt;RowDefinition/&gt;
        &lt;RowDefinition/&gt;
        &lt;RowDefinition/&gt;
    &lt;/Grid.RowDefinitions&gt;
    &lt;Grid.Resources&gt;
        <strong>&lt;Style TargetType=&quot;TextBlock&quot;
               BasedOn=&quot;{StaticResource PhoneTextNormalStyle}&quot;&gt;</strong>
            &lt;Setter Property=&quot;FontSize&quot; Value=&quot;21&quot;/&gt;
            &lt;Setter Property=&quot;Foreground&quot; Value=&quot;Pink&quot;/&gt;
        &lt;/Style&gt;
    &lt;/Grid.Resources&gt;
    &lt;TextBlock Grid.Row=&quot;0&quot; Text=&quot;styles&quot;/&gt;
    &lt;TextBlock Grid.Row=&quot;1&quot; Text=&quot;blend&quot;/&gt;
    &lt;TextBlock Grid.Row=&quot;2&quot; Text=&quot;wow&quot;/&gt;
&lt;/Grid&gt;</pre>
<p>the above XAML will produce:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/image.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/image_thumb.png" width="83" height="106" /></a></p>
<p>But if we change the style to having a key:</p>
<pre class="brush: xml; first-line: 2;">&lt;Style <strong>x:Key=&quot;PinkStyle&quot;</strong> TargetType=&quot;TextBlock&quot;
BasedOn=&quot;{StaticResource PhoneTextNormalStyle}&quot;&gt;</pre>
<p>we instead get:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/image1.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/image_thumb1.png" width="80" height="104" /></a></p>
<p>so – it has to be an “anonymous” style.</p>
<h2>It’s all about looks - applying the style e.v.e.r.y.w.h.e.r.e</h2>
<p>So – what will happen if we put the style in App.xaml? You guessed it – visual tree propagation galore! All your textblocks will get the style.</p>
<pre class="brush: xml; first-line: 2;">&lt;Application.Resources&gt;
    &lt;Style …&gt;
        …
    &lt;/Style&gt;
&lt;/Application.Resources&gt;</pre>
<p>&#160;</p>
<p><img src="http://img.thesun.co.uk/multimedia/archive/00766/SNA2708Z5-682_766323a.jpg" /></p>
<p>There you go! I don’t use this all the time – but it can make the XAML nice and tidy if you are repeating many controls on a page that should share the same looks.</p>
<p>Happy styling!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/18/implicit-styles-in-windows-phone-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Azure Blob Storage &#8211; a simple example</title>
		<link>http://blog.jayway.com/2011/10/18/azure-blob-storage-a-simple-example/</link>
		<comments>http://blog.jayway.com/2011/10/18/azure-blob-storage-a-simple-example/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 05:22:00 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[azure]]></category>

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

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

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

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

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

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

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

		<guid isPermaLink="false">http://blog.jayway.com/?p=10396</guid>
		<description><![CDATA[If your Windows Phone 7 project isn’t starting at all – you’re not even hitting App.xaml.cs, you’ve probably renamed the app project. Fix: Set the startup object on the app project’s properties page In the .csproj file, this corresponds to the SilverlightAppEntry element: &#60;SilverlightAppEntry&#62;PhotoDiary.App&#60;/SilverlightAppEntry&#62; I would call it a bug, that you cannot rename a [...]]]></description>
			<content:encoded><![CDATA[<p>If your Windows Phone 7 project isn’t starting at all – you’re not even hitting App.xaml.cs, you’ve probably renamed the app project.</p>
<p><strong>Fix</strong>: Set the <em>startup object</em> on the app project’s properties page</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/startup_object.jpg" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="startup_object" border="0" alt="startup_object" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/startup_object_thumb.jpg" width="484" height="202" /></a></p>
<p>In the .csproj file, this corresponds to the <em>SilverlightAppEntry </em>element:</p>
<pre class="brush: xml; first-line: 1;">

&lt;SilverlightAppEntry&gt;PhotoDiary.App&lt;/SilverlightAppEntry&gt;

</pre>
<p>I would call it a bug, that you cannot rename a project and have the <em>SilverlightAppEntry</em> update accordingly. But luckily, the work-around is simple. </p>
<p>Have a nice day!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/12/fixing-wp7-app-not-starting-after-project-rename/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Implementing Windows 8 Push Notifications &#8211; An Example</title>
		<link>http://blog.jayway.com/2011/10/12/implementing-windows-8-push-notifications-an-example/</link>
		<comments>http://blog.jayway.com/2011/10/12/implementing-windows-8-push-notifications-an-example/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 08:34:00 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[windows 8]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10069</guid>
		<description><![CDATA[This blog post will explain how you can (using only the raw .NET Framework) implement push notifications for a Windows 8 Metro Application. Windows Push Notifications (WNS) in Windows 8 is actually quite similar to the model we are used to when working with a Windows Phone 7, so anyone of you that worked with [...]]]></description>
			<content:encoded><![CDATA[<p>This blog post will explain how you can (using only the raw .NET Framework) implement push notifications for a Windows 8 Metro Application. Windows Push Notifications (WNS) in Windows 8 is actually quite similar to the model we are used to when working with a Windows Phone 7, so anyone of you that worked with those before will most likely recognize the tutorial coming up in this post.</p>
<p>But before I go any further I would like to thank whoever wrote the official <a href="http://code.msdn.microsoft.com/windowsapps/Push-Notifications-Sample-c6718fa9" target="_blank">Push Notification Sample</a>, it helped me a lot. Also a big thanks to Nick Harris for his <a href="http://www.nickharris.net/2011/09/delivering-notifications-using-windows-azure-and-windows-push-notification-service/" target="_blank">post</a> dealing with push notifications and his and Darren Louie’s <a href="http://channel9.msdn.com/events/BUILD/BUILD2011/SAC-863T" target="_blank">video</a> from BUILD.</p>
<p>In order to get this to work we first need to register our application to receive push notifications. Once that is done we’ll continue with client and then server implementation. In my case I used an Azure server, but you could just as well host this anywhere else. The figure below illustrates the flow when sending a push notification. In this post I’ll show code written for the Win 8 Client and Azure Server.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/Presentation11.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Presentation1" border="0" alt="Presentation1" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/Presentation1_thumb1.png" width="657" height="439" /></a></p>
<p>Let’s get started.</p>
<h2>Register your application to receive push notifications</h2>
<p>The first thing that we need to do, before writing any code, is to register our application to actually be discoverable by WNS. For the moment, the address is <a title="https://manage.dev.live.com/build" href="https://manage.dev.live.com/build">https://manage.dev.live.com/build</a> but I’m guessing that it will change later on.</p>
<p>At the site they have very clear instructions on how to proceed, but I’ll write down the steps in either case. First step is to enter your “Package display name” and “Publisher” to the website. Both can be found by opening your “Package.appxmanifest” file in your Metro client project.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/package.appxmanifest1.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="package.appxmanifest" border="0" alt="package.appxmanifest" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/package.appxmanifest_thumb1.png" width="650" height="271" /></a></p>
<p>And then enter those values in the form found on the website.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/signingupforpush1.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="signingupforpush" border="0" alt="signingupforpush" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/signingupforpush_thumb1.png" width="651" height="206" /></a></p>
<p>After pressing “I accept” you get this information.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/step31.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="step3" border="0" alt="step3" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/step3_thumb1.png" width="653" height="226" /></a></p>
<p>Here you’ll copy the “Package name” and paste it into your “Package.appxmanifest” as seen below. The other two values, “Client secret” and “Package Security Identifier (SID)”, is necessary later on when our server fetches our access token from Live Services.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/step41.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="step4" border="0" alt="step4" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/step4_thumb1.png" width="653" height="274" /></a></p>
<p>Notice that the “Package Family Name” at the bottom also changes. That’s it really, we can now continue with the client implementation.</p>
<h2>Client implementation</h2>
<p>First of all you need to open up a channel in order to receive push notifications. It can be done as in the code sample below.</p>
<pre class="brush: csharp; ruler: true; gutter: false;">PushNotificationChannel pushNotificationChannel;

void OpenChannel()
{
    var operation = PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
    operation.Completed = OnChannelCreationCompleted;
    operation.Start();
}

void OnChannelCreationCompleted(IAsyncOperation&lt;PushNotificationChannel&gt; operation)
{
    if (operation.Status == AsyncStatus.Completed)
    {
        pushNotificationChannel = operation.GetResults();

        // Send these values together with user data to your server of choice
        var notificationUri = pushNotificationChannel.Uri;
        var expirationTime = pushNotificationChannel.ExpirationTime;
    }
}</pre>
<p align="left">If the user accepts push notifications you would typically call <font face="Consolas"><strong>OpenChannel()</strong></font> when the application starts. When opened it will call <font face="Consolas"><strong>OnChannelCreationCompleted(…)</strong></font>. Here you can extract two important properties of the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br241283(v=VS.85).aspx" target="_blank"><font face="Consolas"><strong>PushNotificationChannel</strong></font></a> - <strong><font face="Consolas">Uri</font></strong> and <strong><font face="Consolas">ExpirationTime</font></strong>. Both of these should typically be posted to your server solution of choice. In our case, the Uri will be something like this (shortened).</p>
<pre class="brush: plain; ruler: true; gutter: false;">https://db3.notify.windows.com/?token=AQQAAACL3PSmbrWaRkusVuK…</pre>
<p align="left">I didn’t write any code for actually sending the data to the server. I’ll leave it up to you if would like to do a simple POST, service reference or whatever. When I tried it, I just did a POST using a <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx" target="_blank">HttpWebRequest</a> to a <a href="http://wcf.codeplex.com/" target="_blank">WCF Web API</a> service that I hosted in Azure. In a normal scenario you would typically also post an user id so that you can identify which user the notification Uri belongs to.</p>
<p align="left">Now, in order to actually se what was happening I needed to subscribe to <font face="Consolas"><strong>PushNotificationReceived</strong></font>.</p>
<pre class="brush: csharp; ruler: true; gutter: false;">pushNotificationChannel.PushNotificationReceived += OnPushNotificationReceived;</pre>
<p align="left"><font face="Consolas"><strong>OnPushNotificationReceived</strong></font> don’t actually do anything else than blocking the event from actually reaching the UI. When I tested it I just added a breakpoint to this method so that I could take a peak on whatever came in.</p>
<pre class="brush: csharp; ruler: true; gutter: false;">void OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs e)
{
    string notificationContent = String.Empty;
    switch (e.NotificationType)
    {
        case PushNotificationType.Badge:
            notificationContent = e.BadgeNotification.Content.GetXml();
            break;
        case PushNotificationType.Tile:
            notificationContent = e.TileNotification.Content.GetXml();
            break;
        case PushNotificationType.Toast:
            notificationContent = e.ToastNotification.Content.GetXml();
            break;
    }

    // prevent the notification from being delivered to the UI
    e.Cancel = true;
}</pre>
<p align="left">Note that this will only be triggered if the application is in the foreground, if it’s in the background this method will <u>not</u> be executed.</p>
<p align="left">That’s it for the client implementation; now let’s see what we need to do on the server side.</p>
<h2>Server implementation</h2>
<p>I’ll keep this code raw without wrapping up the logic in any classes. The whole idea with this exercise was for me to understand what was happening and in order to do that I needed to get as close the the raw web requests as possible. I should also mention that I wrote this code on a machine running Windows 7 OS and VS2010.</p>
<h5>Fetching an access token</h5>
<p>First of all I needed to get a hold of my access token, we’ll need it when we push data to the client. From what I understand you should actually cache this value until it expires, but I haven’t been able to figure out where you can see the expiration date… anyway, in order to get your access token you need to do a POST.</p>
<pre class="brush: plain; ruler: true; gutter: false;">POST https://login.live.com/accesstoken.srf HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: login.live.com
Content-Length: 212 

grant_type=client_credentials&amp;client_id=ms-app%3a%2f%2fs-1-15-2-2540850135-1066809635-1827421751-2963426696-2171157241-2579410831-1077576199&amp;client_secret=Si7vgThlGhKrtILSs7BWXPTdE-9yaGGI&amp;scope=notify.windows.com</pre>
<p>As you probably noticed, the <font face="Consolas"><strong>client_id</strong></font> is actually a html encoded version of the “Package Security Identifier (SID)” that we retrieved when registering our application (see images above). The same goes for the <font face="Consolas"><strong>client_secret</strong></font> that is the… well “Client secret”. So, how are we going to express all of this in code?</p>
<pre class="brush: csharp; ruler: true; gutter: false;">

private string GetAccessToken()
{

    string url = &quot;https://login.live.com/accesstoken.srf&quot;;
    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = &quot;POST&quot;;
    request.ContentType = &quot;application/x-www-form-urlencoded&quot;;

    string sid = HttpUtility.UrlEncode(&quot;ms-app://s-1-15-2-2540850135-1066809635-…&quot;);
    string secret = HttpUtility.UrlEncode(&quot;Si7vgThlGhKrtILSs7BWXPTdE-9yaGGI&quot;);
    string content = &quot;grant_type=client_credentials&amp;client_id={0}&amp;client_secret={1}&amp;scope=notify.windows.com&quot;;

    string data = string.Format(content, sid, secret);

    byte[] notificationMessage = Encoding.Default.GetBytes(data);
    request.ContentLength = notificationMessage.Length;

    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(notificationMessage, 0, notificationMessage.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();

    string result;
    using(Stream responseStream = response.GetResponseStream())
    {
        var streamReader = new StreamReader(responseStream);
        result = streamReader.ReadToEnd();
    }

    return result;
}
</pre>
<p>Not pretty - I’m well aware of it. But you should get an idea of how the request is built up to match the POST described above. Important to note is that we need to UrlEncode both our SID and client secret. The result we receive will be.</p>
<pre class="brush: plain; ruler: true; gutter: false;">HTTP/1.1 200 OK
Cache-Control: no-store
Content-Length: 426
Content-Type: application/json
Connection: close 

{
   “access_token”:”EgAfAQMAAAAEg…”,
   “token_type”:”bearer”
}</pre>
<p>The access token is actually much longer, I just shortened it a bit.</p>
<h5>Push data to the client</h5>
<p>Now we can actually push the data to the client, in this example we’ll send a badge update. We will create a web request in a similar manner that we did when we fetched the access token. But this time we will do the following POST.</p>
<pre class="brush: plain; ruler: true; gutter: false;">

POST https://db3.notify.windows.com/?token=AQQAAACL3PSmbrWaRkusVuK…
Content-Type: text/xml
Host: db3.notify.windows.com 

X-WNS-Type: wns/badge
Authorization: Bearer EgAfAQMAAAAEg…
Content-Length: 59 

&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;badge value=&quot;2&quot;/&gt;
</pre>
<p>Two things worth mentioning here. First of all we POST to the <font face="Consolas"><strong>pushUri</strong></font> received from the client. Also, the authorization contains our <font face="Consolas"><strong>accessToken</strong></font>. Then as content we send the information used by the client to actually update its tile. The code I used to accomplish this is below.</p>
<pre class="brush: csharp; ruler: true; gutter: false;">private HttpStatusCode Push(string pushUri, string accessToken)
{
    var subscriptionUri = new Uri(pushUri);

    var request = (HttpWebRequest)WebRequest.Create(subscriptionUri);
    request.Method = &quot;POST&quot;;
    request.ContentType = &quot;text/xml&quot;;
    request.Headers = new WebHeaderCollection();
    request.Headers.Add(&quot;X-WNS-Type&quot;, &quot;wns/badge&quot;);
    request.Headers.Add(&quot;Authorization&quot;,&quot;Bearer &quot; + accessToken);

    string data = &quot;&lt;?xml version='1.0' encoding='utf-8'?&gt;&lt;badge value=\&quot;2\&quot;/&gt;&quot;;

    byte[] notificationMessage = Encoding.Default.GetBytes(data);
    request.ContentLength = notificationMessage.Length;

    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(notificationMessage, 0, notificationMessage.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();

    return response.StatusCode;
}</pre>
<p>The response we would get from this would typically look like.</p>
<pre class="brush: plain; ruler: true; gutter: false;">HTTP/1.1 200 OK
Content-Length: 0
X-WNS-NOTIFICATIONSTATUS: received
X-WNS-MSG-ID: 1AE359FBBE342FFA
X-WNS-DEBUG-TRACE: DB3WNS5044574</pre>
<p>Important to note here is that a successful response only indicates that the message was sent, not that it was actually received by the client. So <strong><font face="Consolas">200 OK</font></strong> only means that the request was processed by WNS. We also receive some debug information that you typically would like to log somewhere if you run into any issues and need support.</p>
<h2>Summary</h2>
<p>That’s it really. The push was received by the client and if I had actually implemented more support for it than a breakpoint it would work as expected. When it comes to finding documentation and online help for any issues or questions I can (while writing this) say that it’s as best sparse. Prepare for a lot of experimentation and guessing as you go along.</p>
<p>If you don’t want to reinvent the wheel as I did, there’s always <a href="http://watwindows8.codeplex.com/" target="_blank">Windows Azure Toolkit for Windows 8</a>. It contains push notifications recipes that makes it really easy to create and send push notifications.</p>
<p>If you would like to learn more about developing Metro applications I recommend at visit to Øredev. It will feature a full day track covering Windows 8 development.</p>
<p><a href="http://oredev.org/2011/windows-8/friday"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Øredev Banner" border="0" alt="728x90[1]" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/728x9011.png" width="659" height="86" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/12/implementing-windows-8-push-notifications-an-example/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Backing up a boot camp partition</title>
		<link>http://blog.jayway.com/2011/10/06/backing-up-a-boot-camp-partition/</link>
		<comments>http://blog.jayway.com/2011/10/06/backing-up-a-boot-camp-partition/#comments</comments>
		<pubDate>Thu, 06 Oct 2011 07:44:22 +0000</pubDate>
		<dc:creator>Anders Poulsen</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[Boot Camp]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10050</guid>
		<description><![CDATA[As a .Net developer using a MacBook Pro as my development machine, I plan on using Windows 7 installed on a Boot Camp partition. That way I can either boot into Windows directly for maximum performance or use VMWare Fusion to get the best of both platforms. After a few initial days of work, I've [...]]]></description>
			<content:encoded><![CDATA[<p>As a .Net developer using a MacBook Pro as my development machine, I plan on using Windows 7 installed on a Boot Camp partition. That way I can either boot into Windows directly for maximum performance or use VMWare Fusion to get the best of both platforms.</p>
<p>After a few initial days of work, I've now installed all the tools I need including but far from limited to VS2010, Resharper, SQL Server Express 2008, NUnit, Git Extensions, Tortoise, Beyond Compare and many more. The project that I will be working on is also configured with locally running IIS7 websites, SQL server databases, certificates and, again, much more.</p>
<p>Now is the time, I think, to do a backup/snapshot/whatever of my Windows partition, because I certainly do not want to go through the entire install/configure process again and my Windows installation is still fairly clean.</p>
<p>I considered using Fusions "snapshot" feature, but VMWare recommends that you <a href="http://kb.vmware.com/kb/1014509" target="_blank">don't use snapshots as a backup strategy</a>.</p>
<p>My first move is to use WinClone to create a backup image of the entire boot camp partition, since Time Machine only backs up my OS X files. The otherwise incredible tool Super Duper will not do the trick here, since it only handles OS X partitions. A caveat here is that WinClone is discontinued from the originator and doesn't support Lion. However, an alternative version that does support Lion can be found <a title="Winclone that supports Lion" href="http://roaringapps.com/app:904" target="_blank">here</a>. I'm currently backing up my Boot Camp partition to a USB drive. Next step will be to test if that backup can actually be used for anything.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/06/backing-up-a-boot-camp-partition/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Debugging Picture Viewer App Connect on WP7</title>
		<link>http://blog.jayway.com/2011/09/28/debugging-picture-viewer-app-connect-on-wp7/</link>
		<comments>http://blog.jayway.com/2011/09/28/debugging-picture-viewer-app-connect-on-wp7/#comments</comments>
		<pubDate>Wed, 28 Sep 2011 13:40:37 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[emulator]]></category>
		<category><![CDATA[windows phone 7]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9768</guid>
		<description><![CDATA[The 7.5 update for Windows Phone 7, codenamed “Mango” has finally been released to the public and adds a ton of new features both for end users as well as developers. One of these features is called App Connect. App Connect can put your app in selected places within the OS and make your app [...]]]></description>
			<content:encoded><![CDATA[<p>The 7.5 update for Windows Phone 7, codenamed “Mango” has finally been released to the public and adds a ton of new features both for end users as well as developers. One of these features is called <em>App Connect</em>. App Connect can put your app in selected places within the OS and make your app more integrated with the system than ever before.</p>
<h2>Extending the Picture Viewer</h2>
<p>Described in the <a href="http://msdn.microsoft.com/en-us/library/ff817010.aspx">MSDN docs here</a>, adding this extension to your app will put it in the list of apps available when looking at pictures.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/IC513020.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="IC513020" border="0" alt="IC513020" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/IC513020_thumb.png" width="639" height="279" /></a></p>
<p>To activate this feature, you need to add the following code to your WMAppManifest.xml, as a child of the &lt;App&gt; element.</p>
<pre class="brush: xml;">

&lt;Extensions&gt;
  &lt;Extension
    ExtensionName=&quot;Photos_Extra_Viewer&quot;
    ConsumerID=&quot;{5B04B775-356B-4AA0-AAF8-6491FFEA5632}&quot;
    TaskID=&quot;_default&quot; /&gt;
&lt;/Extensions&gt;
</pre>
<p>You are then ready to begin receiving pictures to your app. To detect and accept the picture sent to you, you examine the “token” key of the NavigationContext, something like:</p>
<pre class="brush: xml;">IDictionary&lt;string, string&gt; queryStrings =
    this.NavigationContext.QueryString;

Stream photoStream = null;
if (queryStrings.ContainsKey(&quot;token&quot;))
{
    var library = new MediaLibrary();
    Picture picture = library.GetPictureFromToken(queryStrings[&quot;token&quot;]);
    photoStream = picture.GetImage();
}</pre>
<h2>Gotcha 1 - Navigation &amp; the token parameter</h2>
<p>Invoking the app from the Picture Viewer starts your app and navigates to the main page. I think the most common scenario for handling a new picture is to do this on some other page than the main page. In my app that I’m writing (a photo diary app), I directly navigate away from the main page to the details page, thus creating a diary entry for the new picture. This is all easily done, but the quirk comes when navigating back to the main page – the “token” parameter is not cleared! So, my so simple code immediately creates yet another entry and takes me straight back to the details page.</p>
<p><strong>Fix - </strong>Clear the “token” parameter after fetching the picture.</p>
<pre class="brush: xml;">if (queryStrings.ContainsKey(&quot;token&quot;))
{
    var library = new MediaLibrary();
    Picture picture = library.GetPictureFromToken(queryStrings[&quot;token&quot;]);
    photoStream = picture.GetImage();
    <b>queryString.Remove(&quot;token&quot;);</b>
}</pre>
<h2>Gotcha 2 – You can’t debug</h2>
<p>I really hope someone proves me wrong here. Please do <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/wlEmoticon-smile.png" /></p>
<p>The problem:</p>
<blockquote>
<p><strong>emulator </strong>– the picture hub does not exist, neither the camera app</p>
</blockquote>
<blockquote>
<p><strong>device</strong> – you’re now allowed to access the picture hub while connected to the computer (not even the <em>PhotoChooserTask</em> will launch)</p>
</blockquote>
<p>So, how can we debug this? Well, I found a way, a tedious way, but still a way.</p>
<p><strong>Fix 2 - </strong>Put an image in the isolated storage, then feed this image to your code on the main page. </p>
<p>An even more realistic test would be to put the exact same token in the queryStrings collection – but I’m not sure that the app would have privileges to read that picture from the picture hub then.</p>
<p><strong>2a. </strong>Take a snapshot of the isolated storage from the emulator using ISETOOL (<a href="http://msdn.microsoft.com/en-us/library/hh286408(v=vs.92).aspx">Isolated Storage Explorer</a>). The app guid is the “&lt;App ProductID=” from WMAppManifest.xml.</p>
<pre>isetool ts xd &lt;app-guid&gt; .</pre>
<p><strong>2b. </strong>Put an image in the root (or wherever) of the isolated storage file structure</p>
<p><strong>2c. </strong>Restore the snapshot to the emulator (note the folder name here, should the child folder of the folder specified in the “take snapshot command)</p>
<pre>isetool rs xd &lt;app-guid&gt; IsolatedStore</pre>
<p><strong>2d. </strong>Fake AppConnect by reading your file</p>
<p>Here I read the image to a MemoryStream and hand away, to interfere with IsolatedStorage as little as possible. </p>
<p>The high-level code that will not change looks like:</p>
<pre class="brush: csharp;">

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    HandleImageFromAppConnect();
}

private void HandleImageFromAppConnect()
{
    var stream = GetPictureStream();

    if (stream != null)
    {
        ViewModel.HandleAddWithImageInvoked(stream);
        NavigateToDetails();
    }
}
</pre>
<p>And the method to get the stream:</p>
<pre class="brush: csharp;">

private Stream GetPictureStream()
{
    IDictionary&lt;string, string&gt; queryStrings =
        this.NavigationContext.QueryString;

    Stream photoStream = null;
    if (queryStrings.ContainsKey(&quot;token&quot;))
    {
        var library = new MediaLibrary();
        Picture picture = library.GetPictureFromToken(queryStrings[&quot;token&quot;]);
        queryStrings.Remove(&quot;token&quot;);
        photoStream = picture.GetImage();
    }

#if DEBUG
    var isFakingImageFromAppConnect = false;
    if (isFakingImageFromAppConnect)
    {
        MemoryStream manualStream = null;
        using (var store = IsolatedStorageFile.
            GetUserStoreForApplication())
        {
            if (store.FileExists(&quot;/pic.jpg&quot;))
            {
                using (var file = store.OpenFile(&quot;/pic.jpg&quot;, FileMode.Open))
                {
                    var bytes = new byte[file.Length];
                    file.Read(bytes, 0, bytes.Length);
                    manualStream = new MemoryStream(bytes);
                }
            }
        }

        photoStream = manualStream;
    }
#endif

</pre>
<p>That does it – we can debug-stop on the bool, set it, then let the code spin and debug away.</p>
<p>Finally – please – find an easier way and tell me about it <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/wlEmoticon-smile.png" /></p>
<p>Bye for now!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/28/debugging-picture-viewer-app-connect-on-wp7/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Storing double.NaN in a WP7 SQLCE database</title>
		<link>http://blog.jayway.com/2011/09/23/storing-double-nan-in-a-wp7-sqlce-database/</link>
		<comments>http://blog.jayway.com/2011/09/23/storing-double-nan-in-a-wp7-sqlce-database/#comments</comments>
		<pubDate>Fri, 23 Sep 2011 12:02:13 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[sqlce]]></category>
		<category><![CDATA[windows phone 7]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9667</guid>
		<description><![CDATA[Summary double.NaN gives me update issues (ChangeConflictException) in SQL Compact, my fallback was to set the value to zero instead: double.IsNaN(value.Altitude) ? 0 : value.Altitude where ‘Alt’ is the property on my SQLCE entity object. Of course NaN is not the same as zero – but that does not matter to me. Background For a [...]]]></description>
			<content:encoded><![CDATA[<h2>Summary</h2>
<p>double.NaN gives me update issues (ChangeConflictException) in SQL Compact, my fallback was to set the value to zero instead:</p>
<p>double.IsNaN(value.Altitude) ? 0 : value.Altitude</p>
<p>where ‘Alt’ is the property on my SQLCE entity object. Of course NaN is not the same as zero – but that does not matter to me.</p>
<h2>Background</h2>
<p>For a Windows Phone 7 demo app that I’m writing, I’ve been trying to store GPS locations in a SQL Compact database. The GeoCoordinate data type is not supported by SQLCE, so I just took the Latitude, Longitude and Altitude and stored those as doubles in the db. (<a href="http://msdn.microsoft.com/en-us/library/ms172424(SQL.110).aspx">here's a list of SQL Compact supported data types</a>)</p>
<p>And, this was not my first my first version of the app (hence db), so I had to make the properties nullable – otherwise the SQLCE engine cannot add columns for them, <a href="http://msdn.microsoft.com/en-us/library/hh202860(VS.92).aspx">read more about wp7 databases here</a>. I do not think the nullable thing was a part of my problem, but you never know…</p>
<h2>The problem</h2>
<p>So, I happily took data from the GPS in the emulator, got double.NaN as the Altitude and saved that to the DB, all fine so far… Then when updating the database record with other values and trying to save the entry again, I kept getting the error: </p>
<p>ChangeConflictException {&quot;Row not found or changed.&quot;}</p>
<p>Since this problem appeared when I added the Altitude to the database, it was my prime suspect and when I removed it again all was fine.</p>
<p>I’m not sure of the inner workings of this problem, but I suspect it having to do with the fact that when trying to compare a double with double.NaN, VS hints with:</p>
<p><em>A NaN does not compare equal with any floating point number</em></p>
<p>I can perfectly understand that NaN is a special case so I’m fine with sidestepping it like this.</p>
<h2>The fix</h2>
<pre class="brush: csharp;">Alt = double.IsNaN(value.Altitude) ? 0 : value.Altitude;</pre>
<p>The code in the [Table] class:</p>
<pre class="brush: csharp;">private double? _alt;
[Column(CanBeNull = true)]
public double? Alt
{
    get { return _alt; }
    set
    {
        OnPropertyChanging(&quot;Alt&quot;);
        _alt = value;
        OnPropertyChanged(&quot;Alt&quot;);
    }
}

public GeoCoordinate Location
{
    get { return new GeoCoordinate(
        Lat.GetValueOrDefault(),
        Lng.GetValueOrDefault(),
        Alt.GetValueOrDefault()); }
    set
    {
        Lat = value.Latitude;
        Lng = value.Longitude;

        //just setting the double.NaN value, this gave me trouble
        //Alt = value.Altitude;

        //my fix: replacing NaN with zero
        Alt = double.IsNaN(value.Altitude) ? 0 : value.Altitude;

        _location = value;
    }            </pre>
<p>And the code where I update the Item entity from my view model:</p>
<pre class="brush: csharp;">private void SaveEntry()
{
    var item = (from i in db.Items
                where i.Id == ViewModel.Id
                select i).First();

    db.Refresh(RefreshMode.OverwriteCurrentValues, item);

    item.PhotoUrl = ViewModel.PhotoUrl;
    item.Text = ViewModel.LongText;
    item.Title = ViewModel.Title;
    item.Location = ViewModel.Location;
    db.SubmitChanges();
}</pre>
<p>I have of course tried the different RefreshModes, with the same result.</p>
<p>I hope this helped someone out there with weird SQL errors and NaN values.</p>
<p>Bye!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/23/storing-double-nan-in-a-wp7-sqlce-database/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NoSQL with RavenDB</title>
		<link>http://blog.jayway.com/2011/09/22/nosql-with-ravendb/</link>
		<comments>http://blog.jayway.com/2011/09/22/nosql-with-ravendb/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 07:43:48 +0000</pubDate>
		<dc:creator>Niklas Lundberg</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[nosql]]></category>
		<category><![CDATA[ravendb]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8762</guid>
		<description><![CDATA[In the strongly typed world we have to predefine data structures expressed with language elements such as structs and classes. However in a dynamic web world there is a greater flexibility, especially with a dynamic language as JavaScript, native browser support for JSON and jQuery libraries. If your data is relational and fixed in the [...]]]></description>
			<content:encoded><![CDATA[<p>In the strongly typed world we have to predefine data structures expressed with language elements such as structs and classes. However in a dynamic web world there is a greater flexibility, especially with a dynamic language as JavaScript, native browser support for JSON and jQuery libraries.</p>
<p>If your data is relational and fixed in the sense that there is a predefined schema, then a relational database would solve your problem just fine. However, if the problem domain is not relational in its nature, then other data structures might be better suited.</p>
<p>When dealing with free text qualitative data, there is really no connections that could be modeled between different sets of data. Instead a data structure of independent documents would be more suitable.</p>
<p>As a .NET developer the document database RavenDB is attractive since it provides us with a built-in .NET API, HTTP API and many of the features a NoSQL database can offer. In a web environment the HTTP API is useful because it could eliminate the need for a middle tier for simple scenarios where you don't need all the features the server side could offer. In RavenDB all documents are stored as JSON and its input and output is also JSON.</p>
<p>Since RavenDB is built in .NET, the natural way of using it is from .NET code. It is very easy to store and fetch strongly typed objects since RavenDB has APIs for doing the mapping transparently. However, you are not forced to use .NET code only. From JavaScript we can call the database directly with RavenDB's RESTful API. The mapping to a .NET class is stored as metadata with a fully qualified name. This is the only difference between a .NET mapped document and a document without any .NET type.</p>
<p>In RavenDB, you have to create indexes as Map/Reduce functions written as LINQ-queries. These indexes could make use of document properties, metadata or both.</p>
<p>The same logic is applied to collections in RavenDB; it is just some metadata specifying the Raven-Entity-Name. The major difference between this attribute and other metadata is that the Raven-Entity-Name could be used in indexes like this:</p>
<pre class="brush: csharp;">
from album in docs.albums
select new {album}
</pre>
<p>Of course you can add your own metadata and use it in your own indexes.</p>
<p>My personal findings about RavenDB are that it is very easily deployed; you can use xcopy to a website in Internet Information Services, IIS, with all of the features it offers.<br />
The database itself is quite straight forward but there are still things that need to be improved in the eco-system, such as management tools and more extensive documentation. </p>
<p>It is really nice to use Linq syntax to create indexes if you know C#, but you really have to think differently than you do when using a traditional relational database. You cannot write SQL to query RavenDB. However, in most cases it is possible to get the data you want by creating indexes. </p>
<p>Just remember, you store documents, not relational data.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/22/nosql-with-ravendb/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Setting AssemblyVersion number in TeamCity 6.5</title>
		<link>http://blog.jayway.com/2011/09/07/setting-assemblyversion-number-in-teamcity-6-5/</link>
		<comments>http://blog.jayway.com/2011/09/07/setting-assemblyversion-number-in-teamcity-6-5/#comments</comments>
		<pubDate>Wed, 07 Sep 2011 11:00:04 +0000</pubDate>
		<dc:creator>Peter von Lochow</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[TeamCity]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9266</guid>
		<description><![CDATA[You know the process where you need to increment the AssemblyVersion for each build? Personally I’ve solved it both using MSBuild and PowerShell as a part of our daily builds. We have also touched on the subject of incrementing version numbers in earlier posts, like: Håkan Reis – Version handling in TeamCity first part Håkan [...]]]></description>
			<content:encoded><![CDATA[<p>You know the process where you need to increment the AssemblyVersion for each build? Personally I’ve solved it both using MSBuild and PowerShell as a part of our daily builds. We have also touched on the subject of incrementing version numbers in earlier posts, like:</p>
<ul>
<li><a href="http://blog.jayway.com/author/hakanreis/">Håkan Reis</a> – <a href="http://blog.reis.se/post/Version-handling-in-TeamCity-first-part.aspx">Version handling in TeamCity first part</a> </li>
<li><a href="http://blog.jayway.com/author/hakanreis/">Håkan Reis</a> – <a href="http://blog.reis.se/post/Version-handling-in-TeamCity-second-part.aspx">Version handling in TeamCity second part</a> </li>
<li><a href="http://blog.jayway.com/author/fredrikolsson/">Fredrik Olsson</a> – <a href="http://blog.jayway.com/2011/05/31/auto-incrementing-build-numbers-in-xcode/">Auto incrementing Build Numbers in XCode</a> </li>
</ul>
<p>But the fact is, at least for Visual Studio projects, this can be done in two steps without writing any code at all. Simply put, it just got really easy. To accomplish this we’ll be using TeamCity’s <strong>Addition Build Features</strong>.</p>
<h2>Step 1 – Set a build number format</h2>
<p>I used the format 0.1.0.{0} (where {0} will be replaced by the build counter), but you can basically put anything you like here.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/buildnumber.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="buildnumber" border="0" alt="buildnumber" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/buildnumber_thumb.png" width="659" height="200" /></a></p>
<p>The build number format will automatically be stored in TeamCity as %build.number% which we will use in the next step.</p>
<h2>Step 2 – Add an additional build step</h2>
<p>When configuring your <strong>Build Steps</strong> you can also add something called <strong>Additional Build Features</strong>. One of those features is called <a href="http://confluence.jetbrains.net/display/TCD65/AssemblyInfo+Patcher">AssemblyInfo patcher</a> and it’s described like this.</p>
<blockquote><p>AssemblyInfo Patcher build feature allows to set a build number to an assembly automatically, without having to patch <tt>AssemblyInfo.cs</tt> files manually. When adding this build feature you need only to specify version format. Note, that you can use TeamCity parameter references here.</p>
</blockquote>
<p>So just add this feature and put your %build.number% as the assembly version format.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/build-feature.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="build feature" border="0" alt="build feature" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/09/build-feature_thumb.png" width="603" height="329" /></a></p>
<p>Done and done. For every build TeamCity will now update AssemblyInfo.cs, build your solution and then revert the changes that it made to the file. So we’ll end up with an assembly with a version number and unchanged source files.</p>
<p>Maintainable, clean and simple.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/07/setting-assemblyversion-number-in-teamcity-6-5/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Hosting your own Source &amp; Symbol Server</title>
		<link>http://blog.jayway.com/2011/06/19/hosting-your-own-source-symbol-server/</link>
		<comments>http://blog.jayway.com/2011/06/19/hosting-your-own-source-symbol-server/#comments</comments>
		<pubDate>Sun, 19 Jun 2011 16:51:00 +0000</pubDate>
		<dc:creator>Johan Olsson</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8849</guid>
		<description><![CDATA[If you are using NuGet to add 3rd party components in your project, you should also use SymbolSource.org to get debug info and source code for those components. If you are not familiar with SymbolSource.org, it is a service that hosts debug information (.pdb-files) and source code for open source projects. When you debug your [...]]]></description>
			<content:encoded><![CDATA[<p>If you are using NuGet to add 3rd party components in your project, you should also use SymbolSource.org to get debug info and source code for those components. If you are not familiar with SymbolSource.org, it is a service that hosts debug information (.pdb-files) and source code for open source projects. When you debug your project in VisualStudio and step into 3rd party code, Visual Studio automatically downloads the source and you can debug it like it was your own code. Cameron Skinner has written an excellent blog post that explains a Symbol Server works <a href="http://blogs.msdn.com/b/camerons/archive/2011/04/01/debugging-series-symbol-server.aspx">http://blogs.msdn.com/b/camerons/archive/2011/04/01/debugging-series-symbol-server.aspx</a> Also here’s an MSDN article with more technical details <a href="http://msdn.microsoft.com/en-us/library/ms680693.aspx">http://msdn.microsoft.com/en-us/library/ms680693.aspx</a></p>
<p>I am hosting my own NuGet server and I want to host my own Source and Symbol server as well. I can’t use SymbolSource.org because the code is proprietary and even though I could get a non-public account on SymbolSource.org the customer I am working with has a strict security policy of not letting the code leave the company network. So, I must host it myself, but how?</p>
<h2>The Source Server</h2>
<p>Setting up the source server was simple. Just create a file share, create a folder with the version number as name and put your source code there. So if I have a C# file named MySourceCode.cs in MyProject, the path to the source code will be \\myServer\MySourceShare\version1.0\MyProject\MySourceCode.cs</p>
<h2>The Symbol Server</h2>
<p>When you build a .Net assembly in VisualStudio you get one dll file and one pdb file. The pdb file contains debug information and references to the source code that makes up the assembly. There is only one problem with this. The references to the source files are absolute paths. If I have the source code in a file C:\Work\TheCustomer\MyProject\MySourceCode.cs, the pdb file will contain that absolute path.</p>
<p>Thus we must modify the pdb file to contain the path to the source server instead. This is a process call ‘Source Indexing’, and here’s an MSDN article about it, <a href="http://msdn.microsoft.com/en-us/library/ms680641(v=VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms680641(v=VS.85).aspx</a></p>
<p>The source indexing tools in ‘Debugging Tools for Windows’ is a collections of executables and perl scripts, but none of the srcipts do exactly what I want. What I want to do is replacing ‘C:\Work\TheCustomer\MyProject\MySourceCode.cs’ with ‘\\myServer\MySourceShare\version1.0\MyProject\MySourceCode.cs’. I am not proficient in Perl, so I wrote a small console program in C# that takes the replacement paths and modifies the pdb . Please see <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/06/SourceIndex.zip">attachment</a>.</p>
<p>Now we are ready to publish the pdb. Create a second file share ‘\\myServer\MySymbolShare’ and publish the modified pdb there by running symstore.exe (also from ‘Debugging Tools for Windows’).</p>
<pre>symstore.exe add /f myProject.pdb /s \\myServer\MySymbolShare /t "MyProject" /v "1.0.0.0"</pre>
<h2>Setting Up VisualStudio</h2>
<p>Finally we have to tell VisualStudio to search for symbols and source on our new shares.</p>
<p>a. In VisualStudio select "Debug-&gt;Options and Settings"</p>
<p>b. Select 'General' category</p>
<p>c. Uncheck "Enable Just My Code"</p>
<p>d. Check "Enable source server support"</p>
<p>e. Select 'Symbols' category</p>
<p>f. Add a new path by clicking the folder icon in upper right corner. Set name to: “\\myServer\MySourceShare”</p>
<p>g. Add another path. Set name to: “\\myServer\MySymbolShare”</p>
<p>That's it! When you debug 'MyProject', you can step in to the code and VisualStudio will automatically download the source code and display it. Sweet!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/06/19/hosting-your-own-source-symbol-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A nice, basic log4net setup</title>
		<link>http://blog.jayway.com/2011/06/13/a-nice-basic-log4net-setup/</link>
		<comments>http://blog.jayway.com/2011/06/13/a-nice-basic-log4net-setup/#comments</comments>
		<pubDate>Mon, 13 Jun 2011 21:26:26 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[log4net]]></category>
		<category><![CDATA[logging]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8768</guid>
		<description><![CDATA[In my current project I have need for quite a bit of logging. I’ve never used log4net before so I thought it was about time. Log4net has been around for ages, and is very well documented in the log4net documentation, and explained very nicely in e.g. Jim Christopher’s log4net tutorials. What I plan to show [...]]]></description>
			<content:encoded><![CDATA[<p>In my current project I have need for quite a bit of logging. I’ve never used log4net before so I thought it was about time. Log4net has been around for ages, and is very well documented in the <a href="http://logging.apache.org/log4net/index.html">log4net documentation</a>, and explained very nicely in e.g. <a href="http://www.beefycode.com/?tag=/log4net">Jim Christopher’s log4net tutorials</a>. What I plan to show you here is my findings in setting up my logging solution. What I wanted was couple of different log files for different severity levels, and here’s my story how I did it. I’m sure you can do more clever tricks that what I’ve done here, please contact me or share your knowledge in the comments if you have tips or thoughts on improvements.</p>
<h2></h2>
<h2>Summary</h2>
<p>I used…</p>
<ul>
<li>FileAppender+MinimalLock to be able to read the log file while the system is running </li>
<li>three Appenders one each for minimum LogLevel: debug, info and warning </li>
<li>one logger per class – gave me a readable “tag” on each log item, but filtering problems with nhibernate </li>
<li>an LoggerMatchFilter for nhibernate with AcceptOnMatch=false to reject messages </li>
</ul>
<p>&#160;</p>
<h2>Getting started</h2>
<p>To get any logging at all, you need to create a logger and configure it. The code for doing this and writing something to the log looks like this:</p>
<pre class="brush: csharp;">log4net.Config.XmlConfigurator.Configure();
var log = log4net.LogManager.GetLogger(this.GetType());
log.Debug(“debug message”);</pre>
<p>(Yes, it’s not a typo – the namespace is lowercase, I know it’s hard, by try to ignore that…)</p>
<p>Those few lines of course require configuration, the app/web.config is a good place for that so let’s go there now. The config needs three parts; a configSections entry, a log4net appender and a log4net root directive. See for yourself:</p>
<pre class="brush: xml;">&lt;configuration&gt;
  &lt;configSections&gt;
    &lt;section name=&quot;log4net&quot; type=&quot;log4net.Config.Log4NetConfigurationSectionHandler, log4net&quot;/&gt;
  &lt;/configSections&gt;
  &lt;log4net&gt;
    &lt;appender name=&quot;RollingFileAppenderAll&quot; type=&quot;log4net.Appender.RollingFileAppender&quot;&gt;
      &lt;file value=&quot;c:\logs\projectx_log_debug.txt&quot; /&gt;
      &lt;appendToFile value=&quot;true&quot; /&gt;
      &lt;rollingStyle value=&quot;Composite&quot; /&gt;
      &lt;datePattern value=&quot;.yyyyMMdd&quot; /&gt;
      &lt;maxSizeRollBackups value=&quot;10&quot; /&gt;
      &lt;maximumFileSize value=&quot;1MB&quot; /&gt;
      &lt;staticLogFileName value=&quot;true&quot; /&gt;
      &lt;lockingModel type=&quot;log4net.Appender.FileAppender+MinimalLock&quot; /&gt;
      &lt;layout type=&quot;log4net.Layout.Pattern Layout&quot;&gt;
        &lt;conversionPattern value=&quot;%date [%thread] %-6level %logger - %message %exception%newline&quot; /&gt;
      &lt;/layout&gt;
      &lt;filter type=&quot;log4net.Filter.LoggerMatchFilter&quot;&gt;
        &lt;loggerToMatch value=&quot;Jayway.ProjectX&quot; /&gt;
      &lt;/filter&gt;
      &lt;filter type=&quot;log4net.Filter.DenyAllFilter&quot; /&gt;
    &lt;/appender&gt;
    &lt;root&gt;
      &lt;level value=&quot;ALL&quot; /&gt;
      &lt;appender-ref ref=&quot;RollingFileAppenderAll&quot; /&gt;
    &lt;/root&gt;
  &lt;/log4net&gt;</pre>
<h2>Appender</h2>
<p>The appender entry represents a consumer of the logging information. Here I use a <em>RollingFileAppender</em> which rotates the log file periodically, as specified by the <em>datePattern</em>. <em>MaximumFileSize</em> is also honored and breaking that limit also rolls the log file over.</p>
<p>The logging in my project is done from a WCF service with HTTP endpoints. I have testing endpoints (e.g. /log/debug) that just shows the latest log file – very handy. To be able to read from the log file while the service is running, the <em>lockingModel</em> has to be set to <em>FileAppender+MinimalLock </em>which tells log4net to lock the log file as little as possible, instead of all the time which is the default. This will create a performance hit for the logging, but that’s ok for my setup. Specifying a <em>staticLogFileName</em> causes log4net to always log to a specific file, and then rename older log files according to date etc. This allows my hand coded log reader to always know where the latest log info is.</p>
<h2>Root</h2>
<p>The root section is what connects a log consumer (the appender) with a log producer (the ILog in the code). The root section can be replaced by specifying a specific logger (&lt;logger name=”myLogger”&gt;), and that would only process log data from that specific logger. Which logger to process data from brings us to the next topic – filtering.</p>
<h2>Filtering (and getting rid of nhibernate output)</h2>
<p>As you probably know, logs can either say to little, just about right, or WAY too much – that’s where the power of filtering comes in. <em>LogLevel</em> is the most natural and direct thing to filter on. In my service, I have three different log files all set to different levels; one for everything, one for at least <em>Info</em> and one for at least <em>Warning</em>. This is done by having three different appender entries and three appender rows in the <em>root</em> entry. This is where I started bumping into problems, read on…</p>
<h3>One logger per class</h3>
<p>I followed the advice from <a href="http://www.beefycode.com/post/Log4Net-Recommended-Practices-pt-1-Your-Code.aspx">Jim’s log4net recommended practices</a> to create one logger per class – not to use one logger for the entire application. The theory behind this is to have a tag on each log entry allowing you to have a log that “reads like a novel”. I like the idea and it’s very nice to always know what class issued the statement. Here’s an example of log output:</p>
<pre class="brush: csharp;">10:24:57,830 [10] INFO   Jayway.ProjectX.Service - ping called
10:24:57,833 [10] WARN   Jayway.ProjectX.Proxy - ping called
10:28:03,084 [10] INFO   Jayway.ProjectX.RequestCreator - creating request
10:28:03,095 [10] INFO   Jayway.ProjectX.Proxy - sending request
10:28:03,097 [10] WARN   Jayway.ProjectX.Proxy - could not reach host
10:28:03,907 [10] INFO   Jayway.Common.Cache - getting items from cache
10:28:03,910 [10] INFO   Jayway.ProjectX.Proxy - returning cache items
10:28:28,816 [10] INFO   Jayway.ProjectX.Service - returning 100 items</pre>
<p>I made this happen by using a logFactory that I inject into each class, instead of a log. (I’m not using an IoC container, was overkill for this project). The web service class looks like this:</p>
<pre class="brush: csharp;">private readonly ILogFactory _logFactory;
private readonly ILog _log;
public WebService()
{
   _logFactory = new LogFactoryLog4Net();
   _log = _logFactory.Create(this);
}</pre>
<p>whilst one of the classes begins with this:</p>
<pre class="brush: csharp;">private readonly ILog _log;

public Proxy(ILogFactory logFactory)
{
    _log = logFactory.Create(this);
}</pre>
<p>Using this technique, it would be very easy to temporarily add an appender for just a part of your system – giving you awesome control of the logging output.</p>
<h3>nhibernate</h3>
<p>NHibernate also uses log4net – and since I don’t have one logger but one per class, I have to use the “root” logger directive. The root logger funnel everything sent to the log4net system. This caused me to get all the nhibernate debug info in my logs. This was not what I wanted.</p>
<h3>Inverted filtering</h3>
<p>To get the kind of filtering output I wanted I had to use two kinds of filters; the LoggerMatchFilter and the LevelRangeFilter. Filtering in general in log4net works so that if you hit a filter that matches, it breaks the filtering chain and returns. This took me a while to figure out, I thought it just acted as a filter that could be chained, so that I could specify more and more filters to get more and more fine-grained output. But, back to the code:</p>
<pre class="brush: xml;">&lt;filter type=&quot;log4net.Filter.LoggerMatchFilter&quot;&gt;
  &lt;loggerToMatch value=&quot;NHibernate&quot; /&gt;
  &lt;AcceptOnMatch value=&quot;false&quot;/&gt;
&lt;/filter&gt;
&lt;filter type=&quot;log4net.Filter.LevelRangeFilter&quot;&gt;
  &lt;levelMin value=&quot;INFO&quot; /&gt;
&lt;/filter&gt;
&lt;filter type=&quot;log4net.Filter.DenyAllFilter&quot; /&gt;</pre>
<p>As you can see, I use the LoggerMatchFilter inverted. So, when it hits an item that matches “NHibernate” it will immediately reject it. If it does not match, it will continue down the chain and check the level. I figured this out by reading <a href="http://www.matheda.com/Blog/Details/4/log4net-tutorial">Matthew Daugherty’s log4net tutorial</a>, highly recommended.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/06/13/a-nice-basic-log4net-setup/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>WP7 build error &#8216;Xap packaging failed&#8217;</title>
		<link>http://blog.jayway.com/2011/06/03/wp7-build-error-xap-packaging-failed/</link>
		<comments>http://blog.jayway.com/2011/06/03/wp7-build-error-xap-packaging-failed/#comments</comments>
		<pubDate>Fri, 03 Jun 2011 07:48:45 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[wp7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/2011/06/03/wp7-build-error-xap-packaging-failed/</guid>
		<description><![CDATA[Today my Windows Phone 7 solution started giving me one single build error: Xap packaging failed. Object reference not set to an instance of an object. Short story A file had been removed from disk but not from the solution. Always set your sample data files to Build action: None. Long story The missing file [...]]]></description>
			<content:encoded><![CDATA[<p>Today my Windows Phone 7 solution started giving me one single build error: </p>
<p><em>Xap packaging failed. Object reference not set to an instance of an object.</em></p>
<p><em></em><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/06/image.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/06/image_thumb.png" width="483" height="56" /></a>     </p>
<h1>Short story</h1>
<p>A file had been removed from disk but not from the solution. Always set your sample data files to <em>Build action: None.</em></p>
<h1>Long story</h1>
<h2>The missing file</h2>
<p>After a few rounds of clean, rebuild, machine reboot etc., I started thinking and remembered that I had replaced an image in my Expression Blend sample data and removed the old one. Looking at the solution explorer confirms this, on file missing. Excluding this file from the solution removed the problem, I can now build again. But, why would the XAP packager fail on a file only used by the sample data?</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/06/image1.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/06/image_thumb1.png" width="201" height="183" /></a>Solution explorer with a missing file</p>
<h2>Build action</h2>
<p>So, the XAP packaging failed due to a missing image file, something must be wrong. Normal build action for images used by the application should be either <em>content </em>or <em>resource</em>, see <a href="http://www.windowsphonegeek.com/tips/wp7-working-with-images-content-vs-resource-build-action">WindowsPhoneGeek - Working with images...</a> for more info on this. But, an image what will only be used by Blend to show sample data should not be included in the build and therefore have <em>build action: none.</em> Changing my banner.png to <em>Build action: None </em>made the build go through. Of course the missing file should be excluded, but at least now we can build.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/06/image2.png" rel="lightbox"><img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/06/image_thumb2.png" width="244" height="176" /></a>Original (faulty) build action for sample data file</p>
<p>Bye for now!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/06/03/wp7-build-error-xap-packaging-failed/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>&#8220;HTML5 &amp; MVC3&#8243; Debriefing</title>
		<link>http://blog.jayway.com/2011/05/28/html5-mvc3-debriefing/</link>
		<comments>http://blog.jayway.com/2011/05/28/html5-mvc3-debriefing/#comments</comments>
		<pubDate>Sat, 28 May 2011 13:55:03 +0000</pubDate>
		<dc:creator>Gustaf Nilsson Kotte</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8545</guid>
		<description><![CDATA[Recently, Jayway hosted the seminar "HTML5 &#38; MVC3" in Malmö and Stockholm. We also visited the SweNUG Linköping group and held our presentation there. In this post, we will give you links to some of the topics we covered. The presentation was first delivered on Techdays 2011, and we recommend you to look at that [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, Jayway hosted the seminar "HTML5 &amp; MVC3" in Malmö and Stockholm. We also visited the SweNUG Linköping group and held our presentation there. In this post, we will give you links to some of the topics we covered.</p>
<p>The presentation was first delivered on Techdays 2011, and we recommend you to look at <a href="http://blog.jayway.com/2011/03/30/techdays-2011-web-debriefing/">that blog post</a> first. Below, you'll find some additional links to topics covered during some of the presentation occations.</p>
<h2>The links</h2>
<p><a href="http://blogs.jetbrains.com/dotnet/2011/05/resharper-6-enhances-the-javascript-experience/">ReSharper 6</a><br />
Currently in "Early Access Program", with better IntelliSense and refactoring support for JavaScript and CSS in Visual Studio.</p>
<p><a href="http://www.youtube.com/watch?v=N8SS-rUEZPg">Chrome DevToolbar</a> (presentation at Google I/O)<br />
A lot is happening here and this tool is well worth to keep your eyes on.</p>
<p><a href="http://www.jslint.com/">JSLint</a><br />
Static code analysis for JavaScript</p>
<p><a href="http://wcf.codeplex.com/">WCF Web API</a><br />
We talked a bit about some of the features of WCF Web API, a.k.a." WCF Http"</p>
<p><a href="http://blog.paulbetts.org/index.php/2011/05/16/announcing-sassandcoffee-0-5/">SassAndCoffee</a><br />
This <a href="http://nuget.org/List/Packages/SassAndCoffee">NuGet package</a> makes it easier to get started with CoffeeScript and Sass in ASP.NET.</p>
<p><a href="http://msdn.microsoft.com/en-us/data/gg577609">Reactive Extensions (Rx) for JavaScript</a><br />
Compose asynchronous and event-based programs using observable collections and LINQ-style query operators.</p>
<p><a href="http://silk.codeplex.com/">Project Silk</a><br />
Web Application guidance from the Patterns &amp; Practices team at Microsoft.</p>
<p><a href="http://html5boilerplate.com/">HTML5 Boilerplate</a><br />
Gives you a good default when building HTML5 sites/apps. Also exists as a <a href="http://html5boilerplate.com/mobile/">mobile version</a>.<br />
<a href="http://knockoutjs.com/"></a></p>
<p><a href="http://knockoutjs.com/">Knockout<br />
</a>The MVVM pattern implemented in JavaScript.</p>
<p><a href="http://weblogs.asp.net/leftslipper/archive/2010/07/28/migrating-asp-net-mvc-2-applications-to-asp-net-mvc-3-preview-1.aspx">ASP.NET MVC Migration Tool<br />
</a>Help you with the migration between different versions of ASP.NET MVC.</p>
<p><a href="http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx">Localization</a><br />
Localization in the browser is harder than on the server. This blog post is a nice resource on the subject.</p>
<p><a href="http://andrescholten.net/track-site-speed-with-google-analytics-events/">Track site speed with Google Analytics</a><br />
When the "Network tab" is not enough. Lets you track the real loading time for your users.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/05/28/html5-mvc3-debriefing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

