<?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/category/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Unboxing Dropbox and SharpBox</title>
		<link>http://blog.jayway.com/2012/02/06/unboxing-dropbox-and-sharpbox-2/</link>
		<comments>http://blog.jayway.com/2012/02/06/unboxing-dropbox-and-sharpbox-2/#comments</comments>
		<pubDate>Sun, 05 Feb 2012 23:04:31 +0000</pubDate>
		<dc:creator>Johan Silfversparre</dc:creator>
				<category><![CDATA[.Net]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11933</guid>
		<description><![CDATA[How to programmatically upload a file to your Dropbox account. On a train trip during the New Year’s weekend, I spent time testing and collecting notes about how to interact with Dropbox. I will share my findings with you in this blog post. Dropbox &#160; “Dropbox is a free service that lets you bring your [...]]]></description>
			<content:encoded><![CDATA[<p><i>How to programmatically upload a file to your Dropbox account</i><em>.</em></p>
<p>On a train trip during the New Year’s weekend, I spent time testing and collecting notes about how to interact with Dropbox. I will share my findings with you in this blog post.</p>
<h2>Dropbox </h2>
<h2>&#160;</h2>
<blockquote><p><em>“</em><i>Dropbox is a free service that lets you bring your photos, docs, and videos anywhere and share them easily. Never email yourself a file again!&quot; – <a href="http://dropbox.com/">dropbox.com</a></i><em>”</em></p>
</blockquote>
<p>Follow these steps to create a Dropbox account and register the app you will use to interact with your Dropbox file area:</p>
<ol>
<li>Create a new Dropbox account at <a href="http://www.dropbox.com/login#register">www.dropbox.com/login#register</a> </li>
<li>Accept the Dropbox App Developer terms at <a href="http://www.dropbox.com/developers/apply">www.dropbox.com/developers/apply</a> </li>
<li>Continue with the next step, where you create an app with a suitable test name and a short nonsense description     <br /> 
<p></p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/image.png" rel="lightbox"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/image_thumb.png" width="441" height="328" /></a><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/image1.png" rel="lightbox">       <br /></a></li>
</ol>
<p>The Dropbox admin interface should now show you the App Key and App Secret you need later for creating a security token file.</p>
<h2>SharpBox</h2>
<p>My train trip was quite long, so I decided to put another card in the deck. SharpBox is a popular framework for accessing storage and one of the storage service providers it supports is Dropbox. (You can, of course, skip SharpBox and use the Dropbox API directly but I decided out of curiosity to test SharpBox.)</p>
<blockquote><p><i>“SharpBox is the right free open source solution for your project. Our goal is to disburden software projects from the demand to implement storage access twice to support a wide range of storage clouds.&quot; – <a href="http://sharpbox.codeplex.com/">sharpbox.codeplex.com</a></i></p>
</blockquote>
<p>Follow these steps to set up a test application in Visual Studio 2010 and include Sharpbox in it:</p>
<ol>
<li>Create a new <b>C# Console Application </b>in Visual Studio </li>
<li>Open the properties of the application and set <b>Target Framework</b> to <b>.NET Framework 4</b> </li>
<li>Add the SharpBox <b>NuGet</b> package named&#160; <b>AppLimit.CloudComputing.SharpBox</b> </li>
<li>Open the File Explorer and start the SharpBox tool <b>DropBoxTokenIssuer.exe</b> located in the folder <b>approot\packages\AppLimit.CloudComputing.SharpBox.1.2.0.542\lib\net40-full</b>. This tool is used to create a Security Token file you will use in your application. </li>
<li>Enter the <b>Application Key</b> and <b>Application Secret</b> you previously got in the Dropbox admin interface. Name the file <b>DropBoxToken</b> and finally click the Authorize button.&#160;
<p></p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/image2.png" rel="lightbox"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blog.jayway.com/wordpress/wp-content/uploads/2012/02/image_thumb1.png" width="422" height="225" /></a>       </li>
<li>This will hopefully lead you to the Dropbox login page, where you will use the login credentials for the account you previously created. (Please make sure you set the Target Framework correctly to .Net Framework 4 if no login page appears.) </li>
<li>If everything worked out correctly, you will now see an error page. Confusing? This is because the Sharpbox tool redirects to a page that does not exist on Codeplex. You will find the <strong>Security Token file</strong> created in the same folder where the tool application exists. </li>
<li>Finally, move this Security Token file to <strong>C:\Test</strong> together with an empty text file you create and name <b>texttest.txt</b>. </li>
</ol>
<h2>The code</h2>
<p>Everything is now set up for some coding. Fill the Program.cs with this:</p>
<pre class="brush: csharp;">using System;
using System.IO;
using AppLimit.CloudComputing.SharpBox; 

namespace DropBoxTestApp
{
  class Program
  {
    static void Main()
    {
      var dropBoxStorage = new CloudStorage();
      var dropBoxConfig = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox);

      // declare an access token
      ICloudStorageAccessToken accessToken;
      // load a valid security token from file
      using (var fs = File.Open(@&quot;C:\Test\DropBoxToken&quot;, FileMode.Open, FileAccess.Read, FileShare.None))
      {
        accessToken = dropBoxStorage.DeserializeSecurityToken(fs);
      }

      // open the connection
      var storageToken = dropBoxStorage.Open(dropBoxConfig, accessToken);

      var srcFile = Environment.ExpandEnvironmentVariables(@&quot;C:\Test\texttest.txt&quot;);
      dropBoxStorage.UploadFile(srcFile, &quot;/&quot;);             

      // close the connection
      dropBoxStorage.Close();
    }
  }
}</pre>
<p>After executing the application, you should be able to see in your Dropbox client of choice or Dropbox admin interface that the file texttest.txt has been uploaded to your Dropbox file area.</p>
<h2>Useful Hints and Links</h2>
<p>I have now successfully stored files this way for more than a month in a minor hobby application and it works great. After uploading files, you probably also want to download them and SharpBox can help you with this and much more. The only problem I encountered in my own application was when trying to download a file from Dropbox and sending it to the user via a Web browser as a stream. The file had the correct size, but seemed to be empty. The solution was to use <b>Stream.Seek(0,0)</b> before returning the filestream.</p>
<p>You can find more info here:</p>
<ul>
<li><a href="http://www.dropbox.com/developers">Dropbox for Developers</a> </li>
<li><a href="http://sharpbox.codeplex.com/">SharpBox@Codeplex</a> </li>
</ul>
<p>/<a href="http://www.silfversparre.com/">Johan</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/02/06/unboxing-dropbox-and-sharpbox-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Secure your REST-based WCF service with WIF, part 2</title>
		<link>http://blog.jayway.com/2012/01/28/secure-your-rest-based-wcf-service-with-wif-part-2/</link>
		<comments>http://blog.jayway.com/2012/01/28/secure-your-rest-based-wcf-service-with-wif-part-2/#comments</comments>
		<pubDate>Sat, 28 Jan 2012 14:26:06 +0000</pubDate>
		<dc:creator>Stefan Severin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[OAuth]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[WIF]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11909</guid>
		<description><![CDATA[This is the second post in a series of blog posts on how to secure REST-based services built on WCF and ASP.NET. One possible use case would be that we are hosting an OAUTH resource server where a third-party client has been issued a token by an authorization server with the approval of the resource [...]]]></description>
			<content:encoded><![CDATA[<p>This is the second post in a series of blog posts on how to secure REST-based services built on WCF and ASP.NET. One possible use case would be that we are hosting an <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-1" target="_blank">OAUTH</a> resource server where a third-party client has been issued a token by an authorization server with the approval of the resource owner (user) and that the client uses this token to access the protected resources inside our service.    </p>
<p>In <a href="http://blog.jayway.com/2012/01/05/secure-your-rest-based-wcf-service-with-wif-part-1/">part 1</a> the scene was set&#160; by enabling WIF with a little help of a custom <a href="http://msdn.microsoft.com/en-us/library/ms227673.aspx" target="_blank">HTTP module</a>. The module grabs the SAML token from the incoming request’s authorization header and hands it over to WIF, which in turn does its token validation job. </p>
<p>But how does WIF know what to do with the incoming SAML token? Well it doesn’t, not unless we tell it what to do. So this can be done programmatically or through configuration (or a combination of both).    <br />In this case we will initialize the WIF configuration programmatically by giving it a reference to a service configuration element specified inside the web.config file (shown shortly). For this we first need to create a class that inherits from <a href="http://msdn.microsoft.com/en-us/library/microsoft.identitymodel.configuration.serviceconfiguration.aspx">ServiceConfiguration</a>:</p>
<pre class="csharpcode"><span class="kwrd">using</span> Microsoft.IdentityModel.Configuration;

<span class="kwrd">namespace</span> Jayway.IdentityModel.Configuration
{
    <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> CustomServiceConfiguration : ServiceConfiguration
    {
        <span class="kwrd">public</span> CustomServiceConfiguration()
            : <span class="kwrd">this</span>(<span class="str">&quot;[The microsoft.identityModel service name goes here]&quot;</span>)
        {
        }

        <span class="kwrd">public</span> CustomServiceConfiguration(<span class="kwrd">string</span> serviceName)
            : <span class="kwrd">base</span>(serviceName)
        {
            <span class="kwrd">if</span> (!IsInitialized)
            {
                Initialize();
            }
        }
    }
}</pre>
<p>With this class in place we can get a hold of the WIF configuration from inside the WIfEnablingModule defined in <a href="http://blog.jayway.com/2012/01/05/secure-your-rest-based-wcf-service-with-wif-part-1/" target="_blank">part 1</a>…</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> <span class="kwrd">object</span> _lockObject = <span class="kwrd">new</span> <span class="kwrd">object</span>();

<span class="kwrd">private</span> ServiceConfiguration ServiceConfiguration
{
    get
    {
        <span class="kwrd">if</span> (serviceConfiguration == <span class="kwrd">null</span>)
        {
            <span class="kwrd">lock</span> (_lockObject)
            {
                serviceConfiguration = <span class="kwrd">new</span> CustomServiceConfiguration();
            }
        }
        <span class="kwrd">return</span> serviceConfiguration;
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>… and use it the way we did in the AuthenticateRequest method.</p>
<p>&#160;</p>
<p>If we now shift our focus to the actual configuration part inside the web.config file, we first need to register the WIF configuration section:</p>
<pre class="csharpcode">

<span class="kwrd"></span>&#160;

<span class="kwrd">&lt;</span><span class="html">configSections</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">section</span> <span class="attr">name</span><span class="kwrd">=&quot;microsoft.identityModel&quot;</span>
             <span class="attr">type</span><span class="kwrd">=&quot;Microsoft.IdentityModel.Configuration.MicrosoftIdentityModelSection,
     Microsoft.IdentityModel,  Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">configSections</span><span class="kwrd">&gt;</span>

<span class="kwrd"></span>&#160;

<span class="kwrd"></span>&#160;
</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>And our WIF section goes like this:</p>
<pre class="csharpcode">

<span class="kwrd"></span>&#160;

<span class="kwrd">&lt;</span><span class="html">microsoft.identityModel</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">service</span> <span class="attr">name</span><span class="kwrd">=&quot;Jayway.Service&quot;</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">audienceUris</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">value</span><span class="kwrd">=&quot;https://localhost/jaywayservice&quot;</span> <span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">audienceUris</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">issuerNameRegistry</span> <span class="attr">type</span><span class="kwrd">=&quot;Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">trustedIssuers</span><span class="kwrd">&gt;</span>
                <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">thumbprint</span><span class="kwrd">=&quot;J123A4567890Y1W23A456Y78R9OC1d2K3S456090&quot;</span> <span class="attr">name</span><span class="kwrd">=&quot;AuthorizationServer&quot;</span> <span class="kwrd">/&gt;</span>
            <span class="kwrd">&lt;/</span><span class="html">trustedIssuers</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">issuerNameRegistry</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">securityTokenHandlers</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">type</span><span class="kwrd">=&quot;Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;</span> <span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">securityTokenHandlers</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">claimsAuthenticationManager</span> <span class="attr">type</span><span class="kwrd">=&quot;Jayway.IdentityModel.Claims.CustomClaimsAuthenticationManager, Jayway.IdentityModel, ...&quot;</span> <span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">claimsAuthorizationManager</span> <span class="attr">type</span><span class="kwrd">=&quot;Jayway.IdentityModel.Claims.CustomClaimsAuthorizationManager, Jayway.IdentityModel, ...&quot;</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">service</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">microsoft.identityModel</span><span class="kwrd">&gt;</span>

<span class="kwrd"></span>&#160;
</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>By specifying an audienceUri as above we require the SAML token to contain a matching URI. That way we know that the token was indeed meant for our RP (relying party). </p>
<p>Next we use the built-in <a href="http://msdn.microsoft.com/en-us/library/microsoft.identitymodel.tokens.configurationbasedissuernameregistry.aspx" target="_blank">ConfigurationBasedIssuerNameRegistry</a> which takes care of the heavy cryptographic work, validating the token’s digital signature against a list of trusted issuers (or their matching public keys that is). In this case we only have one.&#160; </p>
<p>We also make use of the built-in <a href="http://msdn.microsoft.com/en-us/library/microsoft.identitymodel.tokens.saml2.saml2securitytokenhandler.aspx" target="_blank">Saml2SecurityTokenHandler</a> which handles the deserialization from the SAML 2.0 assertion into a Saml2SecurityToken CLR object, validates it, checks that it has not yet expired and so on, and while it’s at it, also transforms the security token object into a ClaimsIdentityCollection.</p>
<p>Ok so now that we have the set of claims that corresponds to the assertion of the incoming token it’s up to us what we want to do with it. We can for example call a custom claims store to add some more claims to the collection or perhaps delete certain identifying claims that should not be passed all the way to the RP. It’s really up to the requirements at hand.<br />
  <br />The way we can do this is by creating a customized <a href="http://msdn.microsoft.com/en-us/library/microsoft.identitymodel.claims.claimsauthenticationmanager.aspx">ClaimsAuthenticationManager</a>, and call its Authenticate method, which we pass the claims collection. This is exactly what the next configured element in our WIF section is, the CustomClaimsAuthenticationManager above. (See also the AuthenticateRequest method in <a href="http://blog.jayway.com/2012/01/05/secure-your-rest-based-wcf-service-with-wif-part-1/">part 1</a> on how to use it). </p>
<p>The next step in the WIF pipeline is to authorize (or deny) the incoming request before the claims finally are handed over to the RP. For this purpose we have configured the CustomClaimsAuthorizationManager that inherits <a href="http://msdn.microsoft.com/en-us/library/microsoft.identitymodel.claims.claimsauthorizationmanager.aspx" target="_blank">ClaimsAuthorizationManager</a>.</p>
<p>Summary: The focus of this post has been on how we can initialize the WIF configuration through code and configure the WIF pipeline through the microsoft.identityModel configuration section. </p>
<p>In the next post we will look closer on the implementation of the CustomClaimsAuthenticationManager and CustomClaimsAuthorizationManager classes. We will also go ahead and implement a simple REST service and a test client to try it all out.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/01/28/secure-your-rest-based-wcf-service-with-wif-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<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>WebClient/WebRequest threading untangled</title>
		<link>http://blog.jayway.com/2012/01/18/webclientwebrequest-threading-untangled/</link>
		<comments>http://blog.jayway.com/2012/01/18/webclientwebrequest-threading-untangled/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 06:39:00 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[windows phone]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11865</guid>
		<description><![CDATA[WebRequest and its baby sister WebClient behave differently regarding what thread they return on. This is a short post to really clarify what returns where. Summary WebClient will always return on the UI thread if called from the UI thread WebRequest will always return on a background thread The investigation To test this I created [...]]]></description>
			<content:encoded><![CDATA[<p>WebRequest and its baby sister WebClient behave differently regarding what thread they return on. This is a short post to really clarify what returns where.</p>
<h2>Summary</h2>
<ul>
<li>WebClient will always return on the UI thread if called from the UI thread </li>
<li>WebRequest will always return on a background thread </li>
</ul>
<h2>The investigation</h2>
<p>To test this I created a super-simple app that fetches some stuff using WebClient and WebRequest, from the UI and from a background worker.</p>
<p>The code:</p>
<pre class="brush: csharp;">

public partial class MainPage : PhoneApplicationPage
{
    private readonly int _uiThreadId = Thread.CurrentThread.ManagedThreadId;

    // Constructor
    public MainPage()
    {
        InitializeComponent();
    }

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        WriteThreadInfo(&quot;UI&quot;);

        Dispatcher.BeginInvoke(() =&gt; WriteThreadInfo(&quot;dispatcher&quot;));

        RunUiRequests();

        LaunchWorkerRequests();

        base.OnNavigatedTo(e);
    }

    private void RunUiRequests()
    {
        var request = WebRequest.CreateHttp(&quot;http://www.jayway.com&quot;);
        request.BeginGetResponse(RequestCallbackFromUI, null);

        var client = new WebClient();
        client.DownloadStringCompleted += client_DownloadFromUIStringCompleted;
        client.DownloadStringAsync(new Uri(&quot;http://www.jayway.com&quot;, UriKind.RelativeOrAbsolute));
    }

    private void LaunchWorkerRequests()
    {
        var worker = new BackgroundWorker();
        worker.DoWork += (sender, ex) =&gt;
                                {
                                    Thread.Sleep(2000);

                                    WriteThreadInfo(&quot;worker&quot;);

                                    var request = WebRequest.CreateHttp(&quot;http://www.jayway.se&quot;);
                                    request.BeginGetResponse(RequestCallbackFromWorker, null);

                                    var client = new WebClient();
                                    client.DownloadStringCompleted += client_DownloadFromWorkerStringCompleted;
                                    client.DownloadStringAsync(new Uri(&quot;http://www.jayway.com&quot;, UriKind.RelativeOrAbsolute));

                                };
        worker.RunWorkerAsync();
    }

    private void client_DownloadFromWorkerStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        WriteThreadInfo(&quot;webclient from worker&quot;);
    }

    private void RequestCallbackFromWorker(IAsyncResult ar)
    {
        WriteThreadInfo(&quot;webrequest from worker&quot;);
    }

    void client_DownloadFromUIStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        WriteThreadInfo(&quot;webclient from UI&quot;);
    }

    private void RequestCallbackFromUI(IAsyncResult ar)
    {
        WriteThreadInfo(&quot;webrequest from UI&quot;);
    }

    private void WriteThreadInfo(string threadName)
    {
        var id = Thread.CurrentThread.ManagedThreadId;
        Debug.WriteLine(&quot;{0,-28} Thread is {1} ({2})&quot;,
                        threadName,
                        id,
                        (id == _uiThreadId) ? &quot;UI&quot; : &quot;background&quot;);
    }
}

&#160;
</pre>
<p>And one set of results from running this is: </p>
<p><font face="Courier New">UI&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Thread is 257753342 (UI)<br />
    <br />dispatcher&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Thread is 257753342 (UI)</p>
<p>webrequest from UI&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Thread is 255066402 (background)</p>
<p>webclient from UI&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Thread is 257753342 (UI)</p>
<p>worker&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Thread is 254411058 (background)</p>
<p>webclient from worker&#160;&#160;&#160;&#160;&#160;&#160;&#160; Thread is 236257614 (background)</p>
<p>webrequest from worker&#160;&#160;&#160;&#160;&#160;&#160; Thread is 255066402 (background)</font></p>
<p>As you can see, the WebClient returns on the UI thread when called from the UI thread, but when called from the worker thread – it returns on a background thread.</p>
<p>I hope you feel enlightened – I 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/2012/01/wlEmoticon-smile.png" /></p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:41b83fb3-a9dc-43c3-8b7d-c510f1634b86" class="wlWriterEditableSmartContent">
<p> <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2012/01/WebRequestThreadingTestApp1.zip" target="_blank">Download source here</a></p>
</div>
<p><font face="Courier New">&#160;</font></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/01/18/webclientwebrequest-threading-untangled/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Crafting the &#216;redev Windows Phone app live tile</title>
		<link>http://blog.jayway.com/2012/01/09/crafting-the-redev-windows-phone-app-live-tile/</link>
		<comments>http://blog.jayway.com/2012/01/09/crafting-the-redev-windows-phone-app-live-tile/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 21:46:11 +0000</pubDate>
		<dc:creator>Andreas Hammar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[windows phone]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[wp7dev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11731</guid>
		<description><![CDATA[In November last year, it was once again time for the 2011 Øredev developer conference. For the 2010 conference, we at Jayway created a schedule app with a social twist – a puzzle game that you played by talking to other participants. When updating the app this year, we decided to make use of the [...]]]></description>
			<content:encoded><![CDATA[<p>In November last year, it was once again time for the 2011 <a href="http://oredev.org/2011">Øredev</a> developer conference. For the 2010 conference, we at Jayway created a schedule app with a social twist – a puzzle game that you played by talking to other participants. When updating the app this year, we decided to make use of the live tile feature on Windows Phone. We were happy with the results and the added user value, and would like to share how we did it.</p>
<h2>Deciding what to show</h2>
<p>Since the app was going to be used throughout the conference, showing something about what’s coming up would be nice. At first we were thinking about showing upcoming session titles with speaker names etc – maybe one randomized at a time. But then, we ended up with something more personal and more graphical – thumbnails of upcoming speakers. Here’s what the tile looks like:</p>
<p align="center">front:  <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2012/01/tile_before_front.png" rel="lightbox"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="tile_before_front" src="http://blog.jayway.com/wordpress/wp-content/uploads/2012/01/tile_before_front_thumb.png" alt="tile_before_front" width="177" height="177" border="0" /></a>         back: <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2012/01/tile_before_back.png" rel="lightbox"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="tile_before_back" src="http://blog.jayway.com/wordpress/wp-content/uploads/2012/01/tile_before_back_thumb.png" alt="tile_before_back" width="176" height="177" border="0" /></a></p>
<p align="left">Hence the front of the tile shows the speakers, and the back of the tile shows at what time the next sessions start. Instead of just using the back of the tile – we opted for giving the user as immediate information as possible – so whenever he/she would look at their start screen – something useful would be there, not just the app logo. This we think is a viable solution for this kind of short-term usage app, but maybe is not suitable for a lifetime app, like your bank, that you will (hopefully) keep forever and will not use every 5 minutes.</p>
<p align="left">We put a finale in there as well; after the conference was over – the tile changed to:</p>
<p align="center">front: <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2012/01/tile_original_tile.png" rel="lightbox"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="tile_original_tile" src="http://blog.jayway.com/wordpress/wp-content/uploads/2012/01/tile_original_tile_thumb.png" alt="tile_original_tile" width="178" height="178" border="0" /></a>         back: <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2012/01/tile_after_back.png" rel="lightbox"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="tile_after_back" src="http://blog.jayway.com/wordpress/wp-content/uploads/2012/01/tile_after_back_thumb.png" alt="tile_after_back" width="177" height="176" border="0" /></a></p>
<p align="left">Nice huh? When the conference is over – the conference logo comes back as the app’s front tile and a nice message shows on the back. Maybe the message is a bit too much, but I think it’s a nice pointer to un-pin the app from your start screen. An app should be on the start screen for a reason– and this conference app does not really belong there once the conference is over.</p>
<h2>Install size vs bandwidth usage</h2>
<p>We bundled all speaker images with the app. This creates a larger file to install, but gives less data to download when updating the tile, and less hassle if you compare with downloading and caching. With lots of people coming from abroad, we thought it would be better to rely the dodgy conference wireless <em>once</em> during installation instead of on each tile update.</p>
<h2>Implementing the tile</h2>
<p>The of-the-shelf solution for updating a tile is very well documented here: <a href="http://msdn.microsoft.com/en-us/library/hh202979(v=vs.92).aspx">updating the tile</a> and <a href="http://msdn.microsoft.com/en-us/library/hh202941(v=vs.92).aspx">running in the background</a>. What can be a bit tricky is creating a fully customized tile, which is done by rendering a background image for the tile using WriteableBitmap. The blog post <a href="http://http://blogs.msdn.com/b/johnalioto/archive/2011/08/30/10203141.aspx">Customize a Windows Phone 7 Live Tile by John P Alioto</a> helped me on the way.</p>
<p>The OnInvoke method first checks whether to reset the tile and remove the background agent, then launches the canvas setup on the current dispatcher. When not running on the dispatcher, cross threading issues keep popping up.</p>
<pre class="brush: csharp;">protected override void OnInvoke(ScheduledTask task)
{
    if (CheckConferenceEndedAndDisableAgent(task))
    {
        NotifyComplete();
        return;
    }

    Deployment.Current.Dispatcher.BeginInvoke(SetupCanvas);
}

private bool CheckConferenceEndedAndDisableAgent(ScheduledTask task)
{
    if (!ConferenceTimeCalculator.HasConferenceEnded())
        return false;

    var tileData = new StandardTileData
                       {
                           BackgroundImage = new Uri("Background.png", UriKind.RelativeOrAbsolute),
                           Title = APP_TITLE,
                           BackTitle = "welcome back!",
                           BackContent = APP_TITLE + " is over"
                       };
    var tile = ShellTile.ActiveTiles.First();
    tile.Update(tileData);

    Debug.WriteLine("conference has ended, removing scheduled task");
    ScheduledActionService.Remove(task.Name);
    return true;
}

private void SetupCanvas()
{
    _canvas = new Canvas
                  {
                      Height = TILE_SIDE,
                      Width = TILE_SIDE
                  };

    var bmp = new BitmapImage
                  {
                      CreateOptions = BitmapCreateOptions.None
                  };

    bmp.ImageOpened += OnBackgroundBmpOpened;
    bmp.UriSource = new Uri("Background.png", UriKind.RelativeOrAbsolute);
}</pre>
<p>as you can see, the SetupCanvas only opens the background image then returns. Since the original tile file Background.png is a content file – we have to wait for the ImageOpened event to be raised before trying to render it – otherwise the result will only be black.</p>
<p>So, when the image is opened, we open all the images for all the speakers:</p>
<pre class="brush: csharp;">
private void OnBackgroundBmpOpened(object sender, RoutedEventArgs e)
{
    Debug.WriteLine("background opened");
    var image = new Image
                    {
                        Source = (BitmapImage)sender,
                        Width = 173,
                        Height = 173
                    };

    Canvas.SetLeft(image, 0);
    Canvas.SetTop(image, 0);
    _canvas.Children.Add(image);

    Deployment.Current.Dispatcher.BeginInvoke(LaunchOpenOfAllSpeakerImages);
}

public void LaunchOpenOfAllSpeakerImages()
{
    _nbrOfSpeakers = _speakers.Count;
    Debug.WriteLine("starting tile update for {0} speakers",
                    _nbrOfSpeakers);
    foreach (var speaker in _speakers)
        GetSpeakerBitmap(speaker);
}

private void GetSpeakerBitmap(ISpeaker speaker)
{
    var bmp = new BitmapImage { CreateOptions = BitmapCreateOptions.None };
    bmp.ImageOpened += OnSpeakerBmpOpened;

    //live
    //bmp.UriSource = new Uri(speaker.ImageUri, UriKind.RelativeOrAbsolute);

    //cached
    bmp.UriSource = new Uri("/images/speakers/" + speaker.Id + ".jpg", UriKind.RelativeOrAbsolute);
}

private void OnSpeakerBmpOpened(object sender, RoutedEventArgs e)
{
    Debug.WriteLine("image opened");
    var mySpeakerIndex = _nbrOfSpeakers;
    _nbrOfSpeakers -= 1;

    AddImageToCanvas(mySpeakerIndex, (BitmapImage)sender);

    if (_nbrOfSpeakers == 0)
        RenderComposedBitmap();
}

private void AddImageToCanvas(int mySpeakerIndex, BitmapImage bitmapImage)
{
    var image = new Image
                    {
                        Source = bitmapImage,
                        Width = 57,
                        Height = 57,
                        Stretch = Stretch.UniformToFill,
                        Opacity = 1
                    };

    _canvas.Children.Add(image);
    Canvas.SetLeft(image, 58 * (mySpeakerIndex % 3));
    Canvas.SetTop(image, 58 * (mySpeakerIndex / 3));
}</pre>
<p>and finally, when all images have been opened, we render the image and update the tile:</p>
<pre class="brush: csharp;">private void RenderComposedBitmap()
{
    Debug.WriteLine("rendering composed bitmap");
    var writeableBitmap = new WriteableBitmap(173, 173);

    writeableBitmap.Render(_canvas, null);
    writeableBitmap.Invalidate();

    WriteJpg(writeableBitmap);
    UpdateTile();
}

private void UpdateTile()
{
    var tile = ShellTile.ActiveTiles.First();
    var data = new StandardTileData
                   {
                       Title = "",
                       BackTitle = APP_TITLE,
                       BackgroundImage = new Uri("isostore:/" + TILE_BACKGROUND_IMAGE_URI, UriKind.RelativeOrAbsolute),
                       BackContent = "next sessions: " + _sessionstart
                   };
    tile.Update(data);
    NotifyComplete();
}</pre>
<p>The Control Canvas is used for layout of the tile. As guys who love Grid’s and dynamic layout – we first tried using a Grid with three columns and three rows, but could not get the images to render correctly. During a Windows Phone Code Camp at Jayway, <a href="http://buzzfrog.blogs.com/">Dag König</a> nicely pointed us towards the Canvas which he had used in his <a href="http://www.windowsphone.com/sv-se/apps/d0bd170e-ce51-4dca-97ef-1dd18ab9abbe">Month Tile</a> app – works beautifully. It’s probably just some Measure/Arrange-calls together with an Invalidate to get a Grid-powered tile to render correctly, left as exercise for the reader <img class="wlEmoticon wlEmoticon-winkingsmile" style="border-style: none;" src="http://blog.jayway.com/wordpress/wp-content/uploads/2012/01/wlEmoticon-winkingsmile.png" alt="Winking smile" /></p>
<p>That’s it! Hope this inspires or helps someone out there. L8r g8rs!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/01/09/crafting-the-redev-windows-phone-app-live-tile/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>Secure your REST-based WCF service with WIF, part 1</title>
		<link>http://blog.jayway.com/2012/01/05/secure-your-rest-based-wcf-service-with-wif-part-1/</link>
		<comments>http://blog.jayway.com/2012/01/05/secure-your-rest-based-wcf-service-with-wif-part-1/#comments</comments>
		<pubDate>Thu, 05 Jan 2012 13:56:22 +0000</pubDate>
		<dc:creator>Stefan Severin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[OAuth]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[WIF]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11661</guid>
		<description><![CDATA[&#160; In this particular scenario we have a REST API built on WCF and ASP.NET which exposes resources owned by some imaginary users, and we want to make their resources accessible to third-party applications (clients) in a secure way. That is, we want to allow our users to grant authorization to clients requesting access to [...]]]></description>
			<content:encoded><![CDATA[<p>&#160;</p>
<p>In this particular scenario we have a REST API built on WCF and ASP.NET which exposes resources owned by some imaginary users, and we want to make their resources accessible to third-party applications (clients) in a secure way. That is, we want to allow our users to grant authorization to clients requesting access to their resources without handing over their username and password to the third-party. In that sense this could be seen as a simplified implementation of a .NET OAuth Resource Server.    <br />Each and every request that the API receives must contain a valid SAML token. The token is expected to be found in the request’s authorization header and it must be signed by an OAuth Authorization Server which our service has a trust relationship with.     </p>
<p>The focus in this initial post is on how to extend the request pipeline with a custom HTTP module that will hand over the SAML token to Windows Identity Foundation (WIF) to do its authentication and authorization logic.     </p>
<p>The Visual Studio wizards that come with the WIF SDK makes the job easy when it comes to enabling claims-based identity for ASP.NET web applications as well as SOAP-based WCF services. However at the time of this writing, the SDK has no wizard that enables WIF on the kind of REST API that we are building here. We will get around this though by implementing our own WIF-enabling module. Below I will describe how to do this while showing important parts of a possible code implementation.</p>
<p>The HTTP module that we are going to create has mainly three roles. The first is to extract the SAML token from the authorization header. Secondly it will hand the token over to WIF that validates it according to the WIF configuration inside the web.config. Finally the module will attach the IClaimsPrincipal that it gets back from WIF to the current HTTP user.    </p>
<p>Let’s see how we can accomplish all this:</p>
<p>First we need to create a class that implements System.Web.IHttpModule, let’s call it WifEnablingModule:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> WifEnablingModule : IHttpModule</pre>
<p>
  <br />In its Init method we hook up to the following HttpApplication events:</p>
<pre class="csharpcode">context.AuthenticateRequest += OnAuthenticateRequest;
context.EndRequest += OnEndRequest;</pre>
<p>The code in OnAuthenticateRequest goes as: </p>
<pre class="csharpcode">HttpContext context = HttpContext.Current;

<span class="kwrd">if</span> (context.Request.ContainsAuthorizationHeader())
{
    <span class="kwrd">bool</span> valid = AuthenticateRequest(context.Request);

    <span class="kwrd">if</span> (!valid)
    {
        context.SendUnauthorizedResponse();
    }
}
<span class="kwrd">else</span>
{
    context.SendUnauthorizedResponse();
}</pre>
<p>ContainsAuthorizationHeader() is an extension method on the Request object:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> ContainsAuthorizationHeader(<span class="kwrd">this</span> HttpRequest request)
{
    <span class="kwrd">if</span> (!<span class="kwrd">string</span>.IsNullOrWhiteSpace(request.Headers[<span class="str">&quot;Authorization&quot;</span>]))
    {
        <span class="kwrd">if</span> (request.Headers[<span class="str">&quot;Authorization&quot;</span>].ToLower().StartsWith(“bearer “))
        {
            <span class="kwrd">return</span> <span class="kwrd">true</span>;
        }
    }
    <span class="kwrd">return</span> <span class="kwrd">false</span>;
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;&#160;&#160; whereas SendUnauthorizedResponse() is an extension method on HttpContext:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> SendUnauthorizedResponse(<span class="kwrd">this</span> HttpContext context)
{
    context.Response.StatusCode = (<span class="kwrd">int</span>)HttpStatusCode.Unauthorized;
    context.Response.StatusDescription = “Access Denied“;
    context.Response.Write(“401 Access Denied“);
    context.Response.End();
}</pre>
<p>The last line above will immediately raise the EndRequest event:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> OnEndRequest(<span class="kwrd">object</span> sender, EventArgs args)
{
    var context = (HttpApplication)sender;
    <span class="kwrd">if</span> (context.Response.StatusCode == 401)
    {
        <span class="kwrd">string</span> realm = String.Format(CultureInfo.InvariantCulture, <span class="str">&quot;BASIC Realm=\&quot;{0}\&quot;&quot;</span>, context.Request.Url.AbsolutePath);
        context.Response.AppendHeader(<span class="str">&quot;WWW-Authenticate&quot;</span>, realm);
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>&#160;</p>
<p>The most interesting bits though is found in AuthenticateRequest:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> AuthenticateRequest(HttpRequest request)
{
    <span class="kwrd">string</span> accessToken = request.ExtractSamlTokenFromAuthorizationHeader();
    <span class="kwrd">if</span> (<span class="kwrd">string</span>.IsNullOrWhiteSpace(accessToken))
    {
        <span class="kwrd">return</span> <span class="kwrd">false</span>;
    }
    SecurityToken token;
    <span class="kwrd">using</span> (var stringReader = <span class="kwrd">new</span> StringReader(accessToken))
    {
        var reader = XmlReader.Create(stringReader);
        <span class="kwrd">if</span> (!ServiceConfiguration.SecurityTokenHandlers.CanReadToken(reader))
        {
            <span class="kwrd">return</span> <span class="kwrd">false</span>;
        }
        token = ServiceConfiguration.SecurityTokenHandlers.ReadToken(reader);
    }
    ClaimsIdentityCollection identities = ServiceConfiguration.SecurityTokenHandlers.ValidateToken(token);
    HttpContext.Current.User = <span class="kwrd">new</span> ClaimsPrincipal(identities);

    <span class="kwrd">return</span> <span class="kwrd">true</span>;
}</pre>
<p>In&#160; AuthenticateRequest above we first extract the SAML token from the authorization header with the help of the following extension method:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> ExtractSamlTokenFromAuthorizationHeader(<span class="kwrd">this</span> HttpRequest request)
{
    <span class="kwrd">string</span> token;
    <span class="kwrd">string</span> authHeader = request.Headers[<span class="str">&quot;Authorization&quot;</span>];

    <span class="kwrd">if</span> (<span class="kwrd">string</span>.IsNullOrEmpty(authHeader))
    {
        token = <span class="kwrd">string</span>.Empty;
    }
    <span class="kwrd">else</span>
    {
        <span class="kwrd">const</span> <span class="kwrd">string</span> header = <span class="str">&quot;bearer &quot;</span>;
        <span class="kwrd">if</span> (<span class="kwrd">string</span>.CompareOrdinal(authHeader, 0, header, 0, header.Length) == 0)
        {
            token = authHeader.Remove(0, header.Length);
        }
        <span class="kwrd">else</span>
        {
            token = <span class="kwrd">string</span>.Empty;
        }
    }
    <span class="kwrd">return</span> token;
}</pre>
<p>We then check to see if the security token handler that we have configured in the WIF section of web.config can read the token, and given that it can, we tell it to validate the token.<br />
  <br />Now we can create a new IClaimsPrincipal object and assigns it to the current HTTPContext user. </p>
<p>Finally we want to enable the HTTP module by adding it to the module collection in web.config: </p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">modules</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">name</span><span class="kwrd">=&quot;WifEnablingModule&quot;</span> <span class="attr">type</span><span class="kwrd">=&quot;Jayway.IdentityModel.WifEnablingModule, …&quot;</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">name</span><span class="kwrd">=&quot;UrlRoutingModule&quot;</span> <span class="attr">type</span><span class="kwrd">=&quot;System.Web.Routing.UrlRoutingModule, System.Web, … &quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">modules</span><span class="kwrd">&gt;</span></pre>
<p>We also need to register routes for our secured services in the global.asax.cs. </p>
<p>Summary: The focus in this post has been on how to secure a REST API, acting as a simple OAuth Resource Server, and built on WCF and ASP.NET by implementing a custom HTTP module and there by adding some custom code into the request pipeline where we extract a SAML token and hand it over to WIF to do its token authentication. </p>
<p>In <a href="http://blog.jayway.com/2012/01/28/secure-your-rest-based-wcf-service-with-wif-part-2/" target="_blank">part two</a> we’ll talke a look on how to initialize the WIF configuration programmatically and also how to configure the WIF pipeline in the web.config file.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/01/05/secure-your-rest-based-wcf-service-with-wif-part-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Graphite with .Net and Ubuntu 11.10</title>
		<link>http://blog.jayway.com/2012/01/04/graphite-with-dotnet-and-ubuntu-11-10/</link>
		<comments>http://blog.jayway.com/2012/01/04/graphite-with-dotnet-and-ubuntu-11-10/#comments</comments>
		<pubDate>Tue, 03 Jan 2012 23:00:57 +0000</pubDate>
		<dc:creator>Henrik Feldt</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[devops]]></category>
		<category><![CDATA[graphing]]></category>
		<category><![CDATA[graphite]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[statsd]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11635</guid>
		<description><![CDATA[This is a quick write-up on how to get started with graphite as a .Net developer. We're going to start using graphite with a virtual machine in VirtualBox, although you could use something else also. Steps: Download/install VirtualBox Download/install Ubuntu Download/install Graphite Expose VM to network Use Graphite from C# Download/install VirtualBox Start by downloading [...]]]></description>
			<content:encoded><![CDATA[<p>This is a quick write-up on how to get started with graphite as a .Net developer. We're going to start using graphite with a virtual machine in VirtualBox, although you could use <span title="VmWare Player, Fusion, Workstation, ESXi, MS Virtual Machine, HyperV or any other virtualisation software you care for">something else also</span>.</p>
<p>Steps:</p>
<ol>
<li><a href="#virtualbox">Download/install VirtualBox</a></li>
<li><a href="#ubuntu">Download/install Ubuntu</a></li>
<li><a href="#graphite">Download/install Graphite</a></li>
<li><a href="#expose">Expose VM to network</a></li>
<li><a href="#csharp">Use Graphite from C#</a></li>
</ol>
<h2 id="virtualbox">Download/install VirtualBox</h2>
<p>Start by downloading and <a href="https://www.virtualbox.org/wiki/Downloads">installing virtualbox.</a></p>
<p>The installer is a "Next - next - next" type of installer, so just click through it.</p>
<h2 id="ubuntu">Download/install Ubuntu</h2>
<p>Once installed, download and <a href="http://www.ubuntu.com/download/ubuntu/download">install ubuntu</a> as a new virtual machine.</p>
<p>Now, what you have to do is to bring up a terminal window. Press <span class="key">Win</span> and type <code class="typed-text">Terminal</code> in the input field and launch the terminal.</p>
<h3>A bit on the terminal and sudo</h3>
<p>When working with a linux, you have to type <code class="typed-text">sudo</code> before any command that makes changes to 'root'-owned directories such as <code class="directory">/etc/</code> and <code class="directory">/opt/</code> where we are going to install graphite, Apache and other dependencies.</p>
<p><code class="typed-text">pushd</code> pushes a folder onto an in-memory stack and changes the current directory to the first argument, while <code class="typed-text">popd</code> pops the stack and moves to the previous directory.</p>
<p>You can paste into the terminal with [CTRL]+[SHIFT]+[V] and copy with [CTRL]+[SHIFT]+[C]. Another tab in the terminal is created with [CTRL]+[SHIFT]+[T] - this can be nice to have if you want to look up data about your VM, such as its ip (with 'ifconfig').</p>
<h2 id="graphite">Installing Graphite</h2>
<p>This gist contains the commands you can use to install graphite.</p>
<p><script src="https://gist.github.com/1555553.js?file=bash"></script></p>
<p>When you have followed the gist, try to navigate to <code class="url">http://127.0.0.1</code> or <code class="url">http://[::1]/</code> from Firefox. You should be able to see the graphite start page.</p>
<h2 id="expose">Expose the VM to the network</h2>
<p>When you have a graphite installation, you likely want to start logging things into it - perhaps you already have a piece of software you want to enable metrics from. In order to reach the virtual machine from other computers on the network.</p>
<p>In order to do this, shut down the virtual machine and change its network interface to be 'bridged' - this is in order to let your <abbr>DHCP</abbr> server give the server and <abbr>IP</abbr> rather than only having access to it through your private computer-LAN-to-VM (<abbr>NAT</abbr>ted). Change the following: Machine Settings > Network > Adapter 1 > Attached to: [Bridged].</p>
<p>Start the virtual machine again.</p>
<p>Now check with <code class="typed-text">ifconfig</code> from the <code class="typed-text">Terminal</code> what IP the machine has, and navigate to that IP from your main development operating system. You should be able to see the graphite install now and the example data you added (from the last line of the gist).</p>
<h2 id="csharp">Use the graphite from C#</h2>
<p>Now it's time to log some data with C# into your brand new graphite install!</p>
<p>Open VS and create a new console application. Using Tools > Library Package Manager > Package Manager Console, type "install-package Graphite.NET", targeting your new console project.</p>
<p>Then type this code in the main method (put a <code>using Graphite;</code> directive on top):</p>
<p><script src="https://gist.github.com/1557425.js?file=gistfile1.cs"></script></p>
<p>Try and run the program!</p>
<p>Now you should have some nice data point in graphite! Zoom in the latest minute so that you can see them.</p>
<h4>References:<br />
<h4>
<ul>
<li>Michael Grace - http://geek.michaelgrace.org/2011/09/how-to-install-graphite-on-ubuntu/</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2012/01/04/graphite-with-dotnet-and-ubuntu-11-10/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>N2CMS, TinyMCE and cufon</title>
		<link>http://blog.jayway.com/2011/12/14/n2cms-tinymce-and-cufon/</link>
		<comments>http://blog.jayway.com/2011/12/14/n2cms-tinymce-and-cufon/#comments</comments>
		<pubDate>Wed, 14 Dec 2011 14:17:31 +0000</pubDate>
		<dc:creator>Anders Poulsen</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[N2CMS]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11555</guid>
		<description><![CDATA[Problem On http://www.leanonme.net/ we use cufon to create text with special stylized fonts. This presents a challenge in cases such as the one above, where the content editor should be able to mix regular font with cufon-enabled font. We have solve the problem by integrating custom formatting directly in the TinyMCE editor, which N2CMS uses [...]]]></description>
			<content:encoded><![CDATA[<h1>Problem</h1>
<p>On <a href="http://www.leanonme.net/" target="_blank">http://www.leanonme.net/</a> we use cufon to create text with special stylized fonts.<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/MixedCufonExample.png" rel="lightbox"><img class="alignnone size-full wp-image-11559" title="MixedCufonExample" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/MixedCufonExample.png" alt="" width="619" height="64" /></a></p>
<p>This presents a challenge in cases such as the one above, where the content editor should be able to mix regular font with cufon-enabled font.<br />
We have solve the problem by integrating custom formatting directly in the TinyMCE editor, which N2CMS uses as rich text editor:<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/editor.png" rel="lightbox"><img class="alignnone size-full wp-image-11560" title="editor" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/editor.png" alt="" width="441" height="235" /></a></p>
<p>The purpose of this page is to describe how to enable custom formatting in the N2CMS rich text editor, since it is really not very well documented anywhere else.</p>
<h1>Solution</h1>
<p>With N2CMS it is possible to configure the TinyMCE editor from your web.config.</p>
<pre>&lt;n2&gt;
 &lt;edit&gt;
 &lt;tinyMCE enabled="true" cssUrl="~/Content/css/editor.css"&gt;
 &lt;settings&gt;
 &lt;add key="formats" value="{cufon : {inline : 'span', classes : 'cufon'}}" /&gt;
 &lt;add key="theme_advanced_blockformats" value="p,pre,h1,h2,h3,h4,cufon"/&gt;
 &lt;/settings&gt;
 &lt;/tinyMCE&gt;
 &lt;/edit&gt;
&lt;/n2&gt;</pre>
<h2>css classes in TinyMCE</h2>
<p>The cssUrl points to a stylesheet, which has two purposes:<br />
1. It defines how text is displayed in the TinyMCE editor</p>
<p>2. It defines classes that TinyMCE will pick up on<br />
If the css files contains:</p>
<pre>a.pdf
{
 display: block;
 height: 22px;
 padding-left: 25px;
 padding-top: 5px;
 background-image: url(/Content/images/icons/icn_pdf.png);
 background-repeat: no-repeat;
}

a.disclaimerpopup{}
.cufon
{
 font-style: italic;
 font-weight: bold;
 font-family: Comic Sans MS, Lucida Handwriting;
 font-size: larger;
}
a.popup{}</pre>
<p>Then the TinyMCE editor will allow you to select the 'pdf', 'disclaimerpopup', 'cufon' and 'popup' classes on elements:<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/TinyMCEClassesLink.png" rel="lightbox"><img class="alignnone size-full wp-image-11564" title="TinyMCEClassesLink" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/TinyMCEClassesLink.png" alt="" width="500" height="436" /></a><br />
And if you set e.g. the 'pdf' class on a link, the the link will be displayed inside the rich text editor with the styling, that was defined in the css pointed to by web.config<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/TinyMCELinkPdf.png" rel="lightbox"><img title="TinyMCELinkPdf" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/TinyMCELinkPdf.png" alt="" width="125" height="135" /></a></p>
<h2>Advanced formatting</h2>
<p>The lines</p>
<pre>&lt;settings&gt;
 &lt;add key="formats" value="{cufon : {inline : 'span', classes : 'cufon'}}" /&gt;
 &lt;add key="theme_advanced_blockformats" value="p,pre,h1,h2,h3,h4,cufon"/&gt;
 &lt;/settings&gt;</pre>
<p>control the formatting available in the drop down box:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/TinyMCEFormatDropDown.png" rel="lightbox"><img class="alignnone size-full wp-image-11565" title="TinyMCEFormatDropDown" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/TinyMCEFormatDropDown.png" alt="" width="185" height="220" /></a></p>
<p>The line</p>
<pre>&lt;add key="theme_advanced_blockformats" value="p,pre,h1,h2,h3,h4,cufon"/&gt;</pre>
<p>controls what can be chosen. In this case the standard tags p, pre, h1, etc. are available + an additional formatting called 'cufon'.</p>
<p>TinyMCE knows what to do with the standard tags, but it doesn't know how to handle 'cufon'.</p>
<p>The line</p>
<pre>&lt;add key="formats" value="{cufon : {inline : 'span', classes : 'cufon'}}" /&gt;</pre>
<p>tells TinyMCE that text chosen to be 'cufon' should be inline styled with</p>
<pre>&lt;span class='cufon'&gt;</pre>
<p>Combine this with a stylesheet or jquery script to properly style/handle 'span.cufon' and we are almost ready to rumble.</p>
<p>But there is one problem left. The drop down box contains the cufon-formatting, but the 'cufon' entry is missing:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/TinyMCEFormatDropDownCufonMissing.png" rel="lightbox"><img class="alignnone size-full wp-image-11567" title="TinyMCEFormatDropDownCufonMissing" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/TinyMCEFormatDropDownCufonMissing.png" alt="" width="186" height="202" /></a></p>
<p>The reason is that TinyMCE keeps the texts for the front-end in translation files. To solve this, you must first add</p>
<pre>cufon:"advanced.cufon"</pre>
<p>in the function _createBlockFormats in \N2\Resources\tiny_mce\themes\advanced\editor_template.js so TinyMCE knows which key to look for in the translation file. Then you must add</p>
<pre>cufon:"Cufon"</pre>
<p>in \N2\Resources\tiny_mce\themes\advanced\langs\en.js, which contains the english translations used by TinyMCE.<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/TinyMCEFormatDropDownNoStyle.png" rel="lightbox"><img class="alignnone size-full wp-image-11571" title="TinyMCEFormatDropDownNoStyle" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/TinyMCEFormatDropDownNoStyle.png" alt="" width="194" height="228" /></a></p>
<p>Finally you might want to style the cufon entry in the drop down list. This is done in \N2\Resources\tiny_mce\themes\advanced\skins\default\ui.css by adding the line</p>
<pre>.defaultSkin .mce_cufon span.mceText {font-style: italic;font-weight: bold;font-family: Comic Sans MS, Lucida Handwriting;font-size: larger;</pre>
<p>and the final result is:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/TinyMCEFormatDropDown1.png" rel="lightbox"><img class="alignnone size-full wp-image-11572" title="TinyMCEFormatDropDown" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/TinyMCEFormatDropDown1.png" alt="" width="185" height="220" /></a></p>
<h1>References</h1>
<p>N2CMS: <a href="http://n2cms.codeplex.com" target="_blank">http://n2cms.codeplex.com</a></p>
<p>&nbsp;</p>
<p>TinyMCE custom formatting <a href="http://www.tinymce.com/wiki.php/Configuration:formats" target="_blank">http://www.tinymce.com/wiki.php/Configuration:formats</a></p>
<p>TinyMCE advanced blockformats: <a href="http://www.tinymce.com/wiki.php/Configuration:theme_advanced_blockformats" target="_blank">http://www.tinymce.com/wiki.php/Configuration:theme_advanced_blockformats</a></p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/14/n2cms-tinymce-and-cufon/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Possible pitfall when using EF Migrations</title>
		<link>http://blog.jayway.com/2011/12/14/possible-pitfall-when-using-ef-migrations/</link>
		<comments>http://blog.jayway.com/2011/12/14/possible-pitfall-when-using-ef-migrations/#comments</comments>
		<pubDate>Wed, 14 Dec 2011 09:35:23 +0000</pubDate>
		<dc:creator>Per Ökvist</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[entity framework]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11541</guid>
		<description><![CDATA[Recently the EF migrations package reached version 0.8 beta. The goal is to include this in the upcoming EF release.&#160; Today EF code first has a simple model of initializers. This solves simple scenarios when developing and changing model or deploying a brand new instance. Migrations continues the story, to handle just that. Migrations. Change [...]]]></description>
			<content:encoded><![CDATA[<p>Recently the EF migrations package reached <a href="http://blogs.msdn.com/b/adonet/archive/2011/11/29/code-first-migrations-beta-1-released.aspx">version 0.8 beta</a>. The goal is to include this in the upcoming EF release.&#160; Today EF code first has a simple model of initializers. This solves simple scenarios when developing and changing model or deploying a brand new instance.</p>
<p>Migrations continues the story, to handle just that. Migrations. Change of your model during the lifetime of your application.</p>
<h2>Introduction</h2>
<p>Migrations offers automatic migrations or non automatic migrations. In the latter there are two key parts. <em>DbMigrationsConfiguration&lt;TContext&gt;</em> and <em>DbMigration</em>.&#160; Configuration is for settings like automatic migrations and allowing data loss. The former responsibility of the Initializer to seed data also resides in configuration. Now seeding is done when all migrations has run. The DbMigration class describes the model changes to update or downgrade the database.</p>
<h2>What I learned </h2>
<p>The order of sets in your context matters! The convention for naming relation tables may choose different name depending on the order. This can cause some nasty things in your migrations! </p>
<p>Lets say we have a model where Foo and Bar have a many to many relationship. EF might represent the relationship table as FooBars.</p>
<p>If we later add to our model some other object relation to Foo or Bar and update our Context, EF may then represent the same relation as BarFoos. This has nothing to do with migrations, it has to do with the <a href="http://stackoverflow.com/questions/7933276/entity-framework-many-to-many-relationship/7935702#7935702">order of your set in the context</a>. You might not have noticed this when working with Initializers, BUT when reviewing generated DbMigration classes you will. In a migration scenario this could also mean that you lose data due to dropping and recreating relationship tables.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/12/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/12/image_thumb.png" width="169" height="244" /></a></p>
<h2>Conclusion</h2>
<p>Some friendly advice is to review your migrations or <a href="http://vincentlauzon.wordpress.com/2011/04/15/entity-framework-4-1-many-to-many-relationships-5/">manually configure</a> naming of relationship tables for full control. </p>
<p>Nice to see migrations as another ingredient added to the 4.5 kettle.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/14/possible-pitfall-when-using-ef-migrations/feed/</wfw:commentRss>
		<slash:comments>0</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>MVC3, Razor and MS Chart Controls in .NET 4</title>
		<link>http://blog.jayway.com/2011/12/11/mvc3-razor-and-ms-charting-tool-net-4/</link>
		<comments>http://blog.jayway.com/2011/12/11/mvc3-razor-and-ms-charting-tool-net-4/#comments</comments>
		<pubDate>Sun, 11 Dec 2011 07:23:05 +0000</pubDate>
		<dc:creator>Henrik Andersson</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/2011/12/11/mvc3-razor-and-ms-charting-tool-net-4/</guid>
		<description><![CDATA[&#160; During this weekend I was elaborating with Microsoft Charting Tool and want with this blog post share the knowledge that I gained. Demo I started with an empty ASP.NET MVC 3 Web Application with the View engine Razor and I selected an Empty template. I added a reference to the assembly System.Web.DataVisualization. Thereafter I [...]]]></description>
			<content:encoded><![CDATA[<p>&#160;</p>
<p>During this weekend I was elaborating with Microsoft Charting Tool and want with this blog post share the knowledge that I gained.</p>
<h2>Demo</h2>
<p>I started with an empty ASP.NET MVC 3 Web Application with the View engine Razor and I selected an Empty template. I added a reference to the assembly System.Web.DataVisualization.</p>
<p>Thereafter I created ViewModel called BarGraphViewModel. </p>
<p>&#160;</p>
<div class="csharpcode">
<pre class="csharpcode"><span class="kwrd">using</span> System.Web.UI.DataVisualization.Charting;

<span class="kwrd">namespace</span> Charters.Models
{
    <span class="kwrd">public</span> <span class="kwrd">class</span> BarGraphViewModel
    {
        <span class="kwrd">public</span> Chart BarChart
        {
            get { <span class="kwrd">return</span> BuildBarChart(); }
        }
        <span class="kwrd">private</span> Chart BuildBarChart()
        {
            var data = <span class="kwrd">new</span> BarData
            {
                xValues = <span class="kwrd">new</span> <span class="kwrd">int</span>[] { 1, 2, 3, 4 },
                yValues = <span class="kwrd">new</span> <span class="kwrd">double</span>[] { 0.3, 0.3, 0.1, 0.7 }
            };
            <span class="kwrd">return</span> BindChartData(data);
        }
        <span class="kwrd">private</span> Chart BindChartData(BarData data)
        {
            Chart chart = <span class="kwrd">new</span> Chart();
            chart.Width = 150;
            chart.Height = 150;

            chart.ChartAreas.Add(<span class="kwrd">new</span> ChartArea());
            chart.Series.Add(<span class="kwrd">new</span> Series());

            chart.Series[0].ChartType = SeriesChartType.Column;
            chart.Series[0].BackGradientStyle = GradientStyle.HorizontalCenter;
            chart.Series[0].BackSecondaryColor = System.Drawing.Color.Black;

            <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; data.xValues.Length; i++)
            {
                <span class="kwrd">int</span> x = data.xValues[i];
                <span class="kwrd">double</span> y = data.yValues[i];
                <span class="kwrd">int</span> ptIdx = chart.Series[0].Points.AddXY(x, y);
                DataPoint pt = chart.Series[0].Points[ptIdx];
            }

            <span class="kwrd">return</span> chart;

        }
    }

    <span class="kwrd">internal</span> <span class="kwrd">class</span> BarData
    {
        <span class="kwrd">public</span> <span class="kwrd">int</span>[] xValues;
        <span class="kwrd">public</span> <span class="kwrd">double</span>[] yValues;
    }

}</pre>
</div>
<p>&#160;</p>
<p>After I created the viewmodel I created the Controller that I called BarGraphController.</p>
<div class="csharpcode">
<pre class="csharpcode"><span class="kwrd">using</span> System.IO;
<span class="kwrd">using</span> System.Web.Mvc;
<span class="kwrd">using</span> Charters.Models;
<span class="kwrd">using</span> System.Web.UI.DataVisualization.Charting;

<span class="kwrd">namespace</span> Charters.Controllers
{
    <span class="kwrd">public</span> <span class="kwrd">class</span> BarGraphController : Controller
    {
        <span class="kwrd">public</span> ActionResult Index()
        {
            <span class="kwrd">return</span> View();
        }

        <span class="kwrd">public</span> ActionResult DrawBarChart()
        {
            var viewModel = <span class="kwrd">new</span> BarGraphViewModel();
            Chart charter = viewModel.BarChart;
            MemoryStream ms = <span class="kwrd">new</span> MemoryStream();
            charter.SaveImage(ms, ChartImageFormat.Png);
            ms.Position = 0;
            <span class="kwrd">return</span> File(ms.GetBuffer(), <span class="str">&quot;image/png&quot;</span>);
        }
    }
}</pre>
</div>
<p>Now it is time to create the view. I selected the Razor view and no strongly-typed view. In the view I added following line of code. </p>
<pre class="csharpcode">&lt;a href=<span class="str">&quot;@Url.Action(&quot;</span>DrawBarChart<span class="str">&quot;,&quot;</span>BarGraph<span class="str">&quot;)&quot;</span>/&gt;Graph
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</pre>
<p>Compile and Run your web application. Don’t forget to enter correct path to the controller. My path are </p>
<div class="csharpcode">
<pre><a href="http://localhost:54217/BarGraph/">http://localhost:54217/BarGraph/</a>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/11/mvc3-razor-and-ms-charting-tool-net-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing Web.config Transformations, Part 1</title>
		<link>http://blog.jayway.com/2011/12/08/testing-web-config-transformations/</link>
		<comments>http://blog.jayway.com/2011/12/08/testing-web-config-transformations/#comments</comments>
		<pubDate>Thu, 08 Dec 2011 20:44:45 +0000</pubDate>
		<dc:creator>Mads Troest</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[Deployment]]></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=11089</guid>
		<description><![CDATA[Web.config transformations is a Microsoft-supported technology for adapting a base configuration to a particular deployment environment. In my previous post, I mentioned how AppHarbor provides an online tool for manually testing transformations. Also, the Visual Studio extension SlowCheetah provides support for manually testing and transformation and diffing them against the base configuration from inside Visual Studio. These [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/dd465326.aspx" target="_blank">Web.config transformations</a> is a Microsoft-supported technology for adapting a base configuration to a particular deployment environment.</p>
<p>In my <a href="http://blog.jayway.com/2011/11/14/web-config-transformations-and-xml-namespaces/" target="_blank">previous post</a>, I mentioned how <a href="http://appharbor.com" target="_blank">AppHarbor</a> provides an <a href="http://webconfigtransformationtester.apphb.com/" target="_blank">online tool</a> for manually testing transformations. Also, the Visual Studio extension <a href="http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5" target="_blank">SlowCheetah</a> provides support for manually testing and transformation and <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/SlowCheetahPreviewTransform.png" target="_blank">diffing</a> them against the base configuration from inside Visual Studio. These tools are useful and may be fine for tinkering with getting a transform just right, but being software professionals, we find it highly desirable to reliably automate our transformation testing.</p>
<p>In this article we shall look at one way to exercise our Web.config transformations from our own code, so that we can TDD our transformations and regression test them as part of our continuous integration cycle, like everything else.</p>
<h2>Starting Point</h2>
<p>The actual Web.config transformation process is normally invoked by MSBuild, as described in detail by Elton Stoneman in <a href="http://geekswithblogs.net/EltonStoneman/archive/2010/08/20/using-msbuild-4.0-web.config-transformation-to-generate-any-config-file.aspx" target="_blank">this post</a>. (One approach to testing the transformations could, thus, be to fork off MSBuild processes on custom build targets, but we'd like to take a less cumbersome route.)</p>
<p>Being an MSBuild task means that the transformation is implemented as an <strong>ITask</strong> realization. The concrete implementation is called <strong>TransformXml</strong> and resides in the <strong>Microsoft.Web.Publishing.Tasks.dll</strong> assembly. Note that this assembly is not pre-installed with Windows/.NET but rather installed along with Visual Studio 2010, typically to <em>C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web</em>). Given that its location is not fixed, you'd probably want to add it to your dependencies folder (caveat emptor: check license terms before passing it around).</p>
<p>From Elton's post, we can also see 3 arguments being passed to the TransformXml task:</p>
<ul>
<li>Source (the XML file to transform)</li>
<li>Transform (the transformation XML file itself)</li>
<li>Destination (the target of the transformed XML file)</li>
</ul>
<p>Armed with that background knowledge, let's move on and try to get the transformation to run outside of the MSBuild environment in which it normally executes. For our experiment, we'll be transforming the following source (<em>app.config</em>):</p>
<pre class="brush: xml;">   &lt;configuration&gt;
     &lt;appSettings&gt;
	   &lt;add key="testKey" value="testValue"/&gt;
     &lt;/appSettings&gt;
   &lt;/configuration&gt;</pre>
<p>The transformation we'll be testing (<em>app.Debug.config</em>) should change the "testValue" of the "testKey" to something transformation specific ("debugValue" in this case):</p>
<pre class="brush: xml;">   &lt;configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"&gt;
     &lt;appSettings&gt;
       &lt;add key="testKey"
            value="debugValue"
            xdt:Locator="Match(key)" xdt:Transform="SetAttributes" /&gt;
     &lt;/appSettings&gt;
   &lt;/configuration&gt;</pre>
<h2>Test Approach</h2>
<p>Our initial stab at automatically testing the transformation will be to invoke the XmlTransform through its outermost interface; i.e. the ITask interface. First, we need to add a reference to <strong>Microsoft.Web.Publishing.Tasks.dll</strong> as mentioned above. Additionally, we need to reference <strong>Microsoft.Build.Framework</strong> and <strong>Microsoft.Build.Utilities.v4.0</strong> (these should be available from your usual <em>Project, Add Reference, .NET </em>tab).</p>
<p>Opening up the XmlTransform class in Visual Studio's Object Browser shows us a single method, <strong>Execute()</strong>, plus a handful of properties, most of which we recognize from Stoneman's previously mentioned post. A little experimentation reveals the following details:</p>
<ul>
<li><strong>SourceRootPath</strong></li>
<ul>
<li>The base path to which the XML file specified in <strong>Source</strong> is relative. If not specified, this will  be the current directory (which, when running from a test runner, would typically be your build target directory).</li>
</ul>
<li><strong>Source</strong></li>
<ul>
<li>The name of the XML source file to be transformed. If this is not an absolute path, it will be relative to the <strong>SourceRootPath</strong>.</li>
</ul>
<li><strong>TransformRootPath</strong></li>
<ul>
<li>The base path to which the XML file specified in <strong>Transform</strong> is relative. If not specified, this will be the same as <strong>SourceRootPath</strong>.</li>
</ul>
<li><strong>Transform</strong></li>
<ul>
<li>The name of the XML transformation to be applied to the source. If this is not an absolute path, it will be relative to the <strong>TransformRootPath</strong>.</li>
</ul>
<li><strong>Destination</strong></li>
<ul>
<li>The name of the resulting transformed XML file. If this is not an absolute path, it will be relative to the current directory (typically your build target directory, in a test context).</li>
</ul>
</ul>
<p>So all we need to do is something like the following, right?</p>
<pre class="brush: csharp;">   var transformer = new TransformXml
   {
      SourceRootPath = @"..\..\..\Jayway.WebTransformTesting\",
      Source = @"app.config",
      Transform = @"app.Debug.config",
      Destination = @"app.transformed.config"
   };
   var transformationSucceeded = transformer.Execute();</pre>
<p>Well, as the <strong>System.InvalidOperationException</strong> with the message <em>"Task attempted to log before it was initialized" </em>thrown in our face subtly tells us, this is not quite the case...</p>
<p>Investigating the task implementation with Reflector shows the problem to be due to the fact that a property, <strong>BuildEngine</strong>, of the Task base class has not been set. It is used as a dependency injection mechanism, giving the task access to some environment services (see <a href="http://msdn.microsoft.com/en-us/library/microsoft.build.framework.ibuildengine.aspx" target="_blank">IBuildEngine</a> on MSDN) normally provided by MSBuild.</p>
<p>Well, the whole purpose of this experiment was to run outside of MSBuild, so we'll roll our own "build engine" instead:</p>
<pre class="brush: csharp;">   public class BuildEngineForTest : IBuildEngine
   {
      public void LogErrorEvent(BuildErrorEventArgs e)
      {
         Console.WriteLine(LogFormat, "ERROR", e.Message);
      }

      public void LogWarningEvent(BuildWarningEventArgs e)
      {
         Console.WriteLine(LogFormat, "WARNING", e.Message);
      }

      public void LogMessageEvent(BuildMessageEventArgs e)
      {
         Console.WriteLine(LogFormat, e.Importance, e.Message);
      }

      public void LogCustomEvent(CustomBuildEventArgs e)
      {
         Console.WriteLine(LogFormat, "CUSTOM", e.Message);
      }

      public bool BuildProjectFile(
         string projectFileName, string[] targetNames,
         IDictionary globalProperties, IDictionary targetOutputs)
      {
         return true;
      }

      public bool ContinueOnError
      {
         get { return true; }
      }

      public int LineNumberOfTaskNode
      {
         get { return 0; }
      }

      public int ColumnNumberOfTaskNode
      {
         get { return 0; }
      }

      public string ProjectFileOfTaskNode
      {
         get { return string.Empty; }
      }

      private const string LogFormat = "{0} : {1}";
   }</pre>
<p>This was the piece we were missing to be able to run the transformation outside MSBuild. We are, thus, able to write our coveted test:</p>
<pre class="brush: csharp;">...
   [Test]
   public void ApplyingDebugTransformationToConfigurationSetsExpectedKey()
   {
      const string targetFile = @"app.transformed.config";

      var transformer = new TransformXml
      {
         BuildEngine = new BuildEngineForTest(),
         SourceRootPath = @"..\..\..\Jayway.WebTransformTesting\",
         Source = @"app.config",
         Transform = @"app.Debug.config",
         Destination = targetFile
      };

      // Left as exercise for the reader... ;]
      AssertKeyInTransformedFile(targetFile);
   }
...</pre>
<p>Our transformation runs successfully, yielding the following console output from our "build engine":</p>
<pre>Normal : Transforming Source File: ..\..\..\Jayway.WebTransformTesting\app.config
Normal : Applying Transform File: ..\..\..\Jayway.WebTransformTesting\app.Debug.config
Low : Executing SetAttributes (transform line 6, 35)
Low : on /configuration/appSettings/add[@key='testKey']
Low : Applying to 'add' element (source line 4, 6)
Low : Set 'key' attribute
Low : Set 'value' attribute
Low : Set 2 attributes
Low : Done executing SetAttributes
Normal : Output File: app.transformed.config
Normal : Transformation succeeded</pre>
<p>Yay? Yay.</p>
<h2>Conclusion</h2>
<p>We have shown how Web.config Transformations can be invoked programmatically, outside the MSBuild process by providing a simple custom IBuildEngine realization; a technique that might prove useful for other scenarios as well.</p>
<p>We have applied that knowledge to enable automated testing of our transformations.</p>
<p>In my next post in this series, we'll continue our investigation, aiming to get rid of the whole, nasty detour around the file system.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/08/testing-web-config-transformations/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>WinRM w/ self-signed certificate in 4 steps</title>
		<link>http://blog.jayway.com/2011/11/21/winrm-w-self-signed-certificate-in-4-steps/</link>
		<comments>http://blog.jayway.com/2011/11/21/winrm-w-self-signed-certificate-in-4-steps/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 16:36:07 +0000</pubDate>
		<dc:creator>Henrik Feldt</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[devops]]></category>

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

		<guid isPermaLink="false">http://blog.jayway.com/?p=10833</guid>
		<description><![CDATA[In this post we’ll highlight a feature in the MEF 2 preview 4, that by convention registers parts in our mvc application. This so we can use it for DI scenarios. Why? What the we also found was that applications using MEF for extensibility would also use it for internal composition, a-la IoC. From Nicholas [...]]]></description>
			<content:encoded><![CDATA[<p>In this post we’ll highlight a feature in the <a href="http://mef.codeplex.com/">MEF 2 preview 4</a>, that by convention registers parts in our mvc application. This so we can use it for DI scenarios.</p>
<h2>Why?</h2>
<p><a href="http://nblumhardt.com/2011/10/convention-based-part-registration-available-in-a-new-mef-preview/#more-320"><em>What the we also found was that applications using MEF for extensibility would also use it for internal composition, a-la IoC</em></a>. From Nicholas Blumhardt’s <a href="http://nblumhardt.com">blog</a>.</p>
<h2>Demo</h2>
<p>First we need to download and reference <em>System.ComponentModel.Composition.Web.Mvc.CodePlex.dll </em>from <a href="http://mef.codeplex.com/">codeplex</a>.</p>
<p>In my <a href="http://blog.jayway.com/2011/11/02/using-jsviews-mvchaack-prototype-to-update-multiple-records-in-asp-mvc/">last post</a> we started off with a simple model that we scaffold. We’re going to use the same model here.</p>
<pre class="brush: csharp;">Scaffold Controller Pizza –Repository</pre>
<p>
  <br />When were done our controller has a constructor that takes <em>IPizzaRepository</em>. (Remove the parameter less constructor)</p>
<p></p>
<pre class="brush: csharp;">   public PizzasController(IPizzaRepository pizzaRepository)
        {
            this.pizzaRepository = pizzaRepository;
        }</pre>
<p>Time to let MEF wire up this dependency. The convention for auto wire is based on namespace. The repository needs to be under a namespace path of <em>.Parts.</em> ex <em>Pizza.App.Parts.PizzaRepository.</em> So to get this working all we need is to move the generated repository to a Parts folder and adjust the namespace, and done!</p>
<p>Run the app and the dependency for PizzaController will be wired up. This is the simple scenario with no configuration just auto magic. There is also a way for you to configure this more in detail manually, check this <a href="http://blogs.msdn.com/b/bclteam/archive/2011/11/01/getting-started-with-convention-based-part-registration-in-mef-version-2.aspx">BCL Team </a>post for more on convention-based part registration.</p>
<p>The convention also works with namespaces with Parts in it. We’ll do a quick fix in the demo code. Lets make an quick interface for our EF context.</p>
<pre class="brush: csharp;">    public interface IPizzaContext
    {
        IDbSet&lt;Pizza&gt; Pizzas { get; set; }

        int SaveChanges();

        DbEntityEntry Entry(object entity);
    }</pre>
<p>
  <br />Then we fix the constructor of the Pizza Repository to match.</p>
<p></p>
<pre class="brush: csharp;">    private IPizzaContext context;

        public PizzaRepository(IPizzaContext context)
        {
            this.context = context;
        }</pre>
<p>The we put the context in a <em>Data </em>folder in the <em>Parts</em> folder and fix the namespace to match. Run the app and all should be wired up. Neat!</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/mvc_mef2_post.png" rel="lightbox"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="mvc_mef2_post" border="0" alt="mvc_mef2_post" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/11/mvc_mef2_post_thumb.png" width="244" height="164" /></a></p>
<p>Of course this is a simple demo, with no consideration of life time management etc.</p>
<h2>Conclusion</h2>
<p>A lot is happening around .NET web with <a href="http://aspnet.codeplex.com/wikipage?title=MVC&amp;referringTitle=Home">ASP.NET MVC</a> and <a href="http://wcf.codeplex.com/">WCF Web Api</a> and the <a href="https://twitter.com/#!/gblock/status/132305937754103809">integration</a> between the two. Interesting to see what <em>“Simplifying the use of MEF in web applications is a core goal of the new release.” (</em><a href="http://blogs.msdn.com/b/bclteam/archive/2011/10/27/what-s-new-in-mef-version-2-preview-4.aspx"><em>post</em></a><em>) </em>could add to the 4.5 web story.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/08/auto-wiring-parts-in-asp-net-mvc-with-mef-2/feed/</wfw:commentRss>
		<slash:comments>3</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>Using JsViews + MVCHaack Prototype to update multiple records in ASP.NET MVC</title>
		<link>http://blog.jayway.com/2011/11/02/using-jsviews-mvchaack-prototype-to-update-multiple-records-in-asp-mvc/</link>
		<comments>http://blog.jayway.com/2011/11/02/using-jsviews-mvchaack-prototype-to-update-multiple-records-in-asp-mvc/#comments</comments>
		<pubDate>Wed, 02 Nov 2011 09:25:23 +0000</pubDate>
		<dc:creator>Per Ökvist</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10730</guid>
		<description><![CDATA[In this post we’ll take a look at two quite new things. JSViews and the MVCHaack prototype, in a simple scenario in which we’ll update multiple records in an mvc app. First what is what. Intro JsViews, is the next generation of jQuery templates and data link, divided in two parts JsRender and JsViews. On [...]]]></description>
			<content:encoded><![CDATA[<p>In this post we’ll take a look at two quite new things. JSViews and the MVCHaack prototype, in a simple scenario in which we’ll update multiple records in an mvc app.</p>
<p>First what is what.</p>
<h2>Intro</h2>
<p><strong>JsViews</strong>, is the next generation of jQuery templates and data link, divided in two parts JsRender and JsViews. On <a href="https://github.com/BorisMoore/jsviews">github</a> introduced as “<em>Interactive data-driven views, built on top of JsRender templates”. </em>For more info check out the blog <a href="http://www.borismoore.com/">Dancing with data</a> by Boris Moore.</p>
<p><strong>MvcHaack.Ajax</strong> is a <em>“proof-of-concept prototype” </em>by <a href="http://haacked.com/archive/2011/08/18/calling-asp-net-mvc-action-methods-from-javascript.aspx">Phil Haack</a><em>&#160;</em>to ease access to mvc actions from javascript. Available as a <a href="http://nuget.org/List/Packages/MvcHaack.Ajax">nuget package</a>. </p>
<h2>Demo</h2>
<p>To use this two in a update scenario we’re using a simple model of a Pizza.</p>
<pre class="brush: csharp;">    public class Pizza
    {
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }

        public double Price { get; set; }

        public bool Available { get; set; }
    }</pre>
<p>We’ll scaffold the model, using <a href="http://nuget.org/List/Packages/MvcScaffolding">MvcScaffolding.</a></p>
<pre class="brush: csharp;">

Scaffold Controller Pizza –Repository

&#160;
</pre>
<p>So now we have the needed base to start using MvcHaack.Ajax.</p>
<p>We’ll edit the PizzaController to look like.</p>
<pre class="brush: csharp;">  public class PizzaController :  MvcHaack.Ajax.JsonController
    {
        private readonly IPizzaRepository pizzaRepository;

        public PizzaController(IPizzaRepository pizzaRepository)
        {
            this.pizzaRepository = pizzaRepository;
        }

        public IEnumerable&lt;Pizza&gt; List()
        {
            return this.pizzaRepository.All;
        }

        public object SaveList(List&lt;Pizza&gt; pizzas)
        {
            pizzas.ForEach(x =&gt; this.pizzaRepository.InsertOrUpdate(x));
            this.pizzaRepository.Save();

            return new { success = true, pizzas = pizzas };
        }

    }</pre>
<p>First thing to note is that we derive from a base controller from the MvcHaack library. Second we don’t return ActionResults. Other than that there isn’t much strange things going on. We’re using injection of IPizzaRepository here, if you like you could keep the instantiation of the repository generated by the scaffolding template.</p>
<p>Ok, now how do we put this to use and gain ease of access to this controller from jQuery ? </p>
<p>First we’ll need to add a special route (code shown using an area).</p>
<pre class="brush: csharp;">context.Routes.Add(new JsonRoute(&quot;json/{controller}&quot;));</pre>
<p>The we’re off to the client side! In our view we now add;</p>
<pre class="brush: csharp;">&lt;script src=&quot;/json/haack?json&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;</pre>
<p>This is where the magic of MvcHaack comes in to play. This will generate an access point to our actions. Please take a look in the generated script. Its simple but as often with simple - useful.</p>
<p>This gives us the following access points to our actions. Neat!</p>
<pre class="brush: js;">

     $mvc.Pizza.List().success(function(data) {
                ....
     });


     $mvc.Pizza.SaveList(pizzasJson).success(function(data) {&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ....&#160; &#160;&#160;&#160;&#160; });
</pre>
<p>Now we’ll switch over to put JsViews to use. First we’ll need some scripts for JsViews.</p>
<pre class="brush: js;">    &lt;script src=&quot;http://borismoore.github.com/jsviews/jsrender.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;http://borismoore.github.com/jsviews/jquery.observable.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;http://borismoore.github.com/jsviews/jquery.views.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;</pre>
<p>Then we’ll add a table to hold our pizzas and the a jQueryTemplate (JsRender) to display each pizza in edit mode. Then a save button.</p>
<pre class="brush: js;">&lt;button id=&quot;sendJson&quot;&gt;Send Json&lt;/button&gt;

&lt;table&gt;&lt;tbody id=&quot;editPizzaTable&quot;&gt;&lt;/tbody&gt;&lt;/table&gt;

&lt;script id=&quot;editRowTmpl&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
&lt;tr&gt;
    &lt;td data-getfrom=&quot;[Name]&quot; /&gt;
    &lt;td&gt;
        &lt;input data-getfrom=&quot;[Name]&quot; data-to=&quot;[Name]&quot; /&gt;
    &lt;/td&gt;
&lt;/tr&gt;
&lt;/script&gt;</pre>
<p>Ok, this ain’t an ordinary template. It contains some JsViews binding specific attributes. This from and to attributes lets you track changes to your json object that we bound to template. Note that I only show Name here, you could add the other properties too.</p>
<p>And now how do we bind to this template ? Simple;</p>
<pre class="brush: js;">$(&quot;#editPizzaTable&quot;).link(pizzas, &quot;#editRowTmpl&quot;);</pre>
<p>The magic lies in the link operator here, that tells JsViews to track changes to our pizzas. Interested or confused ? Check out <a href="http://borismoore.github.com/jsviews/demos/jQueryConfDemosOct2011/index.html">Booris samples</a> to get the whole picture.</p>
<p>So all we need to do is tie this two things together. My demo module looks like.</p>
<pre class="brush: js;">if (!Jayway) { var Jayway = {}; }
if (!Jayway.Demos) { Jayway.Demos = {}; }

Jayway.Demos = lib(function () {
    var app = {
        pizzas: null
    };
    return {
        // Public functions
        init: function() {

            $mvc.Pizza.List().success(function(data) {
                app.pizzas = data;
                _render();

            });

            $('#sendJson').click(function() {
                $mvc.Pizza.SaveList(app.pizzas).success(function(data) {
                    alert(data.success);
                });
            });
        }
    };

    //Private
    function _render() {
        $(&quot;#editPizzaTable&quot;).link(app.pizzas, &quot;#editRowTmpl&quot;);
    }
} ());</pre>
<h2>Conclusion</h2>
<p>We looked at JsViews in a context where often <a href="http://knockoutjs.com/">Knockout</a> or <a href="http://documentcloud.github.com/backbone/">Backbone</a> could be mentioned. I’ll hope you’ll follow the project to see in what scenarios this could be helpful for you.</p>
<p>MvcHaack.Ajax is a prototype with a question attached. Would you like to see something like this in ASP.NET MVC 4 ?</p>
<p>It’s simple and does not interfere with other library choices, so I think that it would be a neat addition.</p>
<p>Enjoy!&#160; </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/02/using-jsviews-mvchaack-prototype-to-update-multiple-records-in-asp-mvc/feed/</wfw:commentRss>
		<slash:comments>1</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>
	</channel>
</rss>

