<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:a10="http://www.w3.org/2005/Atom" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel xml:base="http://mark.mymonster.nl/"><title>Mark Monster's Blog</title><description>This weblog from Mark Monster covers multiple topics, related to Microsoft technology like: .NET, Silverlight, Windows Phone 7</description><language>en-US</language><a10:author><a10:name>Mark Monster</a10:name></a10:author><lastBuildDate>Sun, 20 May 2012 14:40:29 +0200</lastBuildDate><generator>MC Blog Engine v1.0</generator><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/MarkMonster" /><feedburner:info uri="markmonster" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/7Zu_LZ-xBSs/mimic-the-game-hub-application-bar-with-a-behavior-on-the-bindableapplicationbar</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Patterns</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>WPDev</category><title>Mimic the Game Hub Application Bar with a Behavior on the BindableApplicationBar</title><description>&lt;p&gt;A couple of days ago &lt;a href="http://dotnetapp.com/blog/2012/05/16/how-to-mimic-the-application-bar-of-the-game-hub-and-to-avoid-the-splash-screen-bug/"&gt;Sébastien Lachance wrote an excellent article about mimicking the application bar of the game hub&lt;/a&gt;. Really interesting for one of my applications which makes use of a minimal applicationbar that’s also transparant. However quite often the texts of the menu are difficult to read when they don’t have a solid backgroud. That’s exactly what is solved in the game hub: a transparant applicationbar, but when expanded to view the menu it has a solid background. And Sébastien also found a solution how to fix this in our own applications.&lt;/p&gt;  &lt;p&gt;However Sébastien is using the ApplicationBar, I’m using the wrapper around the ApplicationBar, called &lt;a href="http://phone7.codeplex.com/"&gt;BindableApplicationBar that’s part of the Phone7.Fx project&lt;/a&gt;. So how to solve this? &lt;/p&gt;  &lt;p&gt;The ApplicationBar and BindableApplicationBar both implement the &lt;a href="http://msdn.microsoft.com/en-us/library/microsoft.phone.shell.iapplicationbar_events(v=vs.92)"&gt;IApplicationBar interface which prescribes the StateChanged event&lt;/a&gt; that is used by Sébastien in his solution. So it looks like we can use the same event, let’s look a little bit closer…&lt;/p&gt;  &lt;p&gt;Seems that the code inside the BindableApplicationBar never fires the StateChanged event, so let’s fix this with a little bit of code in the BindableApplicationBar. Please be aware that you need to use the source version of the BindableApplicationBar to be able to fix this. So let’s subscribe the underlying ApplicationBar first, we do this in t he constructor of the BindableApplicationBar by adding one line.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:a2ebc6ef-c3dd-4dac-8830-2401aaad3531" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; highlight: [4]"&gt;public BindableApplicationBar()
{
    _applicationBar = new Microsoft.Phone.Shell.ApplicationBar();
    _applicationBar.StateChanged += HandleStateChanged;
    Loaded += BindableApplicationBarLoaded;
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Now we still need to implement the HandleStateChanged method, which is a pretty straight forward implementation you’ve probably seen thousands of times.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:8b9b5ecd-aa1e-4f56-b790-2d1238e81285" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;private void HandleStateChanged(object sender, ApplicationBarStateChangedEventArgs e)
{
    if (StateChanged != null)
    {
        StateChanged(this, e);
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;So we now have a BindableApplicationBar that has all the features we need to mimic the ApplicationBar of the game hub. The rest of the implementation could be similar to Sébastien’s code. However I thought this is a typical thing that you can easily implement and reuse in a Behavior. I’m not writing behaviors daily, so I thought giving a look at the blog of the &lt;a href="http://dotnetbyexample.blogspot.com"&gt;Behavior Master himself, Joost van Schaik&lt;/a&gt;. About a year ago he wrote a &lt;a href="http://dotnetbyexample.blogspot.com/2011/04/safe-event-detachment-pattern-for.html"&gt;pattern for safe event detachment in behaviors&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;So I started with this pattern as a basis. However my eagerness to make this Behavior perfect by immediately using this pattern caused me a lot of trouble. The pattern also tries to safely remove the events when the AssociatedObject aka Control is unloaded. The control I use is of a special type, the BindableApplicationBar, which immediately calls the unloaded event, don’t know why, but it took me almost an hour to find this out. In the end I did a step back and removed the Safe Pattern, and came to the following behavior. The essence is in the highlighted line where I set the BarOpacity property.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:db00120f-d973-4743-9c5b-c210632de968" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; highlight: [15]"&gt;public class TransparantToFillApplicationBarBehavior : Behavior&amp;lt;BindableApplicationBar&amp;gt;
{
    private double? _originalBarOpacity;

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.StateChanged += StateChanged;
    }

    private void StateChanged(object sender, ApplicationBarStateChangedEventArgs e)
    {
        if (!_originalBarOpacity.HasValue)
            _originalBarOpacity = AssociatedObject.BarOpacity;
        AssociatedObject.BarOpacity = e.IsMenuVisible ? 1 : _originalBarOpacity.Value;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.StateChanged -= StateChanged;
        base.OnDetaching();
    }
}
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;And now you want to use it in your BindableApplicationBar, of course.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:2812948f-dc6a-43b4-890d-33873fbc75d1" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; highlight: [4,5,6]"&gt;&amp;lt;ApplicationBar:BindableApplicationBar Mode=&amp;quot;Minimized&amp;quot;
                                        BarOpacity=&amp;quot;0.6&amp;quot;
                                        IsVisible=&amp;quot;{Binding LoggedIn}&amp;quot; BackgroundColor=&amp;quot;{StaticResource PhoneBackgroundColor}&amp;quot;&amp;gt;
    &amp;lt;i:Interaction.Behaviors&amp;gt;
        &amp;lt;ApplicationBar:TransparantToFillApplicationBarBehavior /&amp;gt;
    &amp;lt;/i:Interaction.Behaviors&amp;gt;
    &amp;lt;ApplicationBar:BindableApplicationBarMenuItem Text=&amp;quot;about+settings&amp;quot;
                                                    Command=&amp;quot;{Binding AboutCommand}&amp;quot; /&amp;gt;
&amp;lt;/ApplicationBar:BindableApplicationBar&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;And the end result is like this. Transparent when the menu is collapsed.&lt;/p&gt;

&lt;p&gt;&lt;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="Transparant" border="0" alt="Transparant" src="http://mark.mymonster.nl/Uploads/2012/05/transparant-3.png" width="484" height="804" /&gt;&lt;/p&gt;

&lt;p&gt;And non-transparent when the menu is visible.&lt;/p&gt;

&lt;p&gt;&lt;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="Fill" border="0" alt="Fill" src="http://mark.mymonster.nl/Uploads/2012/05/fill-3.png" width="484" height="804" /&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/7Zu_LZ-xBSs" height="1" width="1"/&gt;</description><pubDate>Sun, 20 May 2012 14:40:29 +0200</pubDate><a10:updated>2012-05-20T14:40:29+02:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2012/05/20/mimic-the-game-hub-application-bar-with-a-behavior-on-the-bindableapplicationbar</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/FtNtIrq6pfU/google-analytics-on-your-windows-phone-app-in-1-minute</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>IoC</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>WPDev</category><title>Google Analytics on your Windows Phone App in 1 minute</title><description>&lt;p&gt;Yes 1 minute. So let’s start immediately. &lt;/p&gt;  &lt;p&gt;1 - Open the NuGet Package Manager Console and type:&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:2715a60c-5796-41b1-bfbc-ff0a9fa5bea4" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:text; gutter:false; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;Install-Package MSAF.GoogleAnalytics&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;2 - Next, register a new application / web property inside Google Analytics.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2012/05/image-2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 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://mark.mymonster.nl/Uploads/2012/05/image-thumb.png" width="244" height="186" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then copy the Property ID that starts with UA-.&lt;/p&gt;

&lt;p&gt;3 - Past that Property ID inside the App.xaml at this place.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:e4c87d78-11f3-4467-b9a7-c610408509df" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;analytics:GoogleAnalyticsService WebPropertyId=&amp;quot;UA-12345-6&amp;quot; /&amp;gt;&lt;/pre&gt;&lt;/div&gt;





&lt;p&gt;That’s it. Yes, totally. And? Did you do it under the minute?&lt;/p&gt;

&lt;h3&gt;Background information&lt;/h3&gt;

&lt;p&gt;I’ve been in contact with &lt;a href="http://twitter.com/#!/synergist"&gt;Michael Scherotter&lt;/a&gt; for some time about NuGet and &lt;a href="http://msaf.codeplex.com/"&gt;MSAF&lt;/a&gt;, thanks for the support Michael. Basically the MSAF project is really powerful and can be applied to your Windows Phone project quite easily when you know how to do this. I’ve written about it a couple of times. However when we upgraded to Mango all dlls were upgraded except the Google.WebAnalytics dll. The mismatch in versions was causing a lot of problems because some libraries were asking for a 7.0 version of System.Windows.Interactivity and some were asking for the 7.1 version. I fixed that for the NuGet release, everything is 7.1 based. &lt;/p&gt;

&lt;h3&gt;Advanced tracking&lt;/h3&gt;

&lt;p&gt;I also added the code to track a little bit of basic information. You can find that in the GoogleAnalyticsService class in the Analytics folder after applying the NuGet package. There is support for up to 5 Custom Variables. Yes I removed the AppId/ProductId that’s included by default leaving only 4 Custom Variables. You can still add the AppId Custom Variable by your own choice, but I removed it because I have one Google Analytics Web Property per App, so it was useless.&lt;/p&gt;

&lt;p&gt;When you want to track your analytics from for example your ViewModel you do something like this.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:75da5eda-9e4b-4849-9fac-c1609430b7e6" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:false; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;IAnalyticsTracker tracker = new AnalyticsTracker();
tracker.Track(&amp;quot;EventCategory&amp;quot;,&amp;quot;EventName&amp;quot;,&amp;quot;EventValue optional&amp;quot;);&lt;/pre&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/FtNtIrq6pfU" height="1" width="1"/&gt;</description><pubDate>Wed, 16 May 2012 22:33:49 +0200</pubDate><a10:updated>2012-05-16T22:35:09+02:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2012/05/16/google-analytics-on-your-windows-phone-app-in-1-minute</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/yoaajKEel-Q/reset-the-back-of-your-tile-through-push</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Phone</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>WPDev</category><title>Reset the back of your Tile through push</title><description>&lt;p&gt;Have you ever created the back of your tile with a Push notification? You just add some xml in the Notification Message that you send to the Notification Channel.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:083da8d6-49e1-4dfc-9156-8517f754b4ba" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;wp:BackBackgroundImage&amp;gt;http://someurlinthewild.com/BackTileBackground.png&amp;lt;/wp:BackBackgroundImage&amp;gt;
&amp;lt;wp:BackTitle&amp;gt;Back&amp;lt;/wp:BackTitle&amp;gt;
&amp;lt;wp:BackContent&amp;gt;Content&amp;lt;/wp:BackContent&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Yeah that’s easy. Ever tried to get rid of it using a Push notification? Yeah, trying to push without content. Thought that should work as well, didn’t. Leaving the full Xml elements from the Push Notification? Didn’t work either. You explicitly have to add an attribute &lt;strong&gt;Action&lt;/strong&gt; and give it the value &lt;strong&gt;Clear&lt;/strong&gt;, like this:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:7bd7b889-0855-4fa1-b771-521d6a5bc650" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;wp:BackBackgroundImage Action=&amp;quot;Clear&amp;quot;&amp;gt;&amp;lt;/wp:BackBackgroundImage&amp;gt;
&amp;lt;wp:BackTitle Action=&amp;quot;Clear&amp;quot;&amp;gt;&amp;lt;/wp:BackTitle&amp;gt;
&amp;lt;wp:BackContent Action=&amp;quot;Clear&amp;quot;&amp;gt;&amp;lt;/wp:BackContent&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This works for the Title and Count properties for the front of your tile as well. This can all be found in &lt;a href="http://msdn.microsoft.com/en-us/library/hh202945(v=vs.92).aspx"&gt;the documentation for Push Notifications&lt;/a&gt; as well, but today it took me some time to figure this out.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/yoaajKEel-Q" height="1" width="1"/&gt;</description><pubDate>Tue, 21 Feb 2012 21:26:52 +0100</pubDate><a10:updated>2012-02-21T21:26:52+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2012/02/21/reset-the-back-of-your-tile-through-push</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/Yyecr3BEoW4/unified-ad-for-windows-phone-part-4-genericadproviderforxaml</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>advertisement</category><category>Open Source</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>WPDev</category><category>WPUnifiedAd</category><title>Unified Ad for Windows Phone - Part 4 - GenericAdProviderForXaml</title><description>&lt;p&gt;Alright, we have &lt;a href="http://mark.mymonster.nl/2012/02/07/windows-phone-unified-ad-part-1-introduction/"&gt;signed up to a lot of Ad Providers in Part 1&lt;/a&gt;, &lt;a href="http://mark.mymonster.nl/2012/02/08/unified-ad-for-windows-phone-part-2-basic-usage/"&gt;setup the Unified Ad control in Part 2&lt;/a&gt; and even &lt;a href="http://mark.mymonster.nl/2012/02/13/unified-ad-for-windows-phone-part-3-remote-ad-provider-configuration/"&gt;implemented the Remote Ad Provider configuration in Part 3&lt;/a&gt;. What’s next?&lt;/p&gt;  &lt;h3&gt;The Generic Ad Provider for Xaml&lt;/h3&gt;  &lt;p&gt;Think of the Generic Ad Provider as a very simple AdProvider. It can show Xaml and that’s basically it. You could use this Ad Provider for example to market your own applications within your own applications. So a piece of Xaml with a little bit of text and an HyperlinkButton that links to a Uri. And after a minute the Ad Provider will rotate to the next Ad Provider. The Xaml can be much more complex, we will come up to that in a moment. But first see a small example Ad in Xaml.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:e33d321b-0e0b-46e3-97db-68bd7912a330" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;Grid xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
      Width=&amp;quot;480&amp;quot;
      Height=&amp;quot;80&amp;quot;
      Background=&amp;quot;{StaticResource PhoneBackgroundBrush}&amp;quot;&amp;gt;
    &amp;lt;Border BorderBrush=&amp;quot;{StaticResource PhoneAccentBrush}&amp;quot;
            BorderThickness=&amp;quot;1&amp;quot;&amp;gt;
        &amp;lt;Grid&amp;gt;
            &amp;lt;TextBlock Text=&amp;quot;WP Unified Ad&amp;quot;
                       Foreground=&amp;quot;{StaticResource PhoneAccentBrush}&amp;quot; Margin=&amp;quot;0&amp;quot;
                       VerticalAlignment=&amp;quot;Center&amp;quot; HorizontalAlignment=&amp;quot;Center&amp;quot; FontSize=&amp;quot;35&amp;quot;/&amp;gt;
            &amp;lt;HyperlinkButton NavigateUri=&amp;quot;http://wpunifiedad.codeplex.com&amp;quot;
                             HorizontalAlignment=&amp;quot;Stretch&amp;quot;
                             VerticalAlignment=&amp;quot;Stretch&amp;quot;&amp;gt;
            &amp;lt;/HyperlinkButton&amp;gt;
        &amp;lt;/Grid&amp;gt;
    &amp;lt;/Border&amp;gt;
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3&gt;Where do we put the Xaml?&lt;/h3&gt;

&lt;p&gt;Ideal it would be on a remote server. But if you don’t have the remote server or you want to have a fallback ad in case the remote server isn’t available you can use the &lt;strong&gt;OfflineContent&lt;/strong&gt; property of the &lt;strong&gt;GenericAdProvider&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;If you do have the remote server you can set the &lt;strong&gt;XamlUri&lt;/strong&gt; property to the remote Url. In case you want to some more intelligent stuff, like a special ad for each country, or making sure you do something special for the current application, you can make use of the format parameters. The first {0} argument will be replaced by the ApplicationID and the second {1} argument will be replace by the CountryCode. So let’s say I have a server app that returns ads for me, my XamlUri could be configured like this:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:d7272825-2ef6-4282-9dec-95562b1d0730" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:text; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;http://someurlontheinternet.com/ProvideAd?Country={1}&amp;amp;AppId={0}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;If you don’t need one or both arguments you could omit them off course.&lt;/p&gt;

&lt;h3&gt;Using Phone Styles&lt;/h3&gt;

&lt;p&gt;If you want to make sure that the advertisements have the same color palette as the Phone settings you can even make use of the usual Phone Resources. Like this example where the Background is set to the PhoneBackgroundBrush and the Border and Text to the PhoneAccentBrush.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:9a7166e4-a494-4228-9397-cf35925e9031" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;Grid Width=&amp;quot;480&amp;quot;
        Height=&amp;quot;80&amp;quot;
        Background=&amp;quot;{StaticResource PhoneBackgroundBrush}&amp;quot;&amp;gt;
    &amp;lt;Border BorderBrush=&amp;quot;{StaticResource PhoneAccentBrush}&amp;quot;
            BorderThickness=&amp;quot;1&amp;quot;&amp;gt;
        &amp;lt;Grid&amp;gt;
            &amp;lt;TextBlock Text=&amp;quot;WP Unified Ad&amp;quot;
                        Foreground=&amp;quot;{StaticResource PhoneAccentBrush}&amp;quot;
                        Margin=&amp;quot;0&amp;quot;
                        VerticalAlignment=&amp;quot;Center&amp;quot;
                        HorizontalAlignment=&amp;quot;Center&amp;quot;
                        FontSize=&amp;quot;35&amp;quot; /&amp;gt;
        &amp;lt;/Grid&amp;gt;
    &amp;lt;/Border&amp;gt;
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3&gt;How to add links&lt;/h3&gt;

&lt;p&gt;The easiest way to add a link is to put a HyperlinkButton on top of the full Xaml. You don’t have to give it a visual appearance as long as you make it stretch to the full Ad space. Put the Uri you want to link to in the NavigateUri. What? Yes put the Uri in the NavigateUri. But won’t that only work for navigation inside the application, from page to page? Yes but this is improved navigation.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;“&lt;a href="http://anythingontheweb.com"&gt;http://anythingontheweb.com&lt;/a&gt;” and “&lt;a href="https://anythingontheweb.com"&gt;https://anythingontheweb.com&lt;/a&gt;” will start the WebBrowserTask &lt;/li&gt;

  &lt;li&gt;“marketplace://search/some content” will start the MarketplaceSearchTask with “some content” as query. &lt;/li&gt;

  &lt;li&gt;“marketplace://review” will start the MarketplaceReviewTask for the current application. &lt;/li&gt;

  &lt;li&gt;“marketplace://detail” will start the MarketplaceDetailTask for the current application. &lt;/li&gt;

  &lt;li&gt;“marketplace://detail/5f171b43-6ea8-e011-a53c-78e7d1fa76f8” will start the MarketplaceDetailTask for the application with the mentioned ID. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This will enable you to create simple ads that show a webpage. But if you want more, like for example market your other apps you can do this as well.&lt;/p&gt;

&lt;h3&gt;Complex Ads&lt;/h3&gt;

&lt;p&gt;I’m not the best designer, but I know a little about Xaml. So I was interested to see if I could get a more complex Ad working. The below Ad for example has a Storyboard attached that changes the opacity of two elements. Sounds easy, it is easy. Just think about what more nice things you can do instead.&lt;/p&gt;



&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:d5982d3e-c222-4156-aa9d-90cea3f3e9a7" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;Grid xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
      xmlns:x=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml&amp;quot;
      Width=&amp;quot;480&amp;quot;
      Height=&amp;quot;80&amp;quot;
      Background=&amp;quot;{StaticResource PhoneBackgroundBrush}&amp;quot;&amp;gt;
	&amp;lt;Grid.Resources&amp;gt;
		&amp;lt;Storyboard x:Name=&amp;quot;Storyboard&amp;quot; AutoReverse=&amp;quot;True&amp;quot; RepeatBehavior=&amp;quot;Forever&amp;quot;&amp;gt;
			&amp;lt;DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=&amp;quot;(UIElement.Opacity)&amp;quot; Storyboard.TargetName=&amp;quot;One&amp;quot;&amp;gt;
				&amp;lt;EasingDoubleKeyFrame KeyTime=&amp;quot;0&amp;quot; Value=&amp;quot;1&amp;quot;/&amp;gt;
				&amp;lt;EasingDoubleKeyFrame KeyTime=&amp;quot;0:0:2&amp;quot; Value=&amp;quot;1&amp;quot;/&amp;gt;
				&amp;lt;EasingDoubleKeyFrame KeyTime=&amp;quot;0:0:3&amp;quot; Value=&amp;quot;0&amp;quot;/&amp;gt;
				&amp;lt;EasingDoubleKeyFrame KeyTime=&amp;quot;0:0:5&amp;quot; Value=&amp;quot;0&amp;quot;/&amp;gt;
			&amp;lt;/DoubleAnimationUsingKeyFrames&amp;gt;
			&amp;lt;DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=&amp;quot;(UIElement.Opacity)&amp;quot; Storyboard.TargetName=&amp;quot;Two&amp;quot;&amp;gt;
				&amp;lt;EasingDoubleKeyFrame KeyTime=&amp;quot;0&amp;quot; Value=&amp;quot;0&amp;quot;/&amp;gt;
				&amp;lt;EasingDoubleKeyFrame KeyTime=&amp;quot;0:0:2&amp;quot; Value=&amp;quot;0&amp;quot;/&amp;gt;
				&amp;lt;EasingDoubleKeyFrame KeyTime=&amp;quot;0:0:3&amp;quot; Value=&amp;quot;1&amp;quot;/&amp;gt;
				&amp;lt;EasingDoubleKeyFrame KeyTime=&amp;quot;0:0:5&amp;quot; Value=&amp;quot;1&amp;quot;/&amp;gt;
			&amp;lt;/DoubleAnimationUsingKeyFrames&amp;gt;
		&amp;lt;/Storyboard&amp;gt;
	&amp;lt;/Grid.Resources&amp;gt;
    &amp;lt;Border BorderBrush=&amp;quot;{StaticResource PhoneAccentBrush}&amp;quot;
            BorderThickness=&amp;quot;1&amp;quot;&amp;gt;
        &amp;lt;Grid&amp;gt;
            &amp;lt;Grid x:Name=&amp;quot;One&amp;quot;&amp;gt;
        		&amp;lt;TextBlock Text=&amp;quot;WP Unified Ad&amp;quot;
        			Foreground=&amp;quot;{StaticResource PhoneAccentBrush}&amp;quot; Margin=&amp;quot;0&amp;quot;
        			VerticalAlignment=&amp;quot;Center&amp;quot; HorizontalAlignment=&amp;quot;Center&amp;quot; FontSize=&amp;quot;35&amp;quot;/&amp;gt;
        	&amp;lt;/Grid&amp;gt;
            &amp;lt;Grid x:Name=&amp;quot;Two&amp;quot; Opacity=&amp;quot;0&amp;quot;&amp;gt;
            	&amp;lt;TextBlock Text=&amp;quot;by Mark Monster&amp;quot;
            		Foreground=&amp;quot;{StaticResource PhoneAccentBrush}&amp;quot; Margin=&amp;quot;0&amp;quot;
            		VerticalAlignment=&amp;quot;Center&amp;quot; HorizontalAlignment=&amp;quot;Center&amp;quot; FontSize=&amp;quot;35&amp;quot;/&amp;gt;
            &amp;lt;/Grid&amp;gt;
            &amp;lt;HyperlinkButton NavigateUri=&amp;quot;http://wpunifiedad.codeplex.com&amp;quot;
                             HorizontalAlignment=&amp;quot;Stretch&amp;quot;
                             VerticalAlignment=&amp;quot;Stretch&amp;quot;/&amp;gt;
        &amp;lt;/Grid&amp;gt;
    &amp;lt;/Border&amp;gt;
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/Yyecr3BEoW4" height="1" width="1"/&gt;</description><pubDate>Tue, 14 Feb 2012 21:31:29 +0100</pubDate><a10:updated>2012-02-14T21:31:29+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2012/02/14/unified-ad-for-windows-phone-part-4-genericadproviderforxaml</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/VpyU4YxC_JE/unified-ad-for-windows-phone-part-3-remote-ad-provider-configuration</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>advertisement</category><category>Open Source</category><category>Phone</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>WPDev</category><category>WPUnifiedAd</category><title>Unified Ad for Windows Phone - Part 3 - Remote Ad Provider configuration</title><description>&lt;p&gt;Did you read the previous parts?&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mark.mymonster.nl/2012/02/07/windows-phone-unified-ad-part-1-introduction/"&gt;Part 1 – Introduction&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mark.mymonster.nl/2012/02/08/unified-ad-for-windows-phone-part-2-basic-usage/"&gt;Part 2 – Basic Usage&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Done? Let’s continue with Part 3, configure the Ad Providers from a remote location.&lt;/p&gt;  &lt;h3&gt;Step 1, Add the RemoteAdProviderStrategy&lt;/h3&gt;  &lt;p&gt;Okay, let’s forget about the default AdProviderStrategy. The default just rotates between the different AdProviders, we want more. First we set the &lt;strong&gt;AdProviderStrategy&lt;/strong&gt; property of the &lt;strong&gt;AdControl&lt;/strong&gt;. Just like this.&lt;/p&gt;    &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:7bdaaf49-d439-4153-b065-ec01eef42fa2" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;Ads:AdControl.AdProviderStrategy&amp;gt;
    &amp;lt;Strategy:RemoteAdProviderStrategy xmlns:Strategy=&amp;quot;clr-namespace:MC.Phone.Ads.Strategy;assembly=MC.Phone.Ads&amp;quot; /&amp;gt;
&amp;lt;/Ads:AdControl.AdProviderStrategy&amp;gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;Step 2, Create a configuration file&lt;/h3&gt;

&lt;p&gt;It could very well be that you already have a functional configuration file. When you for example made use of &lt;a href="http://wp7adrotator.codeplex.com/"&gt;Windows Phone 7 Ad Rotator&lt;/a&gt; you already have a configuration file that’s fully compatible with the Unfied Ad. But if you want the full power of the Unified Ad you have to use a different configuration file structure. Xml files explain best by showing an example file.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:e4921950-dd69-4bb0-b9c0-049b33ab4325" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;
&amp;lt;AdSettings&amp;gt;
  &amp;lt;CountryDescriptors&amp;gt;
    &amp;lt;AdCountryDescriptor Country=&amp;quot;US, GB&amp;quot;&amp;gt;
      &amp;lt;Probability Value=&amp;quot;70&amp;quot; AdProvider=&amp;quot;None&amp;quot; /&amp;gt;
      &amp;lt;Probability Value=&amp;quot;10&amp;quot; AdProvider=&amp;quot;AdMob&amp;quot; /&amp;gt;
      &amp;lt;Probability Value=&amp;quot;10&amp;quot; AdProvider=&amp;quot;MobFox&amp;quot; /&amp;gt;
      &amp;lt;Probability Value=&amp;quot;10&amp;quot; AdProvider=&amp;quot;AdDuplex&amp;quot; /&amp;gt;
    &amp;lt;/AdCountryDescriptor&amp;gt;
    &amp;lt;AdCountryDescriptor Country=&amp;quot;DE&amp;quot;&amp;gt;
      &amp;lt;Probability Value=&amp;quot;15&amp;quot; AdProvider=&amp;quot;PubCenter&amp;quot; /&amp;gt;
      &amp;lt;Probability Value=&amp;quot;15&amp;quot; AdProvider=&amp;quot;AdMob&amp;quot; /&amp;gt;
      &amp;lt;Probability Value=&amp;quot;20&amp;quot; AdProvider=&amp;quot;AdDuplex&amp;quot; /&amp;gt;
      &amp;lt;Probability Value=&amp;quot;50&amp;quot; AdProvider=&amp;quot;None&amp;quot; /&amp;gt;
    &amp;lt;/AdCountryDescriptor&amp;gt;
    &amp;lt;AdCountryDescriptor&amp;gt;
      &amp;lt;Probability Value=&amp;quot;20&amp;quot; AdProvider=&amp;quot;PubCenter&amp;quot; /&amp;gt;
      &amp;lt;Probability Value=&amp;quot;20&amp;quot; AdProvider=&amp;quot;AdMob&amp;quot; /&amp;gt;
      &amp;lt;Probability Value=&amp;quot;20&amp;quot; AdProvider=&amp;quot;AdDuplex&amp;quot; /&amp;gt;
      &amp;lt;Probability Value=&amp;quot;20&amp;quot; AdProvider=&amp;quot;Smaato&amp;quot; /&amp;gt;
      &amp;lt;Probability Value=&amp;quot;20&amp;quot; AdProvider=&amp;quot;MobFox&amp;quot; /&amp;gt;
    &amp;lt;/AdCountryDescriptor&amp;gt;
  &amp;lt;/CountryDescriptors&amp;gt;
&amp;lt;/AdSettings&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Let examine the last &lt;strong&gt;AdCountryDescriptor&lt;/strong&gt; element lines 16-22. Because this AdCountryDescriptor element doesn’t have a Country property this will be the default configuration to fall back to when there isn’t any other that matches the country of the user.&lt;/p&gt;

&lt;p&gt;Inside the AdCountryDescriptor elements there are Probabilty elements, they consist of two values: a probability and an AdProvider name. You can best compare the Probabilty with the chance in percentage that the specific Ad Provider is chosen during AdRotation. If you don’t want an AdProvider to be shown during rotation you either put the probability to 0, but better just remove the element. The AdProvider property is the name of the AdProvider that has to be filled in. Currently that would be one of these AdProviders: &lt;strong&gt;AdMob, MobFox, AdDuplex, PubCenter, Smaato, InnerActive, None &lt;/strong&gt;and&lt;strong&gt; GenericAdProviderForXaml&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;If you want no ads to be displayed for a certain percentage of the time you should use the None AdProvider. In a future post we will discuss the GenericAdProviderForXaml, for now just see it as a remote location where you put some Xaml that will be displayed as an Ad.&lt;/p&gt;

&lt;p&gt;So we now have a default configuration, what about specific country configurations? Yes important of course, by specifying the Country attribute of the AdCountryDescriptor element you can specify to which countries a specific configuration belongs. Which could be one country, or multiple countries. Each country is only allowed once in the configuration but you can specify multiple countries for one configuration by separating the country-codes by a “,”. For the country-codes make sure you use &lt;a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2"&gt;the two-letter codes from the ISO_3166-1&lt;/a&gt;, so for the UK this is GB.&lt;/p&gt;

&lt;h3&gt;Step 3, Where to put this configuration file?&lt;/h3&gt;

&lt;p&gt;Put it somewhere on a webserver where it’s accessible through http or https. Though if you don’t want to configure it remotely but ship this Xml file as part of your application that’s fine as well. But be aware that the only way to change your shipped configuration file is by shipping a new version of your application. But to have local configuration file makes sense even if you have a remote configuration file. When for example your remote config file cannot be accessed (could be any reason) the RemoteAdProviderStrategy will fallback to the local configuration file. So let’s configure the strategy accordingly.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:d500abcd-9a74-4bba-82bd-b3fbdda1a423" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; highlight: [3,4]"&gt;&amp;lt;Ads:AdControl.AdProviderStrategy&amp;gt;
    &amp;lt;Strategy:RemoteAdProviderStrategy xmlns:Strategy=&amp;quot;clr-namespace:MC.Phone.Ads.Strategy;assembly=MC.Phone.Ads&amp;quot;
                                        LocalProviderSettingsUri=&amp;quot;Ads/AdSettings.xml&amp;quot;
                                        RemoteProviderSettingsUri=&amp;quot;http://someurlinthewild.com/ads.xml&amp;quot; /&amp;gt;
&amp;lt;/Ads:AdControl.AdProviderStrategy&amp;gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The &lt;strong&gt;RemoteProviderSettingsUri&lt;/strong&gt; needs to be filled with the remote location url. So put the file somewhere on an internet website, your own is probably the best so that you can easily change it when you want to. The local provider settings can be used as alternative to the remote location in case you don’t want to remotely configure your ads but it could also be used as fallback when the remote url is not available for some reason. For the LocalProviderSettingsUri you need to be aware that it’s &lt;a href="http://msdn.microsoft.com/en-us/library/ms596994(v=vs.95).aspx"&gt;an ResourceUri&lt;/a&gt;, not an internet Uri. This means that if your xml file has a &lt;strong&gt;BuildAction “Content”&lt;/strong&gt; you can put a simple relative Uri in there, like in the above example. If you would add the Xml file with BuildAction “Resource” you would have to use an Uri like this “/MC.Phone.Ads.Example;component/Ads/AdSettings.xml”.&lt;/p&gt;

&lt;p&gt;Hope this explains the Remote Ad Provider configuration a little bit. Please post any questions.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/VpyU4YxC_JE" height="1" width="1"/&gt;</description><pubDate>Mon, 13 Feb 2012 20:52:07 +0100</pubDate><a10:updated>2012-02-13T20:52:07+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2012/02/13/unified-ad-for-windows-phone-part-3-remote-ad-provider-configuration</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/imxaU8A-YIM/unified-ad-for-windows-phone-part-2-basic-usage</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>advertisement</category><category>Open Source</category><category>Phone</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>WPDev</category><category>WPUnifiedAd</category><title>Unified Ad for Windows Phone - Part 2 - Basic Usage</title><description>&lt;p&gt;Time for Part 2 of the &lt;a href="http://wpunifiedad.codeplex.com/"&gt;Unified Ad for Windows Phone&lt;/a&gt; series. Also read &lt;a href="http://mark.mymonster.nl/2012/02/07/windows-phone-unified-ad-part-1-introduction"&gt;part 1 for the introduction of the Unified Ad for Windows Phone&lt;/a&gt;. We covered the reason why we want the &lt;a href="http://wpunifiedad.codeplex.com" target="_blank"&gt;Unified ad for Windows Phone control&lt;/a&gt; and also registered for a couple of Ad Providers. Let’s start with implementing the Unified ad control in our application.&lt;/p&gt;  &lt;h3&gt;Install the NuGet Package for Unified Ad for Windows Phone&lt;/h3&gt;  &lt;p&gt;Start managing your NuGet Packages for your Windows Phone project. Search for “wpunifiedad” and click install.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2012/02/image-2.png"&gt;&lt;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="Manage NuGet Packages, search for wpunifiedad" border="0" alt="Manage NuGet Packages, search for wpunifiedad" src="http://mark.mymonster.nl/Uploads/2012/02/image-thumb.png" width="244" height="151" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Go to one of your pages, for example “MainPage.xaml” and add the following Xaml in for example the ContentPanel Grid.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:24e1cf0a-96be-4323-b96b-57e48dfd8bfb" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: true; collapse: false; "&gt;&amp;lt;Ads:AdControl x:Name=&amp;quot;AdBasic&amp;quot;
                FallbackAdProviderName=&amp;quot;AdDuplex&amp;quot;
                IsTest=&amp;quot;True&amp;quot;
                xmlns:Ads=&amp;quot;clr-namespace:MC.Phone.Ads;assembly=MC.Phone.Ads&amp;quot;
                xmlns:PubCenter=&amp;quot;clr-namespace:MC.Phone.Ads.PubCenter;assembly=MC.Phone.Ads.PubCenter&amp;quot;
                xmlns:Smaato=&amp;quot;clr-namespace:MC.Phone.Ads.Smaato;assembly=MC.Phone.Ads.Smaato&amp;quot;
                xmlns:MobFox=&amp;quot;clr-namespace:MC.Phone.Ads.MobFox;assembly=MC.Phone.Ads.MobFox&amp;quot;
                xmlns:AdMob=&amp;quot;clr-namespace:MC.Phone.Ads.AdMob;assembly=MC.Phone.Ads.AdMob&amp;quot;
                xmlns:Provider=&amp;quot;clr-namespace:MC.Phone.Ads.Provider;assembly=MC.Phone.Ads&amp;quot;
                xmlns:AdDuplex=&amp;quot;clr-namespace:MC.Phone.Ads.AdDuplex;assembly=MC.Phone.Ads.AdDuplex&amp;quot;&amp;gt;
    &amp;lt;Ads:AdControl.AdProviders&amp;gt;
        &amp;lt;Provider:GenericAdProviderForXaml XamlUri=&amp;quot;http://remoteurlontheinternet.com/Ad.xaml?appid={0}&amp;quot; /&amp;gt;
        &amp;lt;Provider:NoneAdProvider /&amp;gt;
        &amp;lt;AdDuplex:AdDuplexAdProvider App=&amp;quot;&amp;quot; /&amp;gt;
        &amp;lt;AdMob:AdMobAdProvider AdUnit=&amp;quot;&amp;quot; /&amp;gt;
        &amp;lt;MobFox:MobFoxAdProvider Publisher=&amp;quot;test&amp;quot; /&amp;gt;
        &amp;lt;Smaato:SmaatoAdProvider AdSpace=&amp;quot;0&amp;quot;
                                    Publisher=&amp;quot;0&amp;quot; /&amp;gt;
        &amp;lt;PubCenter:PubCenterAdProvider Application=&amp;quot;&amp;quot;
                                        AdUnit=&amp;quot;&amp;quot; /&amp;gt;
        &amp;lt;!--InnerActive is not really suitable for the Ad Rotation because it doesn't have any events to react on.--&amp;gt;
        &amp;lt;!--&amp;lt;InnerActive:InnerActiveAdProvider App=&amp;quot;&amp;quot; /&amp;gt;--&amp;gt;
    &amp;lt;/Ads:AdControl.AdProviders&amp;gt;
&amp;lt;/Ads:AdControl&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Lines 12 to 22 are the AdProviders that are available for the Unified ad control. Just remove the elements for the AdProviders that you’re not using or planning to use. For now also remove the GenericAdProviderForXaml element. This ad provider will be discussed separately in a next part. Also take a look at line 3, it is now configured to be run in Test mode. Now let’s start configuring the different ad providers.&lt;/p&gt;

&lt;h3&gt;AdDuplex configuration&lt;/h3&gt;

&lt;p&gt;After you added a new application to AdDuplex you will see the &lt;strong&gt;App ID&lt;/strong&gt;. Copy this value to the &lt;strong&gt;App&lt;/strong&gt; property of the &lt;strong&gt;AdDuplexAdProvider&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2012/02/image-6.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://mark.mymonster.nl/Uploads/2012/02/image-thumb-2.png" width="244" height="93" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;AdMob configuration&lt;/h3&gt;

&lt;p&gt;When you completed the configuration of a new site/app in AdMob you will see a so called &lt;strong&gt;Publisher ID&lt;/strong&gt;. Copy this value to the &lt;strong&gt;AdUnit&lt;/strong&gt; property of the &lt;strong&gt;AdMobAdProvider&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2012/02/image-8.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://mark.mymonster.nl/Uploads/2012/02/image-thumb-3.png" width="244" height="42" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;MobFox configuration&lt;/h3&gt;

&lt;p&gt;For MobFox you should copy the &lt;strong&gt;Publisher ID&lt;/strong&gt; from the app to the &lt;strong&gt;Publisher&lt;/strong&gt; property of the &lt;strong&gt;MobFoxAdProvider&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2012/02/image-10.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://mark.mymonster.nl/Uploads/2012/02/image-thumb-4.png" width="244" height="65" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;Smaato configuration&lt;/h3&gt;

&lt;p&gt;For Smaato you should fill in both the &lt;strong&gt;AdSpace&lt;/strong&gt; and the &lt;strong&gt;Publisher&lt;/strong&gt; number in the &lt;strong&gt;SmaatoAdProvider&lt;/strong&gt;. Copy the &lt;strong&gt;AdSpaceId&lt;/strong&gt; from the application list for your application to the &lt;strong&gt;AdSpace&lt;/strong&gt; property for the &lt;strong&gt;SmaatoAdProvider&lt;/strong&gt;. Copy the &lt;strong&gt;PubisherId&lt;/strong&gt; below at that screen to the &lt;strong&gt;Publisher&lt;/strong&gt; property for the &lt;strong&gt;SmaatoAdProvider&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2012/02/image-16.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 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://mark.mymonster.nl/Uploads/2012/02/image-thumb-1.png" width="244" height="83" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;PubCenter configuration&lt;/h3&gt;

&lt;p&gt;The PubCenter configuration consist of two parts. An Application, where you need to copy the &lt;strong&gt;Application ID&lt;/strong&gt; to the &lt;strong&gt;Application&lt;/strong&gt; property of the &lt;strong&gt;PubCenterAdProvider&lt;/strong&gt;. And an Ad Unit where you need to copy the &lt;strong&gt;ID&lt;/strong&gt; of the Ad Unit to the &lt;strong&gt;AdUnit&lt;/strong&gt; property of the &lt;strong&gt;PubCenterAdProvider&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2012/02/image-14.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://mark.mymonster.nl/Uploads/2012/02/image-thumb-6.png" width="244" height="101" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;InnerActive configuration&lt;/h3&gt;

&lt;p&gt;InnerActive can be configured, but I cannot recommend using it in combination of the Unified Ad control. Inner Active doesn’t have any events that can be listened to like: NoAd, NewAd or AdEngaged. And because of this it’s impposible to let it rotate with the other Ad Providers. When you want to configure it though, you can. Copy the &lt;strong&gt;App Name&lt;/strong&gt; and put it in the &lt;strong&gt;App&lt;/strong&gt; property of the &lt;strong&gt;InnerActiveAdProvider&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2012/02/image-12.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://mark.mymonster.nl/Uploads/2012/02/image-thumb-5.png" width="244" height="45" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;Test or not?&lt;/h3&gt;

&lt;p&gt;You can put your AdControl in production mode by setting the &lt;strong&gt;IsTest&lt;/strong&gt; property to &lt;strong&gt;False&lt;/strong&gt; or completely removing the property from the Xaml.&lt;/p&gt;

&lt;p&gt;The next part will be about the Remote Ad Provider configuration.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/imxaU8A-YIM" height="1" width="1"/&gt;</description><pubDate>Wed, 08 Feb 2012 21:46:37 +0100</pubDate><a10:updated>2012-02-10T16:05:57+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2012/02/08/unified-ad-for-windows-phone-part-2-basic-usage</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/iS9Mz8hPq0Q/windows-phone-unified-ad-part-1-introduction</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>advertisement</category><category>Open Source</category><category>Phone</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>WPDev</category><category>WPUnifiedAd</category><title>Unified Ad for Windows Phone - Part 1 - Introduction</title><description>&lt;p&gt;About a month ago I started a new investigation about which Ad Provider I should use. Things I wanted.&lt;/p&gt;  &lt;p&gt;- Best eCPM&lt;/p&gt;  &lt;p&gt;- Best Fill Rate&lt;/p&gt;  &lt;p&gt;- Easy to use&lt;/p&gt;  &lt;p&gt;Some of the things that are causing problems is the Ad Availability per Country. Depending on where your app is used more or less localized ads are used. So we know that the Microsoft PubCenter has a high &lt;a href="http://adsense.blogspot.com/2006/02/ecpm-what-exactly-is-that.html" target="_blank"&gt;eCPM&lt;/a&gt; for the US, it is low for The Netherlands. There are more of those problems with other Ad Providers. I heard there was a solution for this problem. Use the &lt;a href="http://wp7adrotator.codeplex.com/" target="_blank"&gt;Ad Rotator for Windows Phone 7&lt;/a&gt; which can be found on Codeplex. I did give it a try but at that moment AdMob was not supported (mostly because there were some AdMob specific problems) and also MobFox and Smaato weren’t supported. Those were the specific Ad Providers I was interested in.&lt;/p&gt;  &lt;p&gt;My initial though would be, let’s try to modify the source a little bit, to get support for MobFox and Smaato in. But after looking into the source I was warned, almost all the code was in the Code Behind for the AdControl. While I am not against the usage of the Code Behind, I’m pro extensibility. The code I saw was far from maintainable and extensibility is done by adding more code. So when more AdProviders will be added code will be less and less maintainable.&lt;/p&gt;  &lt;h3&gt;Unification&lt;/h3&gt;  &lt;p&gt;When I look at the differences between the AdControls, they more or less do the same, but in a different way. All of them have a TestMode, but enabling the testmode is different for each AdControl. Same for the events they have. I want to have a unified ad control that does handle these ‘Complexities’ for me and the rest of the world. There isn’t such a control yet, so why not use the good parts of wp7adrotator (the remote configuration, multiple adproviders) and create something that suits my needs better. So I did.&lt;/p&gt;  &lt;p&gt;The &lt;a href="http://wpunifiedad.codeplex.com" target="_blank"&gt;Windows Phone Unified Ad control&lt;/a&gt; is universal in the following ways.&lt;/p&gt;  &lt;p&gt;Properties:&lt;/p&gt;  &lt;p&gt;&lt;em&gt;- Country – Will be passed to all the AdProviders that support Country or Location as input&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;- IsTest – Will be pass to all the AdProviders that support a way of TestMode. Some have a simple boolean field, others require to set the PublisherId to be set to a specific value.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;Events:&lt;/p&gt;  &lt;p&gt;&lt;em&gt;- NewAd – When a new ad is available this event will be fired, even though the different AdProviders have different events to notify the user, like: NewAdAvailable, AdLoaded, ControlAdRefreshed.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;- NoAd – When no ad is availabe this event will be fired, even though the different AdProviders have different events to notify the user, like: AdFailed, ControlErrorOccurred, AdError.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;- AdEngaged – When an ad is engaged or clicked this event will be fired, even though the different AdProviders have different events to notify the user, like: AdClick, ControlAdEngaged, ControlIsAdEngagedChanged, AdLeavingApplication.&amp;#160; &lt;/em&gt;&lt;/p&gt;  &lt;h3&gt;Best Fill Rate&lt;/h3&gt;  &lt;p&gt;To get the best fill rate the Windows Phone Unified Ad control supports ad provider rotation. As soon as an Ad Provider is not providing an ad the next Provider will be asked to provide an ad. This will enable you to get a higher fill rate compared to using just one ad provider. You can even roll in your own custom ad based on Xaml.&lt;/p&gt;  &lt;h3&gt;Best eCPM&lt;/h3&gt;  &lt;p&gt;Every single Ad Provider changes it’s &lt;a href="http://adsense.blogspot.com/2006/02/ecpm-what-exactly-is-that.html" target="_blank"&gt;eCPM&lt;/a&gt; from time to time. But they even have different &lt;a href="http://adsense.blogspot.com/2006/02/ecpm-what-exactly-is-that.html" target="_blank"&gt;eCPMs&lt;/a&gt; per country. Same as they might have, or might not have ads for a particular country at all. To get the best of both worlds &lt;a href="http://wpunifiedad.codeplex.com/"&gt;Windows Phone Unified Ad control&lt;/a&gt; supports AdProviders per Country. Similar to the wp7adrotator, but instead the Country is used and not so much the full culture. If you already have configuration files for wp7adrotator you can use those as well, they are supported in the &lt;a href="http://wpunifiedad.codeplex.com" target="_blank"&gt;Windows Phone Unified Ad control&lt;/a&gt; as well.&lt;/p&gt;  &lt;h3&gt;Supported AdProviders&lt;/h3&gt;  &lt;p&gt;All Ad Providers that currently have an Ad Control for Windows Phone 7 are supported. Register with the ones you like best. Inner-Active support is experimental because they have no way to find out there’s an ad displayed or not, yet.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://pubcenter.microsoft.com/"&gt;&lt;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="Microsoft PubCenter" border="0" alt="Microsoft PubCenter" src="http://mark.mymonster.nl/Uploads/2012/02/image-3.png" width="180" height="56" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.admob.com/"&gt;&lt;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="AdMob" border="0" alt="AdMob" src="http://mark.mymonster.nl/Uploads/2012/02/image-6.png" width="180" height="62" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.smaato.com/"&gt;&lt;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="Smaato" border="0" alt="Smaato" src="http://mark.mymonster.nl/Uploads/2012/02/image-9.png" width="180" height="42" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.mobfox.com/"&gt;&lt;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="MobFox" border="0" alt="MobFox" src="http://mark.mymonster.nl/Uploads/2012/02/image-18.png" width="180" height="49" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.adduplex.com/"&gt;&lt;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="AdDuplex" border="0" alt="AdDuplex" src="http://mark.mymonster.nl/Uploads/2012/02/image-17.png" width="180" height="45" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.inner-active.com/"&gt;&lt;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="Inner-Active" border="0" alt="Inner-Active" src="http://mark.mymonster.nl/Uploads/2012/02/image-16.png" width="180" height="41" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;There are two special Ad Provider implementations.&lt;/p&gt;  &lt;p&gt;- None – This ad provider is used to not show an ad at all. Can be very handy during testing phase, when testing the application and not the advertisements. But could also be used to show no ads for a certain percentage of the app usage.&lt;/p&gt;  &lt;p&gt;- GenericAdProviderForXaml – This ad provider is used to show some custom Xaml that’s loaded from a remote url. Can be very handy to market your own applications within your own applications.&lt;/p&gt;  &lt;h3&gt;What’s next?&lt;/h3&gt;  &lt;p&gt;&lt;a href="http://mark.mymonster.nl/2012/02/08/unified-ad-for-windows-phone-part-2-basic-usage"&gt;Next part will be about the basic usage of the Windows Phone Unified Ad Control.&lt;/a&gt; If you can’t wait? You can find &lt;a href="http://wpunifiedad.codeplex.com/SourceControl/list/changesets"&gt;the source and an example project with the Windows Phone Unified Ad control on codeplex&lt;/a&gt;. If you want to start right away you can &lt;a href="https://www.nuget.org/packages/wpunifiedad/0.1.0"&gt;add the NuGet Package called WPUnifiedAd&lt;/a&gt;. Also the &lt;a href="http://wpunifiedad.codeplex.com/"&gt;homepage contains a basic guide&lt;/a&gt; that will help as well.&lt;/p&gt;  &lt;p&gt;Part 3 will be about using the Remote Ad Provider Configuration. Future parts will come on how to make use of the GenericAdProviderForXaml&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/iS9Mz8hPq0Q" height="1" width="1"/&gt;</description><pubDate>Tue, 07 Feb 2012 21:13:42 +0100</pubDate><a10:updated>2012-02-08T21:56:53+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2012/02/07/windows-phone-unified-ad-part-1-introduction</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/sthi0fUeYSw/wow-i-actually-couldnrsquot-write-javascript-what-i-wrote-smelledhellip</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>ASP.NET MVC</category><category>JQuery</category><category>WinRT</category><category>Win8</category><category>HTML 5</category><category>JavaScript</category><title>Wow, I actually couldn&amp;rsquo;t write JavaScript, what I wrote smelled&amp;hellip;</title><description>&lt;p&gt;Alright, I’m not really a JavaScript developer, but do they even exists? I think there probably are a few JavaScript developers in this world, but most of the developers that I know of are developing for the Web. Developing for the Web in it’s widest sense. Most of the time there’s a server technology like ASP.NET, ASP.NET MVC, PHP or something else. A lot of times people actually feel like they are a WHATEVER-SERVER-TECHNOLOGY developer. I felt the same. &lt;/p&gt;  &lt;p&gt;But lately the client-side technologies become more and more important. Yes most web developers know a little bit of HTML, and if we’re lucky there’s some knowledge on CSS as well. Yeah we also write JavaScript. uh actually we write jQuery script. Yes we are lucky to have a library like jQuery, but in the end most of don’t know much about JavaScript at all. Yeah we write functions, sometimes. But that’s about it, we don’t write, maintainable, easy to read JavaScript code. Our JavaScript smells.&lt;/p&gt;  &lt;p&gt;And if we want to make use of the full HTML5 stack either for web or for example in a Windows 8 Metro application, our code needs to be maintainable. I can assure you, it’s not going to be 10 lines of JavaScript for a JavaScript Metro application.&lt;/p&gt;  &lt;h3&gt;To == or to ===?&lt;/h3&gt;  &lt;p&gt;&lt;img style="margin: 0px 5px 5px 0px; display: inline; float: left" align="left" src="http://akamaicovers.oreilly.com/images/9780596517748/cat.gif" /&gt;I know C# so I’m using the double equals to check if left and right are equal. WRONG! I really need to admit I didn’t know I was wrong until a few months ago. So chances are some of you, my readers, don’t know it either. To quote &lt;a href="http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/" target="_blank"&gt;Douglas Crockford’s book on JavaScript&lt;/a&gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So from now on I will be using triple-equals instead of double-equals. &lt;/p&gt;  &lt;p&gt;Of course there’s a lot more in The Good Parts book, I can recommend you buying it.&lt;/p&gt;  &lt;h3&gt;Object Oriented Programming uh Closures&lt;/h3&gt;  &lt;p&gt;Most of the JavaScript code I write are just functions, and functions might call other functions, some anonymous some named. The end result is either a large amount of functions, are just a couple of functions with more than 100 lines of code. &lt;/p&gt;  &lt;p&gt;Is this maintainable? Hell no!&lt;/p&gt;  &lt;p&gt;So why don’t I write code in JavaScript like I do in C#? Uh is that possible at all? I recall everybody telling me JavaScript is not an object oriented language. I still have to agree JavaScript doesn’t have all of the object oriented language characteristics to call&amp;#160; it a fully object oriented language. But still. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.w3schools.com/js/js_objects.asp" target="_blank"&gt;JavaScript objects can be created in different ways&lt;/a&gt;, but you’ll have to know a little bit more about some of the JavaScript language features to be able to get things working like you expect.&lt;/p&gt;  &lt;p&gt;Some things were completely new to me like Closures: &lt;a href="http://blog.morrisjohns.com/javascript_closures_for_dummies.html" target="_blank"&gt;JavaScript Closures for Dummies&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Take some time to get to know the above JavaScript features.&lt;/p&gt;  &lt;p&gt;With the above concepts you can learn a little bit about JavaScript patterns, which help you when you want to write your own JavaScript library.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://weblogs.asp.net/dwahlin/archive/2011/08/01/techniques-strategies-and-patterns-for-structuring-javascript-code-the-prototype-pattern.aspx" target="_blank"&gt;Prototype Pattern&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth" target="_blank"&gt;Module Pattern&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://weblogs.asp.net/dwahlin/archive/2011/08/02/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-module-pattern.aspx" target="_blank"&gt;Revealing Module Pattern&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://weblogs.asp.net/dwahlin/archive/2011/08/03/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern.aspx" target="_blank"&gt;Revealing Prototype Pattern&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Really interesting articles that can help, but if you need more, you should definitely take a look at &lt;a href="http://www.pluralsight-training.net/microsoft/Courses/TableOfContents?courseName=structuring-javascript" target="_blank"&gt;the pluralsight course for Structuring JavaScript Code&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;PS. Don’t feel hurt, there are exceptions to what I write here. Actually if there weren’t good JavaScript devs out there the rest of the world, like me, couldn’t learn from their expertise.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/sthi0fUeYSw" height="1" width="1"/&gt;</description><pubDate>Tue, 10 Jan 2012 21:47:38 +0100</pubDate><a10:updated>2012-01-10T21:47:38+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2012/01/10/wow-i-actually-couldnrsquot-write-javascript-what-i-wrote-smelledhellip</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/xZRF6QrQzH0/how-to-cancel-overwrite-a-successful-marketplace-update-submission</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>Technology</category><category>WP7</category><category>WPDev</category><title>How to cancel (overwrite) a successful Marketplace update submission?</title><description>&lt;p&gt;It was a day after I submitted an update to one of my apps to the marketplace where I found out about a bug. This was a functional bug which didn’t affect Marketplace testing. I already knew that I couldn’t cancel a running submission, so I already learned the Hard Way to never Auto Publish, but do a Manual Publish after successful testing.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Tip: Do a Manual Publish after successful testing. This makes sure you are in control!&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Alright, what happened to me recently is that I made a small code change that causes problems a Background Task for about 50% of the time. I didn’t find this during initial testing. A small case of using the less than sign instead of the greater than sign. I found out about this bug after I submitted the app to the marketplace. So I waited until the submission was successful (or failed).&lt;/p&gt;  &lt;p&gt;The Marketplace team successfully tested my application and I was in control (&lt;strong&gt;see tip&lt;/strong&gt;). What can I do?&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Publish the application:&amp;#160; I obviously don’t want this, there’s a bug in the app.&lt;/li&gt;    &lt;li&gt;Edit catalog details: Doesn’t help me either.&lt;/li&gt;    &lt;li&gt;Edit product details: That should help…&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So I went for “Edit product details”, but sadly that didn’t work, because it helped me to Step 2 and not Step 1 where I could upload a new Application Package.&lt;/p&gt;  &lt;p&gt;Alright, time for some hacking I would say. &lt;strong&gt;It might be risky, so use it at your own risk.&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;1. Start with the Edit catalog details url, copy the applicationId and the parentApplicationInstanceId.&lt;/p&gt;  &lt;p&gt;2. Replace the applicationId and the parentApplicationInstanceId in the following url.&lt;/p&gt;  &lt;p&gt;https://windowsphone.create.msdn.com/AppSubmission#/PageUpload&amp;amp;mode=Update&amp;amp;applicationId=00000000-0000-0000-0000-000000000000&amp;amp;parentApplicationInstanceId=00000000-0000-0000-0000-000000000000&lt;/p&gt;  &lt;p&gt;3. Then follow that link. &lt;strong&gt;But do nothing else.&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;4. Go back to the original page where the “Edit product details” didn’t go to step 1, but to step 2. In my situation it did suddenly go to step 1 and I was able to upload a new Application Package.&lt;/p&gt;  &lt;p&gt;I’m now waiting again for the Marketplace testing. I hope this will help some people who have a similar problem.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/xZRF6QrQzH0" height="1" width="1"/&gt;</description><pubDate>Sat, 07 Jan 2012 22:41:17 +0100</pubDate><a10:updated>2012-01-07T22:41:17+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2012/01/07/how-to-cancel-overwrite-a-successful-marketplace-update-submission</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/EMoYOW1sGbY/the-problem-of-the-windows-phone-7-applicationbar-and-not-yet-updated-bindings</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>MVVM</category><category>Phone</category><category>WP7</category><category>WPDev</category><title>The problem of the Windows Phone 7 ApplicationBar and not (yet) updated Bindings</title><description>&lt;p&gt;As a MVVM enthusiast I’m trying to use MVVM as much as possible, but not for things that are almost impossible to do with MVVM. But simple things, like a TextBox Text property is always bound to a ViewModel’s property. That’s something that works very well…until you start having ApplicationBar buttons and menu items.&lt;/p&gt;  &lt;p&gt;A lot of people already know that the ApplicationBar is something special, it’s not just a control like other stuff in your application. When clicking a button on the ApplicationBar the Binding is not yet updated. This is basically because the focus which is on the TextBox for example won’t be changed when clicking ApplicationBar buttons. This is different compared to normal buttons that you put somewhere on your page.&lt;/p&gt;  &lt;h3&gt;The Solution?&lt;/h3&gt;  &lt;p&gt;I’ve read different solutions on the web. For example, force focus on a different control by &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.control.focus(v=vs.96)" target="_blank"&gt;calling the Focus method on a Control&lt;/a&gt;. While this is working, I found a technically nicer solution. By getting the Binding of the current focused control and updating that binding.&lt;/p&gt;  &lt;p&gt;I wrote a small helper class that implements this Binding updating.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:a701cf5a-be90-40a7-8cf2-715e3c2d450d" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public static class ApplicationBarHelper
{
    public static void UpdateBindingOnFocussedControl()
    {
        object focusedElement = FocusManager.GetFocusedElement();
        if (focusedElement != null &amp;amp;&amp;amp; focusedElement is TextBox)
        {
            var binding = (focusedElement as TextBox).GetBindingExpression(TextBox.TextProperty);
            if (binding != null)
                binding.UpdateSource();
        }
    } 
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The first thing you do in the Event handlers for the ApplicationBar Click events is call.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:a77ff0f5-963a-454c-894b-715e3fc7934a" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:false; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;ApplicationBarHelper.UpdateBindingOnFocussedControl();&lt;/pre&gt;&lt;/div&gt;

&lt;h3&gt;What about the BindableApplicationBar?&lt;/h3&gt;

&lt;p&gt;A lot of use MVVM enthusiasts are using the &lt;a href="http://phone7.codeplex.com/" target="_blank"&gt;BindableApplicationBar that’s part of the Phone7.Fx library&lt;/a&gt;. Can we use this in combination with the BindableApplicationBar? Yes we can, actually the best way would be to have this integrated with the BindableApplicationBar itself. I have just downloaded the source and manipulated two methods in two classes. &lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:8bc2a395-06f2-4932-a292-6b635ce9b46e" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; highlight: [7,23]"&gt;public class BindableApplicationBarIconButton : FrameworkElement, IApplicationBarIconButton
{
    // Other code that hasn't been changed in this class.

    void ApplicationBarIconButtonClick(object sender, EventArgs e)
    {
        ApplicationBarHelper.UpdateBindingOnFocussedControl();
        if (Command != null &amp;amp;&amp;amp; CommandParameter != null)
            Command.Execute(CommandParameter);
        else if (Command != null)
            Command.Execute(CommandParameterValue);
        if (Click != null)
            Click(this, e);
    }
}

public class BindableApplicationBarMenuItem : FrameworkElement, IApplicationBarMenuItem
{
    // Other code that hasn't been changed in this class.

    private void ApplicationBarMenuItemClick(object sender, EventArgs e)
    {
        ApplicationBarHelper.UpdateBindingOnFocussedControl();
        if (Command != null &amp;amp;&amp;amp; CommandParameter != null)
            Command.Execute(CommandParameter);
        else if (Command != null)
            Command.Execute(CommandParameterValue);
        if (Click != null)
            Click(this, e);
    }
}&lt;/pre&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/EMoYOW1sGbY" height="1" width="1"/&gt;</description><pubDate>Fri, 16 Dec 2011 19:00:00 +0100</pubDate><a10:updated>2011-12-16T09:23:54+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/12/16/the-problem-of-the-windows-phone-7-applicationbar-and-not-yet-updated-bindings</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/E7yjF5lPung/what-does-featuring-in-the-marketplace-do-with-your-app</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Technology</category><category>WP7</category><category>WPDev</category><title>What does featuring in the Marketplace do with your app?</title><description>&lt;p&gt;A lot of Windows Phone developers probably already know, but some might not. There is a very interesting tool in the market to monitor your application for Downloads, Ranking and Reviews: &lt;a href="http://monitor.distimo.com/" target="_blank"&gt;Distimo Monitor&lt;/a&gt;. You can for example &lt;a href="http://peshir.blogspot.com/2011/11/command-conquer-distimo-style.html" target="_blank"&gt;compare your application with your competition and conquer the world&lt;/a&gt;. Besides that Distimo also shows you when your application was featured in the Marketplace. A couple of the apps I created have been featured so far, but let’s look at &lt;a href="http://windowsphone.com/s?appid=5f171b43-6ea8-e011-a53c-78e7d1fa76f8" target="_blank"&gt;Fokke &amp;amp; Sukke app&lt;/a&gt; and the target market (The Netherlands).&lt;/p&gt;  &lt;h3&gt;Is my app featured?&lt;/h3&gt;  &lt;p&gt;You can watch closely how the marketplace looks either on the Phone or in Zune to see if your app is featured.&lt;/p&gt;  &lt;p&gt;&lt;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://mark.mymonster.nl/Uploads/2011/12/image-3.png" width="640" height="295" /&gt;&lt;/p&gt;  &lt;p&gt;But in the end, this is not very doable. Don’t forget that your app can be featured in every market separately. So what else? We have the distimo monitor which shows events for your application. You can see when a new version was released and when your app was featured.&lt;/p&gt;  &lt;p&gt;&lt;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://mark.mymonster.nl/Uploads/2011/12/image-8.png" width="640" height="192" /&gt;&lt;/p&gt;  &lt;p&gt;The featured periods are:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;12/10 – 18/10&lt;/li&gt;    &lt;li&gt;02/11 – 08/11&lt;/li&gt;    &lt;li&gt;30/11 – 06/12&lt;/li&gt; &lt;/ul&gt;  &lt;h3&gt;My app is featured, now what?&lt;/h3&gt;    &lt;p&gt;It’s cool to see that this app has been featured that often, but what does it mean? Let’s take a look at the Ranking in those periods.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2011/12/image-7.png"&gt;&lt;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://mark.mymonster.nl/Uploads/2011/12/image-thumb-2.png" width="644" height="107" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;You can easily see the areas when the app was featured by the green regions. But more important, you can see that in the first and third period being featured meant that the ranking went up immediately.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/E7yjF5lPung" height="1" width="1"/&gt;</description><pubDate>Wed, 07 Dec 2011 19:00:00 +0100</pubDate><a10:updated>2011-12-07T06:50:48+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/12/07/what-does-featuring-in-the-marketplace-do-with-your-app</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/QQV259wobRs/how-to-give-an-element-focus-when-something-happens</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Silverlight</category><category>WP7</category><category>Used to get articles on www.dotnetmag.nl</category><category>WPDev</category><title>How to give an element focus when something happens?</title><description>&lt;p&gt;I had a very simple problem: On loading of particular screen I wanted to give a TextBox focus. It’s freaking easy to do this in the code behind. Most of my applications are actually MVVM applications and in that case it’s not something for the ViewModel, it’s logic that belongs to the view. But how about a Behavior?&lt;/p&gt;  &lt;p&gt;I want to give a specific control focus when something happens on something else. So that should be a &lt;a href="http://msdn.microsoft.com/en-us/library/ff726545(v=expression.40).aspx" target="_blank"&gt;TargetedTriggerAction&lt;/a&gt;&amp;lt;T&amp;gt;, T should be Control, because that’s something you can give focus. How easy can it be?&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:9d1c8020-e11a-4444-9650-942e52eb980c" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public class FocusOnEvent : TargetedTriggerAction&amp;lt;Control&amp;gt;
{
    protected override void Invoke(object parameter)
    {
        Target.Focus();
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Is that all? Yes it is, or actually, I want to make it even easier, add the default trigger using the &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.interactivity.defaulttriggerattribute_members(v=Expression.40).aspx" target="_blank"&gt;DefaultTriggerAttribute&lt;/a&gt;. Default should be the Loaded event, so let’s add that single line.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:3f84f836-10b6-4dee-b082-30720d5f874f" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;[DefaultTrigger(typeof(FrameworkElement), typeof(EventTrigger), &amp;quot;Loaded&amp;quot;)]
public class FocusOnEvent : TargetedTriggerAction&amp;lt;Control&amp;gt;
{
    protected override void Invoke(object parameter)
    {
        Target.Focus();
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Now we have this easy code, how do we use it? Just add a little bit of xaml to your page / control, just like any other behavior.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:96be8d68-8d21-4163-9c60-4a53c67b2d30" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;i:Interaction.Triggers&amp;gt;
    &amp;lt;i:EventTrigger&amp;gt;
        &amp;lt;Behaviors:FocusOnEvent TargetName=&amp;quot;TitleTextBox&amp;quot; /&amp;gt;
    &amp;lt;/i:EventTrigger&amp;gt;
&amp;lt;/i:Interaction.Triggers&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Some second thoughts, is it required to take the &lt;a href="http://dotnetbyexample.blogspot.com/2011/11/safe-event-detachment-base-class-for.html" target="_blank"&gt;Safe event Detachment base class for Windows Phone Behaviors by Joost van Schaik&lt;/a&gt; into consideration? No it’s not required, because we’re not manually attaching handlers to the events, that’s all done by the TargetedTriggerAction itself. Hope you guys think this little bit of code is useful.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/QQV259wobRs" height="1" width="1"/&gt;</description><pubDate>Mon, 05 Dec 2011 21:44:00 +0100</pubDate><a10:updated>2011-12-05T21:44:00+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/12/05/how-to-give-an-element-focus-when-something-happens</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/0HZhJdJ3wU0/does-windows-8-support-gif-images-and-animated-gif-images</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>Used to get articles on www.dotnetmag.nl</category><category>WPDev</category><category>WinRT</category><category>Metro</category><category>Win8</category><title>Does Windows 8 support Gif images and Animated Gif images?</title><description>&lt;p&gt;To some of us it may sound like a strange question, but developers which are used to Silverlight or Windows Phone development know why I ask this question. In both Silverlight and Windows Phone Gif images aren’t directly supported. Don’t ask me why, I don’t know why. Luckily Silverlight and Windows Phone developers are helped by an &lt;a href="http://imagetools.codeplex.com/"&gt;open source project called Image Tools which enables support for Gif and Animated Gif&lt;/a&gt;.&lt;/p&gt;  &lt;h3&gt;Windows 8 – HTML5 + JS&lt;/h3&gt;  &lt;p&gt;For a starter I just downloaded an ordinary gif-image from the internet and with no knowledge about how to add an image to a Windows 8 application I used my web-knowledge.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:35bc7a44-4f96-4d00-ba18-0095b5ea4956" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;img src=&amp;quot;/images/window.gif&amp;quot; /&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;And yes it does work. What about an animated gif? So I recall an interesting animated gif on &lt;a href="http://wildermuth.com/"&gt;Shawn Wildermuth’s blog&lt;/a&gt;, his head-shot. So without do anything else than changing the source of the image tag I created it started working. A surprise? Not really I already heard that the rendering engine for Windows 8 applications that are build in HTML5 + JS is based on IE, so this is what I did expect.&lt;/p&gt;

&lt;h3&gt;Windows 8 – XAML + C#&lt;/h3&gt;

&lt;p&gt;So I used my Silverlight knowledge to do in XAML what I did in HTML5, add an image.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:02801b17-58f1-4662-a4e5-174d7fae356d" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;Image Source=&amp;quot;/Images/window.gif&amp;quot; /&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;A really fast surprise it started working in the design view of the xaml document even before I ran the project. And also after running the application it seems to work perfectly. And the animated gif? It appears in the designer as well, but doesn’t animate in there. Also when running the application the animation doesn’t work.&lt;/p&gt;

&lt;p&gt;Just a quick thought: Silverlight doesn’t support gif at all, what about WPF? After some googling it seems that WPF does support gif images, but not really the animated gifs. But there are &lt;a href="http://stackoverflow.com/questions/210922/how-do-i-get-an-animated-gif-to-work-in-wpf"&gt;people who created solutions that should work to enable animated gifs in WPF&lt;/a&gt;. So let’s see how much of that is possible in Windows 8.&lt;/p&gt;

&lt;p&gt;The solution for WPF makes use of the &lt;a href="http://msdn.microsoft.com/en-us/library/ms653429.aspx"&gt;GifBitmapDecoder&lt;/a&gt; which isn’t there in Windows 8. But I found something that sounds similar the &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmapdecoder(v=vs.85).aspx"&gt;BitmapDecoder&lt;/a&gt;. I tried to get the a small proof-of-concept working, but failed so far. I invite you to solve this Animated Gif problem using the information I’ve given. Please share your solution with the readers of this post.&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;We all know WinRT isn’t finished, we are just looking at a developer preview. If I recall it correctly WinRT should have the same features in XAML+C# as in HTML5+JS. Will this small difference in features be tackled in the final release?&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/0HZhJdJ3wU0" height="1" width="1"/&gt;</description><pubDate>Tue, 29 Nov 2011 21:51:55 +0100</pubDate><a10:updated>2011-11-29T21:51:55+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/11/29/does-windows-8-support-gif-images-and-animated-gif-images</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/UMFq-buJyIw/statistics-for-your-windows-phone-application-google-analytics</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>IoC</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>WPDev</category><title>Statistics for your Windows Phone application (Google Analytics)</title><description>&lt;p&gt;Alright, I’ve tried a couple of different systems to get the statistics for the apps I created. &lt;/p&gt;  &lt;h3&gt;Google Analytics custom way&lt;/h3&gt;  &lt;p&gt;I started more than a year ago with a &lt;a href="http://mark.mymonster.nl/2010/06/24/capture-usage-information-of-a-windows-phone-7-application-using-google-analytics" target="_blank"&gt;unreliable option using Google Analytics&lt;/a&gt;. This option was unreliable because it didn’t handle things like no connectivity and was depending on the WebBrowser control. Technically this was an option, but there are better options.&lt;/p&gt;  &lt;p&gt;Flurry Analytics&lt;/p&gt;  &lt;p&gt;My first applications actually did go live with &lt;a href="http://www.flurry.com/" target="_blank"&gt;Flurry Analytics&lt;/a&gt; for the stats. This worked perfectly fine for some time, until I introduced a application version that only supported Mango. Strangely I never got stats for that version. In the end I heard more people complaining that the Flurry Analytics library didn’t work with Phones running on Mango. I was not happy because it took weeks before I got a response from Flurry about the problem. They asked if I was interested in doing some beta-testing. I honestly didn’t have interest in beta-testing after that long time. I hear some rumors that it’s still not working, but I’m not sure, I’ve given up Flurry Analytics.&lt;/p&gt;  &lt;h3&gt;PreEmptive Runtime Intelligence&lt;/h3&gt;  &lt;p&gt;Alright, then I heard people say, why don’t you use &lt;a href="http://www.preemptive.com/products/runtime-intelligence/overview" target="_blank"&gt;PreEmptive’s Runtime Intelligence&lt;/a&gt;. It’s free and actually an Enterprise Product. I tried it, and actually liked it. The documentation on how to use it was not top-level, but with a little bit of trying out I got things working. But even better the tool integrates an Obfuscation tool to obfuscate the code. But then it started to take longer to get the stats processed. The last time my stats were processed is at October 6th, that’s 13 days ago, way to long. I understand that it can take some time, 24 hours is pretty acceptable. But more, every user of Runtime Intelligence got an e-mail to say that the conditions are about to change in two months time. This is basically because Microsoft has changed the contract with PreEmptive, but still, the new conditions are not clear, yet. Will it be paid, will it be limited? We don’t know yet. So for me, it’s time to look for a solid Analytics solution that I know will be free and will be supported by tools in the market.&lt;/p&gt;  &lt;h3&gt;Google Analytics with Microsoft Silverlight Analytics Framework&lt;/h3&gt;  &lt;p&gt;Alright, I’ve chosen to go back to Google Analytics and follow the comments I got from my readers on my custom Google Analytics tracking post. They suggest to make use of &lt;a href="http://msaf.codeplex.com/" target="_blank"&gt;Microsoft Silverlight Analytics Framework&lt;/a&gt;. This framework supports a couple of very important scenario’s.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Offline scenarios &lt;/li&gt;    &lt;li&gt;Support for multiple analytics services, including:      &lt;ul&gt;       &lt;li&gt;Comscore &lt;/li&gt;        &lt;li&gt;Google Analytics &lt;/li&gt;        &lt;li&gt;PreEmptive Solutions &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Where I already have experience with implementing analytics using the custom PreEmptive tools I wouldn’t try that again, how long will it be free? I also have some experience with Comscore for one of my customers. I don’t understand how to read the reports so that’s not really an option for me, neither is it free. So &lt;a href="http://www.google.com/analytics/" target="_blank"&gt;Google Analytics&lt;/a&gt; it is, I know how to read the reports, and I’ve got a lot of experience implementing it for websites. Let’s start with the implementation in a Windows Phone application.&lt;/p&gt;  &lt;h3&gt;Step 1 Downloading and Referencing&lt;/h3&gt;  &lt;p&gt;You can download the source or the installation package. Be aware that the source doesn’t contain the source code for the Analytics Services like &lt;a href="http://www.google.com/analytics/" target="_blank"&gt;Google Analytics&lt;/a&gt;. So recommended will be the &lt;a href="http://msaf.codeplex.com/releases/view/56591" target="_blank"&gt;download of the installation package&lt;/a&gt;. After the installation you can find the libraries in: &lt;em&gt;C:\Program Files (x86)\Microsoft SDKs\Microsoft Silverlight Analytics Framework\&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;You’ll need to reference the following libraries when working with Google Analytics:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Microsoft.WebAnalytics.dll &lt;/li&gt;    &lt;li&gt;Microsoft.WebAnalytics.Behaviors.dll &lt;/li&gt;    &lt;li&gt;System.ComponentModel.Composition.dll &lt;/li&gt;    &lt;li&gt;System.ComponentModel.Composition.Initialization.dll &lt;/li&gt;    &lt;li&gt;System.Windows.Interactivity.dll &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; I’ve had some trouble with conflicting System.Windows.Interactivity libraries. It’s distributed with Expression Blend, MVVM Light and also with the Microsoft Silverlight Analytics Framework. I think there needs to be a solution so that the distribution should no longer be required for the different frameworks. I specially had a conflict when using Microsoft Silverlight Analytics Framework (made for Windows Phone SDK 7.0) in combination with MVVM Light 4 Preview (made for Windows Phone SDK 7.1). I did fallback to the previous version of MVVM Light 3 to remove the conflict.&lt;/p&gt;  &lt;h3&gt;Step 2 Create the IApplicationService and use reference it in App.xaml&lt;/h3&gt;  &lt;p&gt;Let’s start with gathering some generic information I want to gather from my users. To be honest I want to do this for all my applications. So this static class get's some information about the device. The &lt;a href="http://coding4fun.codeplex.com/" target="_blank"&gt;PhoneHelper class can be found inside the Coding4fun library&lt;/a&gt; which also has other nice stuff. You could use this also for difference between Trial and Paying users.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:ace2fbc5-67b0-434e-bdd2-e40f16bf83d0" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public static class AnalyticsProperties
{
    public static string DeviceId
    {
        get
        {
            var value = (byte[]) DeviceExtendedProperties.GetValue(&amp;quot;DeviceUniqueId&amp;quot;);
            return Convert.ToBase64String(value);
        }
    }

    public static string DeviceManufacturer
    {
        get { return DeviceExtendedProperties.GetValue(&amp;quot;DeviceManufacturer&amp;quot;).ToString(); }
    }

    public static string DeviceType
    {
        get { return DeviceExtendedProperties.GetValue(&amp;quot;DeviceName&amp;quot;).ToString(); }
    }

    public static string Device
    {
        get { return string.Format(&amp;quot;{0} - {1}&amp;quot;, DeviceManufacturer, DeviceType); }
    }

    public static string OsVersion
    {
        get { return string.Format(&amp;quot;WP {0}&amp;quot;, Environment.OSVersion.Version); }
    }

    public static string ApplicationVersion
    {
        get { return PhoneHelper.GetAppAttribute(&amp;quot;Version&amp;quot;).Replace(&amp;quot;.0.0&amp;quot;, &amp;quot;&amp;quot;); }
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;So let’s continue with our IApplicationService that wraps the WebAnalyticsService provided by the Analytics Framework. Just to prevent that my applications start to depend to much on Microsoft Silverlight Analytics Framework, I don’t want to change too much code when I need or want to switch next time. I explicitly set the Page Tracking to false because I want to be in control when and what to track. Further more I’m setting the CustomVariables that you might recognize from Google Analytics. There is a &lt;strong&gt;maximum of 5 Custom Variables&lt;/strong&gt; and because the GoogleAnalytics library also puts the ApplicationId inside the Custom Variables you end up having &lt;strong&gt;only four &lt;/strong&gt;for your application. That’s one of the reasons why I have the Device Type and Manufacturer concatenated in the Device property, choose carefully what you want to track. Next is the interesting part of Initializing MEF, I’m not an expert on MEF but basically it’s a kind of IoC container but differently. We will make use of the composition possibilities that we get from using MEF in a moment. The last part is the WebPropertyId which is passed to Google Analytics, this is the Google Analytics Property Id which is in the form of UA-XXXXX-X. So make sure you &lt;a href="https://www.google.com/support/analyticshelp/bin/answer.py?hl=en&amp;amp;answer=1042508&amp;amp;topic=1009620" target="_blank"&gt;register a Google Analytics Web Property&lt;/a&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:89dbe2be-0ae4-4947-aa0e-ac0b1291d3db" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public class AnalyticsService : IApplicationService
{
    private readonly IApplicationService _innerService;
    private readonly GoogleAnalytics _googleAnalytics;

    public AnalyticsService()
    {
        _googleAnalytics = new GoogleAnalytics();
        _googleAnalytics.CustomVariables.Add(new PropertyValue { PropertyName = &amp;quot;Device ID&amp;quot;, Value = AnalyticsProperties.DeviceId });
        _googleAnalytics.CustomVariables.Add(new PropertyValue { PropertyName = &amp;quot;Application Version&amp;quot;, Value = AnalyticsProperties.ApplicationVersion });
        _googleAnalytics.CustomVariables.Add(new PropertyValue { PropertyName = &amp;quot;Device OS&amp;quot;, Value = AnalyticsProperties.OsVersion });
        _googleAnalytics.CustomVariables.Add(new PropertyValue { PropertyName = &amp;quot;Device&amp;quot;, Value = AnalyticsProperties.Device });
        _innerService = new WebAnalyticsService
                            {
                                IsPageTrackingEnabled = false,
                                Services = { _googleAnalytics, }
                            };
    }

    public string WebPropertyId
    {
        get { return _googleAnalytics.WebPropertyId; }
        set { _googleAnalytics.WebPropertyId = value; }
    }

    #region IApplicationService Members

    public void StartService(ApplicationServiceContext context)
    {
        CompositionHost.Initialize(
            new AssemblyCatalog(
                Application.Current.GetType().Assembly),
            new AssemblyCatalog(typeof(AnalyticsEvent).Assembly),
            new AssemblyCatalog(typeof(TrackAction).Assembly));
        _innerService.StartService(context);
    }

    public void StopService()
    {
        _innerService.StopService();
    }

    #endregion
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;You can then add this ApplicationService to the ApplicationLifetimeObjects in the App.xaml file.&lt;/p&gt;



&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:3d4acfb9-430c-412e-a7e9-2c57ea680cad" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;Application.ApplicationLifetimeObjects&amp;gt;
    &amp;lt;!--Required object that handles lifetime events for the application--&amp;gt;
    &amp;lt;shell:PhoneApplicationService Launching=&amp;quot;ApplicationLaunching&amp;quot;
                                    Closing=&amp;quot;ApplicationClosing&amp;quot;
                                    Activated=&amp;quot;ApplicationActivated&amp;quot;
                                    Deactivated=&amp;quot;ApplicationDeactivated&amp;quot; /&amp;gt;
    &amp;lt;Analytics:AnalyticsService WebPropertyId=&amp;quot;UA-XXXXX-X&amp;quot; /&amp;gt;
&amp;lt;/Application.ApplicationLifetimeObjects&amp;gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This also enables automatic tracking Launch, Closing, Activated and Deactivated events in Google Analytics. So we don’t have to do anything manually to enable that part.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2011/10/image-2.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://mark.mymonster.nl/Uploads/2011/10/image-thumb.png" width="644" height="119" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;Step 3 Start tracking usage of features&lt;/h3&gt;

&lt;p&gt;Besides the starting and stopping of your application you probably want to track the usage of features in your app. You can make use of the TrackAction Behavior for example which can be found in Microsoft.WebAnalytics.Behaviors. But I actually like to have this kind of stuff in code which makes it easier for me to get an overview of what I’m tracking. So I wrote this simple AnalyticsTracker class that makes use of MEF to import the WebAnalytics stuff.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:6287a169-1daf-48ba-bb7d-1548fb51a14d" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public class AnalyticsTracker
{
    public AnalyticsTracker()
    {
        CompositionInitializer.SatisfyImports(this);
    }

    [Import(&amp;quot;Log&amp;quot;)]
    public Action&amp;lt;AnalyticsEvent&amp;gt; Log { get; set; }

    public void Track(string category, string name)
    {
        Track(category, name, null);
    }

    public void Track(string category, string name, string actionValue)
    {
        Log(new AnalyticsEvent { Category = category, Name = name, ObjectName = actionValue });
    }
}&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Usage is pretty straightforward.&lt;/p&gt;

&lt;p&gt;
  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:e6da4ffd-ff4e-4c95-8f00-e9715879b81d" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;AnalyticsTracker tracker = new AnalyticsTracker();
tracker.Track(&amp;quot;Advertisement&amp;quot;, &amp;quot;Refreshed&amp;quot;, adUnit);&lt;/pre&gt;&lt;/div&gt;
&lt;/p&gt;

&lt;h3&gt;Step 4 Analyse the data&lt;/h3&gt;

&lt;p&gt;Alright start with Top Events&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2011/10/image-4.png"&gt;&lt;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://mark.mymonster.nl/Uploads/2011/10/image-thumb-1.png" width="644" height="374" /&gt;&lt;/a&gt;&lt;/p&gt;



&lt;p&gt;Cool but in which countries?&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2011/10/image-6.png"&gt;&lt;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://mark.mymonster.nl/Uploads/2011/10/image-thumb-2.png" width="644" height="290" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Of course there much more analytics that you can see inside of Google Analytics, this is just a start. &lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/UMFq-buJyIw" height="1" width="1"/&gt;</description><pubDate>Fri, 21 Oct 2011 22:16:44 +0200</pubDate><a10:updated>2011-10-21T22:16:44+02:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/10/21/statistics-for-your-windows-phone-application-google-analytics</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/qDLNTu4iOcA/improve-the-yslow-score-remove-the-etags</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>ASP.NET</category><category>ASP.NET MVC</category><category>Technology</category><title>Improve the YSlow score - remove the ETags</title><description>&lt;p&gt;There are a lot of resources on the web which tell you how to create a fast website. You can measure the speed with for example &lt;a href="http://developer.yahoo.com/yslow/" target="_blank"&gt;YSlow&lt;/a&gt;. Do you want reasons? Maybe it’s good to read for example &lt;a href="http://www.hanselman.com/blog/TheImportanceAndEaseOfMinifyingYourCSSAndJavaScriptAndOptimizingPNGsForYourBlogOrWebsite.aspx" target="_blank"&gt;Scott Hanselman’s blog&lt;/a&gt; or &lt;a href="http://hanselminutes.com/288/googles-steve-souders-creator-of-yslow-on-web-site-optimization" target="_blank"&gt;his recent podcast in which he interviews Steve Souders the creator of YSlow&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;I’m not here to discuss the reasons, but one of the things that can improve the speed of your website is to get rid of the &lt;a href="http://en.wikipedia.org/wiki/HTTP_ETag" target="_blank"&gt;ETags&lt;/a&gt;. ETags are essentially a kind of checksum that can be used to determine if a file on the server has changed. I wanted to improve my &lt;a href="http://developer.yahoo.com/yslow/" target="_blank"&gt;YSlow&lt;/a&gt; score, and part of the way to improve it was removing the ETag. But how?&lt;/p&gt;  &lt;h3&gt;Manipulate the HTTP headers through configuration?&lt;/h3&gt;  &lt;p&gt;1. Remove the header&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:8c155fd5-c714-4224-b86a-43e316066589" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;httpProtocol&amp;gt;
    &amp;lt;customHeaders&amp;gt;
        &amp;lt;remove name=&amp;quot;ETag&amp;quot; /&amp;gt;
    &amp;lt;/customHeaders&amp;gt;
&amp;lt;/httpProtocol&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Doesn’t work. The header is still sent.&lt;/p&gt;

&lt;p&gt;2. Set the header explicitly to empty string&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:8f6b2d5d-dac5-4c58-a7e0-6cc70ddb9226" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;httpProtocol&amp;gt;
    &amp;lt;customHeaders&amp;gt;
        &amp;lt;add name=&amp;quot;ETag&amp;quot; value=&amp;quot;&amp;quot; /&amp;gt;
    &amp;lt;/customHeaders&amp;gt;
&amp;lt;/httpProtocol&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Doesn’t work either. The header is still sent.&lt;/p&gt;

&lt;h3&gt;What does work? A HTTP Module?&lt;/h3&gt;

&lt;p&gt;Alright, let’s try it, write a small HTTP Module and manipulate the headers before they are sent to the client. I just tried to remove the tag.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:e645f9e9-f907-4491-bcf6-426b70042b4e" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public class RemoveETagModule : IHttpModule
{
    public void Dispose() { }

    public void Init(HttpApplication context)
    {
        context.PreSendRequestHeaders += OnPreSendRequestHeaders;
    }

    void OnPreSendRequestHeaders(object sender, EventArgs e)
    {
        HttpContext.Current.Response.Headers.Remove(&amp;quot;ETag&amp;quot;);
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Of course we need to configure it. So add the below code to your web.config file.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:d9ee32a7-917d-4729-b7e9-64cdf8828092" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;system.webServer&amp;gt;
  ...
  &amp;lt;modules runAllManagedModulesForAllRequests=&amp;quot;true&amp;quot;&amp;gt;
      &amp;lt;add name=&amp;quot;RemoveETag&amp;quot; type=&amp;quot;MM.Website.Web.Modules.RemoveETagModule, MM.Website.Web&amp;quot; /&amp;gt;
  &amp;lt;/modules&amp;gt;
  ...
&amp;lt;/system.webServer&amp;gt;
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Did it work? So let’s run Fiddler.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2011/10/image-2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 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://mark.mymonster.nl/Uploads/2011/10/image-thumb.png" width="244" height="208" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Yes, it’s gone.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/qDLNTu4iOcA" height="1" width="1"/&gt;</description><pubDate>Tue, 18 Oct 2011 21:04:28 +0200</pubDate><a10:updated>2011-10-18T21:04:28+02:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/10/18/improve-the-yslow-score-remove-the-etags</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/Uw6eTC6iCOk/adding-tactile-feedback-to-your-app-the-easy-way</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Phone</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>Used to get articles on www.dotnetmag.nl</category><category>WPDev</category><title>Adding Tactile Feedback to your app the easy way</title><description>&lt;p&gt;About a week ago there was &lt;a href="http://hackingsilverlight.blogspot.com/2011/08/29-ways-to-make-your-wp7-app-killer-and.html" target="_blank"&gt;a very good article with tips to make your wp7 app a killer app&lt;/a&gt;. Tip 24 was about tactile feedback. Tactile feedback can be something like 30 milliseconds running the VibrateController. That’s very easy, just like this:&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:b788178b-0c10-4001-9217-d9fdd13c9d22" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;VibrateController vibrateController = VibrateController.Default;
vibrateController.Start(new TimeSpan(0, 0, 0, 0, 30));&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Because I just want to call one method instead of two lines of code, I created a small static method.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:a65532bd-27a0-48f6-9fd6-716a6afdb2f4" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public static void GiveTactileFeedback()
{
    VibrateController vibrateController = VibrateController.Default;
    vibrateController.Start(new TimeSpan(0, 0, 0, 0, 30));
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Alright, but now I had to add this method call to every Button Click, ListBox SelectionChanged, and ApplicationBar menu or button use. Probably there are some more places where I want to give a little bit of feedback. So I’m thinking about a solution, a generic solution. &lt;a href="http://msdn.microsoft.com/en-us/library/ff941108(v=vs.92).aspx" target="_blank"&gt;I remember how easy it was to apply the TiltEffect&lt;/a&gt;. So my mind was going the direction of a similar solution. So I started with some &lt;a href="http://msdn.microsoft.com/en-us/library/cc903943(v=vs.95).aspx" target="_blank"&gt;Attached Dependency Properties&lt;/a&gt;, the same mechanism that’s used to implement the TiltEffect. So enable it for example in the root of your Phone Page and only suppress the effect if you don’t want to apply it a special occasion.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:ad4a2826-894b-477a-9b92-af8e517a9055" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; highlight: [2]"&gt;&amp;lt;phone:PhoneApplicationPage ... 
                            WPUI:TactileFeedbackEffect.IsTactileFeedbackEnabled=&amp;quot;true&amp;quot;&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;And suppress it in this way.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:f47cef91-f13e-4604-8ee1-14716099e834" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:xml; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;&amp;lt;Button Content=&amp;quot;Feedback surpressed&amp;quot;
        WPUI:TactileFeedbackEffect.SuppressTactileFeedback=&amp;quot;true&amp;quot; /&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Basically I want to walk through all the children of the element that have the IsTactileFeedbackEnabled property set to true. So I started walking recursively through the Visual Tree.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:8a4e302e-2c9d-48e1-9842-a7dff87a7e82" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public static IEnumerable&amp;lt;FrameworkElement&amp;gt; GetSelfAndChildren(this FrameworkElement node)
{
    var elements = new List&amp;lt;FrameworkElement&amp;gt;();
    int childrenCount = VisualTreeHelper.GetChildrenCount(node);
    elements.Add(node);
    for (int i = 0; i &amp;lt; childrenCount; i++)
    {
        var childFe = VisualTreeHelper.GetChild(node, i) as FrameworkElement;
        if (childFe != null)
        {
            elements.AddRange(GetSelfAndChildren(childFe));
        }
    }
    return elements;
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Using this Visual Tree of elements to check against controls that should support the Tactile Feedback: ButtonBase (root of all buttons), Selector (root of the different types of ListBoxes), PhoneApplicationPage (only way to get a hold of the&amp;#160; ApplicationBar’s buttons and menu items). For the menu items and buttons, it’s just simply attaching to the Click event. The Selector has a SelectionChanged event to which we can listen. Not that much of rocket science.&lt;/p&gt;

&lt;p&gt;The initial idea I had was to make use of the Loaded event of the Element that has&amp;#160; the DependencyProperty applied to start walking though the visual tree. But what happened when the Visual Tree changes? Caused for example by Data Binding changes, or any of the other ways that enable you to manipulate the Visual Tree. So I attached to the LayoutUpdated event as well, I had to hack a bit, because the sender in the LayoutUpdated event is always null.&lt;/p&gt;

&lt;p&gt;In het end I came to the conclusion that I didn’t have a way to suppress feedback on the ApplicationBar items.This is mainly because the ApplicationBar items are not inheriting from DependencyObject.&lt;/p&gt;

&lt;p&gt;Full code is below for both the VisualTreeHelper and the TactileFeedbackEffect. Please let me know if you have any questions or improvements.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:0664d3a0-d201-4119-b6a0-bbb18751975e" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:css; gutter:true; first-line: 1; tab-size: 4; toolbar: true; collapse: true; "&gt;/// &amp;lt;summary&amp;gt;
/// Simple helpers for walking the visual tree
/// &amp;lt;/summary&amp;gt;
internal static class TreeHelpers
{
    public static IEnumerable&amp;lt;FrameworkElement&amp;gt; GetSelfAndChildren(this FrameworkElement node)
    {
        var elements = new List&amp;lt;FrameworkElement&amp;gt;();
        int childrenCount = VisualTreeHelper.GetChildrenCount(node);
        elements.Add(node);
        for (int i = 0; i &amp;lt; childrenCount; i++)
        {
            var childFe = VisualTreeHelper.GetChild(node, i) as FrameworkElement;
            if (childFe != null)
            {
                elements.AddRange(GetSelfAndChildren(childFe));
            }
        }
        return elements;
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;
  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:9c690f2b-ec86-48aa-84e5-3c75fa0582b5" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: true; collapse: true; "&gt;public class TactileFeedbackEffect : DependencyObject
{
    /// &amp;lt;summary&amp;gt;
    /// Set this Attached Dependency Property to true to enable tactile feedback on an element and it's children.
    /// &amp;lt;/summary&amp;gt;
    public static readonly DependencyProperty IsTactileFeedbackEnabledProperty = DependencyProperty.RegisterAttached
        (
            &amp;quot;IsTactileFeedbackEnabled&amp;quot;,
            typeof (bool),
            typeof (TactileFeedbackEffect),
            new PropertyMetadata(OnIsTactileFeedbackEnabledChanged)
        );

    /// &amp;lt;summary&amp;gt;
    /// Set this Attached Dependency Property to true to suppress tactile feedback on the element.
    /// &amp;lt;/summary&amp;gt;
    public static readonly DependencyProperty SuppressTactileFeedbackProperty = DependencyProperty.RegisterAttached(
        &amp;quot;SuppressTactileFeedback&amp;quot;,
        typeof (bool),
        typeof (TactileFeedbackEffect),
        new PropertyMetadata(false));

    static TactileFeedbackEffect()
    {
        TactileFeedbackItems = new List&amp;lt;Type&amp;gt;
                                    {typeof (ButtonBase), typeof (PhoneApplicationPage), typeof (Selector)};
    }

    private TactileFeedbackEffect()
    {
    }

    public static List&amp;lt;Type&amp;gt; TactileFeedbackItems { get; private set; }

    public static bool GetIsTactileFeedbackEnabled(DependencyObject source)
    {
        return (bool) source.GetValue(IsTactileFeedbackEnabledProperty);
    }


    public static void SetIsTactileFeedbackEnabled(DependencyObject source, bool value)
    {
        source.SetValue(IsTactileFeedbackEnabledProperty, value);
    }

    public static bool GetSuppressTactileFeedback(DependencyObject source)
    {
        return (bool) source.GetValue(SuppressTactileFeedbackProperty);
    }


    public static void SetSuppressTactileFeedback(DependencyObject source, bool value)
    {
        source.SetValue(SuppressTactileFeedbackProperty, value);
    }

    private static void OnIsTactileFeedbackEnabledChanged(DependencyObject target,
                                                            DependencyPropertyChangedEventArgs args)
    {
        if (target is FrameworkElement)
        {
            if ((bool) args.NewValue)
            {
                (target as FrameworkElement).Loaded += (s, e) =&amp;gt;
                                                            {
                                                                var senderDo = s as DependencyObject;
                                                                TryAttachFeedback(senderDo);
                                                                if (senderDo is FrameworkElement)
                                                                    (senderDo as FrameworkElement).LayoutUpdated +=
                                                                        (s2, e2) =&amp;gt;
                                                                            {
                                                                                TryDetachFeedback(senderDo);
                                                                                TryAttachFeedback(senderDo);
                                                                            };
                                                            };
            }
            else
            {
                TryDetachFeedback(target);
            }
        }
    }

    private static void TryAttachFeedback(DependencyObject target)
    {
        foreach (FrameworkElement element in (target as FrameworkElement).GetSelfAndChildren())
        {
            foreach (Type t in TactileFeedbackItems)
            {
                if (t.IsAssignableFrom(element.GetType()))
                {
                    if ((bool) element.GetValue(SuppressTactileFeedbackProperty) != true)
                    {
                        if (element is ButtonBase)
                        {
                            (element as ButtonBase).Click += TactileFeedbackEffectClick;
                        }
                        if (element is PhoneApplicationPage)
                        {
                            var page = element as PhoneApplicationPage;
                            if (page.ApplicationBar != null)
                            {
                                foreach (IApplicationBarMenuItem button in
                                    page.ApplicationBar.Buttons ?? new List&amp;lt;IApplicationBarMenuItem&amp;gt;())
                                {
                                    button.Click += TactileFeedbackEffectApplicationBarClick;
                                }
                                foreach (IApplicationBarMenuItem menuItem in
                                    page.ApplicationBar.MenuItems ?? new List&amp;lt;IApplicationBarMenuItem&amp;gt;())
                                {
                                    menuItem.Click += TactileFeedbackEffectApplicationBarClick;
                                }
                            }
                        }
                        if (element is Selector)
                        {
                            (element as Selector).SelectionChanged += TactileFeedbackEffectSelectionChanged;
                        }
                    }
                }
            }
        }
    }

    private static void TryDetachFeedback(DependencyObject target)
    {
        foreach (FrameworkElement element in (target as FrameworkElement).GetSelfAndChildren())
        {
            foreach (Type t in TactileFeedbackItems)
            {
                if (t.IsAssignableFrom(element.GetType()))
                {
                    if ((bool) element.GetValue(SuppressTactileFeedbackProperty) != true)
                    {
                        if (element is ButtonBase)
                        {
                            (element as ButtonBase).Click -= TactileFeedbackEffectClick;
                        }
                        if (element is PhoneApplicationPage)
                        {
                            var page = element as PhoneApplicationPage;
                            if (page.ApplicationBar != null)
                            {
                                foreach (IApplicationBarMenuItem button in
                                    page.ApplicationBar.Buttons ?? new List&amp;lt;IApplicationBarMenuItem&amp;gt;())
                                {
                                    button.Click -= TactileFeedbackEffectApplicationBarClick;
                                }
                                foreach (IApplicationBarMenuItem menuItem in
                                    page.ApplicationBar.MenuItems ?? new List&amp;lt;IApplicationBarMenuItem&amp;gt;())
                                {
                                    menuItem.Click -= TactileFeedbackEffectApplicationBarClick;
                                }
                            }
                        }
                        if (element is Selector)
                        {
                            (element as Selector).SelectionChanged -= TactileFeedbackEffectSelectionChanged;
                        }
                    }
                }
            }
        }
    }

    private static void TactileFeedbackEffectSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        GiveTactileFeedback();
    }

    private static void TactileFeedbackEffectApplicationBarClick(object sender, EventArgs e)
    {
        GiveTactileFeedback();
    }

    private static void TactileFeedbackEffectClick(object sender, RoutedEventArgs e)
    {
        GiveTactileFeedback();
    }

    public static void GiveTactileFeedback()
    {
        VibrateController vibrateController = VibrateController.Default;
        vibrateController.Start(new TimeSpan(0, 0, 0, 0, 30));
    }
}
&lt;/pre&gt;&lt;/div&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/Uw6eTC6iCOk" height="1" width="1"/&gt;</description><pubDate>Tue, 13 Sep 2011 08:59:26 +0200</pubDate><a10:updated>2011-09-13T09:15:16+02:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/09/13/adding-tactile-feedback-to-your-app-the-easy-way</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/DgdVQdlpEYs/cache-as-fallback-using-reactive-extensions</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Patterns</category><category>Phone</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>Rx</category><category>Reactive Extensions</category><title>Cache as Fallback using Reactive Extensions</title><description>&lt;p&gt;In my &lt;a href="http://mark.mymonster.nl/2011/08/18/isolated-storage-as-cache-using-reactive-extensions" target="_blank"&gt;previous article&lt;/a&gt; I wrote about how to use the Isolated Storage using Reactive Extensions. Let’s combine that with the ability to access online resources using Reactive Extensions.&lt;/p&gt;  &lt;p&gt;What I want to achieve can be explained best by a picture. Basically if downloading of a resource fails it should fall back to the cache.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2011/08/image-2.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://mark.mymonster.nl/Uploads/2011/08/image-thumb.png" width="439" height="559" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Let’s combine some code from the &lt;a href="http://mark.mymonster.nl/2011/08/18/isolated-storage-as-cache-using-reactive-extensions" target="_blank"&gt;previous article&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;First of all we want to download a resource from the internet, and if that’s successful we want to cache that data.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:6259169d-0abd-4a7e-8d4b-0bd19da9e34e" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; highlight: [8]"&gt;public static IObservable&amp;lt;MemoryStream&amp;gt; CacheAsFallback(Uri onlineResource, string cacheKey)
{
    IObservable&amp;lt;MemoryStream&amp;gt; observableOnlineResource = FromInternet(onlineResource);
    return observableOnlineResource
        .Select(stream =&amp;gt;
                    {
                        CacheResource(stream, cacheKey);
                        stream.Position = 0;
                        return stream;
                    });
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Yes that’s all, it’s easy to combine Reactive Extensions (Rx) with Linq. So the above code will make sure that the resource that’s downloaded is cached before it’s returned to the caller. Please take a notion on the resetting of the stream position.&lt;/p&gt;

&lt;h3&gt;Catch an exception in Reactive Extensions&lt;/h3&gt;

&lt;p&gt;The next step is a little bit less seen in the Rx examples found on the web. &lt;a href="http://msdn.microsoft.com/en-us/library/hh211765(v=vs.103).aspx" target="_blank"&gt;Catch an exception and continue with a different Observable&lt;/a&gt;.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:8cf77c10-19f3-4c93-988e-f3ef94033cc0" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; highlight: [2,3]"&gt;public static IObservable&amp;lt;TSource&amp;gt; Catch&amp;lt;TSource, TException&amp;gt;(
    this IObservable&amp;lt;TSource&amp;gt; source,
    Func&amp;lt;TException, IObservable&amp;lt;TSource&amp;gt;&amp;gt; handler
    )
    where TException : Exception&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;So Catch is an Extension method that accepts a Func&amp;lt;Exception, IObservable&amp;lt;T&amp;gt;&amp;gt;. In our case that would be an IObservable&amp;lt;MemoryStream&amp;gt;. If you want to catch only specific Exception types, you could do that as well, but I want to fall back in case of any error. Further more the FromCache Observable returns null when nothing is found. I want that to be translated to an Exception.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:ba1cd1c6-fe0c-41de-877b-bdc6e1141b21" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public static IObservable&amp;lt;MemoryStream&amp;gt; CacheAsFallback(Uri onlineResource, string cacheKey)
{
    IObservable&amp;lt;MemoryStream&amp;gt; observableOnlineResource = FromInternet(onlineResource);
    return observableOnlineResource
        .Select(stream =&amp;gt;
                    {
                        CacheResource(stream, cacheKey);
                        stream.Position = 0;
                        return stream;
                    })
        .Catch&amp;lt;MemoryStream, Exception&amp;gt;(
            exception =&amp;gt; FromCache(cacheKey)
                                .Select(cacheStream =&amp;gt;
                                            {
                                                if (cacheStream == null)
                                                    throw new Exception(&amp;quot;No cache&amp;quot;);
                                                return cacheStream;
                                            }));
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;So now I can write below code to get a resource, and in case of network connectivity problems it will fallback to a cache value.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:af7cd976-640f-4375-b6a6-f6df7423b3d1" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;const string url = &amp;quot;http://mark.mymonster.nl/Content/photo.jpg&amp;quot;;
IObservable&amp;lt;MemoryStream&amp;gt; observable = ObservableResource.CacheAsFallback(new Uri(url), &amp;quot;photo.jpg&amp;quot;);
observable
    .ObserveOnDispatcher()
    .Subscribe(
        stream =&amp;gt;
            {
                if (stream != null)
                {
                    var image = new BitmapImage();
                    image.SetSource(stream);
                    TargetImage.Source = image;
                }
            },
        exc =&amp;gt; Debug.WriteLine(string.Format(&amp;quot;Oops: {0}&amp;quot;, exc.Message)),
        () =&amp;gt; Debug.WriteLine(&amp;quot;Completed.&amp;quot;));&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Now let’s combine everything we have again, toggle below to view it.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:1a891d02-9f18-498b-a82e-2e906646f20a" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: true; collapse: true; "&gt;public static class StreamExtensions
{
    public static MemoryStream ToMemoryStream(this Stream stream)
    {
        var br = new BinaryReader(stream);
        var outputStream = new MemoryStream();
        var buffer = new byte[1024];
        int cb;
        while ((cb = br.Read(buffer, 0, buffer.Length)) &amp;gt; 0)
        {
            outputStream.Write(buffer, 0, cb);
        }
        outputStream.Position = 0;
        return outputStream;
    }
}

public static class ObservableResource
{
    private const string CacheFolder = &amp;quot;cache&amp;quot;;

    public static IObservable&amp;lt;MemoryStream&amp;gt; CacheAsFallback(Uri onlineResource, string cacheKey)
    {
        IObservable&amp;lt;MemoryStream&amp;gt; observableOnlineResource = FromInternet(onlineResource);
        return observableOnlineResource
            .Select(stream =&amp;gt;
                        {
                            CacheResource(stream, cacheKey);
                            stream.Position = 0;
                            return stream;
                        })
            .Catch&amp;lt;MemoryStream, Exception&amp;gt;(
                exception =&amp;gt; FromCache(cacheKey)
                                    .Select(cacheStream =&amp;gt;
                                                {
                                                    if (cacheStream == null)
                                                        throw new Exception(&amp;quot;No cache&amp;quot;);
                                                    return cacheStream;
                                                }));
    }

    public static void CacheResource(MemoryStream toCache, string cacheKey)
    {
        string targetFile = Path.Combine(CacheFolder, cacheKey);
        using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (!isoFile.DirectoryExists(CacheFolder))
                isoFile.CreateDirectory(CacheFolder);
            if (isoFile.FileExists(targetFile))
                isoFile.DeleteFile(targetFile);
            using (IsolatedStorageFileStream outputStream = isoFile.CreateFile(targetFile))
            {
                toCache.WriteTo(outputStream);
            }
        }
    }

    public static IObservable&amp;lt;MemoryStream&amp;gt; FromCache(string cacheKey)
    {
        return new AnonymousObservable&amp;lt;MemoryStream&amp;gt;(
            observer =&amp;gt;
                {
                    string targetFile = Path.Combine(CacheFolder, cacheKey);

                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!isoFile.FileExists(targetFile))
                        {
                            observer.OnNext(null);
                        }
                        else
                        {
                            using (IsolatedStorageFileStream inputStream =
                                isoFile.OpenFile(targetFile, FileMode.Open, FileAccess.Read))
                            {
                                observer.OnNext(inputStream.ToMemoryStream());
                            }
                        }
                    }
                    observer.OnCompleted();
                    return Disposable.Empty;
                });
    }

    public static IObservable&amp;lt;MemoryStream&amp;gt; FromInternet(Uri onlineResource)
    {
        return
            new AnonymousObservable&amp;lt;WebResponse&amp;gt;(
                observer =&amp;gt;
                    {
                        var httpWebRequest =
                            (HttpWebRequest) WebRequest.Create(onlineResource);
                        httpWebRequest.BeginGetResponse(
                            iar =&amp;gt;
                                {
                                    WebResponse response;
                                    try
                                    {
                                        var requestState = (HttpWebRequest) iar.AsyncState;
                                        response = requestState.EndGetResponse(iar);
                                    }
                                    catch (Exception exception)
                                    {
                                        observer.OnError(exception);
                                        return;
                                    }
                                    observer.OnNext(response);
                                    observer.OnCompleted();
                                }, httpWebRequest);
                        return Disposable.Empty;
                    })
                .Select(
                    response =&amp;gt; response.GetResponseStream().ToMemoryStream());
    }
}&lt;/pre&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/DgdVQdlpEYs" height="1" width="1"/&gt;</description><pubDate>Sat, 20 Aug 2011 10:50:20 +0200</pubDate><a10:updated>2011-08-20T10:50:20+02:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/08/20/cache-as-fallback-using-reactive-extensions</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/zFo-ZDEO4lc/isolated-storage-as-cache-using-reactive-extensions</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Patterns</category><category>Phone</category><category>WP7</category><category>Rx</category><category>Reactive Extensions</category><title>Isolated Storage as Cache using Reactive Extensions</title><description>&lt;p&gt;A lot of people are used to write some data to the Isolated Storage to use it as a Cache. I’m doing that as well, it’s easy to write and read to the Isolated Storage. Some people just write text/xml data and want to put the content in a string. I have however a lot of situations where caching of images is important, so my approach doesn’t make use of a string but a &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.memorystream(v=VS.95).aspx" target="_blank"&gt;MemoryStream&lt;/a&gt; instead. So I have a static method that writes a MemoryStream to a file in Isolated Storage.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:15f0d9ce-bf4b-4253-8e80-784e4544d56b" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;private const string CacheFolder = &amp;quot;cache&amp;quot;;
public static void CacheResource(MemoryStream toCache, string cacheKey)
{
    string targetFile = Path.Combine(CacheFolder, cacheKey);
    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (!isoFile.DirectoryExists(CacheFolder))
            isoFile.CreateDirectory(CacheFolder);
        if (isoFile.FileExists(targetFile))
            isoFile.DeleteFile(targetFile);
        using (IsolatedStorageFileStream outputStream = isoFile.CreateFile(targetFile))
        {
            toCache.WriteTo(outputStream);
        }
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;That’s the easy part &lt;em&gt;writing&lt;/em&gt;. I must admit reading isn’t much more complicated, unless you want to read it in a special way, namely using &lt;a href="http://msdn.microsoft.com/en-us/data/gg577609" target="_blank"&gt;Reactive Extensions&lt;/a&gt; (Rx). Reactive Extensions offer a different way to look at asynchronous code, instead of listening to events, it allows to subscribe to things that happen. In addition to this it supports &lt;a href="http://msdn.microsoft.com/en-us/netframework/aa904594" target="_blank"&gt;Linq&lt;/a&gt; on observable objects. I’m not going to dig deep on Rx, there are &lt;a href="http://msdn.microsoft.com/en-us/data/gg577611" target="_blank"&gt;other blogs that can do that much better&lt;/a&gt;. The mechanism described in this article is intended for use in Windows Phone, but should work in Silverlight as well.&lt;/p&gt;

&lt;h3&gt;Reactive Extensions (Rx) over WebRequest&lt;/h3&gt;

&lt;p&gt;So why did I want to do use Rx? It’s simple: I want to have a similar signature and way of usage of code when I access content online (Async required) and when I access content from the cache (Standard only sync access). So how do I access online content?&lt;/p&gt;

&lt;p&gt;In this example, I’m downloading online content and setting the MemoryStream as the Source of a &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage(v=VS.95).aspx" target="_blank"&gt;BitmapImage&lt;/a&gt; and put the BitmapImage as the source of an Image control. It’s a regular Rx way of reacting on an &lt;a href="http://msdn.microsoft.com/en-us/library/dd990377(v=VS.92).aspx" target="_blank"&gt;Observable&lt;/a&gt;, where I put a &lt;a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" target="_blank"&gt;lambda&lt;/a&gt; to react on OnNext, OnError and OnCompleted. Further more because I’m interacting with the User Interface it’s important to run that code on the Dispatcher. &lt;a href="http://mark.mymonster.nl/2008/07/12/silverlight-threading-getting-back-to-the-ui-thread#comments" target="_blank"&gt;Running code on the dispatcher can be done manually&lt;/a&gt; or you can use Rx combined with &lt;a href="http://msdn.microsoft.com/en-us/library/ff708114(v=vs.92).aspx" target="_blank"&gt;ObserveOnDispatcher&lt;/a&gt; method. &lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:6ada2d8a-09a7-4b84-945d-9a0990196e4b" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;const string url = &amp;quot;http://mark.mymonster.nl/Content/photo.jpg&amp;quot;;
IObservable&amp;lt;MemoryStream&amp;gt; observable = ObservableResource.FromInternet(new Uri(url));
observable
    .ObserveOnDispatcher()
    .Subscribe(
        stream =&amp;gt;
        {
            if (stream != null)
            {
                var image = new BitmapImage();
                image.SetSource(stream);
                TargetImage.Source = image;
            }
        },
        exc =&amp;gt; Debug.WriteLine(string.Format(&amp;quot;Oops: {0}&amp;quot;, exc.Message)),
        () =&amp;gt; Debug.WriteLine(&amp;quot;Completed.&amp;quot;));&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;So how does my ResourceHelper.OnlineResource method look like? I’m using an AnonymousObservable to construct an observable from the Async pattern in a WebRequest. Please don’t tell me I could use &lt;a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.fromasyncpattern(v=vs.103).aspx" target="_blank"&gt;Observable.FromAsyncPattern&lt;/a&gt;, I’ve used it in the past, but have stopped using it, I’m now writing my own Observable code to be sure I’m in control.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:2bb72de3-73d8-4b2a-8335-d2c93edcbb4c" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public class AnonymousObservable&amp;lt;T&amp;gt; : IObservable&amp;lt;T&amp;gt;
{
    private readonly Func&amp;lt;IObserver&amp;lt;T&amp;gt;, IDisposable&amp;gt; _subscribeAction;

    public AnonymousObservable(Func&amp;lt;IObserver&amp;lt;T&amp;gt;, IDisposable&amp;gt; subscribeAction)
    {
        _subscribeAction = subscribeAction;
    }

    #region IObservable&amp;lt;T&amp;gt; Members

    public IDisposable Subscribe(IObserver&amp;lt;T&amp;gt; observer)
    {
        return _subscribeAction(observer);
    }

    #endregion
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This anonymous Observable class is a simple implementation that get’s a lambda passed in which will be executed on Subscribe. So finally we have the FromInternet implementation combined with a operation that reads a stream to a MemoryStream.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:25692c01-3df6-478c-acbd-02bed959d920" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public static IObservable&amp;lt;MemoryStream&amp;gt; FromInternet(Uri onlineResource)
{
    return
        new AnonymousObservable&amp;lt;WebResponse&amp;gt;(
            observer =&amp;gt;
                {
                    var httpWebRequest =
                        (HttpWebRequest) WebRequest.Create(onlineResource);
                    httpWebRequest.BeginGetResponse(
                        iar =&amp;gt;
                            {
                                WebResponse response;
                                try
                                {
                                    var requestState = (HttpWebRequest) iar.AsyncState;
                                    response = requestState.EndGetResponse(iar);
                                }
                                catch (Exception exception)
                                {
                                    observer.OnError(exception);
                                    return;
                                }
                                observer.OnNext(response);
                                observer.OnCompleted();
                            }, httpWebRequest);
                    return Disposable.Empty;
                })
            .Select(
                response =&amp;gt; response.GetResponseStream().ToMemoryStream());
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;What you can see in the Lambda that get’s passed into the AnonymousObservable for Online Resources, it’s similar to what we would have done in the past, but now it’s calling observer.OnNext, observer.OnError and observer.OnCompleted operations. Further more you can see that I attached a Select operation we are used to in Linq to convert a WebResponse to a MemoryStream using the ToMemoryStream extension method.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:30f1941b-0421-4722-9c32-e84a760c1dd3" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public static class StreamExtensions
{
    public static MemoryStream ToMemoryStream(this Stream stream)
    {
        var br = new BinaryReader(stream);
        var outputStream = new MemoryStream();
        var buffer = new byte[1024];
        int cb;
        while ((cb = br.Read(buffer, 0, buffer.Length)) &amp;gt; 0)
        {
            outputStream.Write(buffer, 0, cb);
        }
        outputStream.Position = 0;
        return outputStream;
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;h3&gt;Reactive Extensions (Rx) over Isolated Storage&lt;/h3&gt;

&lt;p&gt;So far it has all been preparation for the Reactive Extensions over Isolated Storage. Where the implementation is actually really simple, it’s now wrapped in an Anonymous Observable.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:a089c699-b88a-4e90-9427-55cbc3fc0b61" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;public static IObservable&amp;lt;MemoryStream&amp;gt; FromCache(string cacheKey)
{
    return new AnonymousObservable&amp;lt;MemoryStream&amp;gt;(
        observer =&amp;gt;
            {
                string targetFile = Path.Combine(CacheFolder, cacheKey);

                using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!isoFile.FileExists(targetFile))
                    {
                        observer.OnNext(null);
                    }
                    else
                    {
                        using (IsolatedStorageFileStream inputStream =
                            isoFile.OpenFile(targetFile, FileMode.Open, FileAccess.Read))
                        {
                            observer.OnNext(inputStream.ToMemoryStream());
                        }
                    }
                }
                observer.OnCompleted();
                return Disposable.Empty;
            });
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This now enables me to get something from cache in the same way as I can get something from the internet. Please mark the “photo.jpg” is a key for accessing the cache, which in the end results in data. If you choose a different caching-strategy you should remind this is a cache key.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:e030628e-755b-4afc-8260-86a2a3ff0fe7" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: false; collapse: false; "&gt;IObservable&amp;lt;MemoryStream&amp;gt; observable = ObservableResource.FromCache(&amp;quot;photo.jpg&amp;quot;);
observable
    .ObserveOnDispatcher()
    .Subscribe(
        stream =&amp;gt;
        {
            if (stream != null)
            {
                var image = new BitmapImage();
                image.SetSource(stream);
                TargetImage.Source = image;
            }
        },
        exc =&amp;gt; Debug.WriteLine(string.Format(&amp;quot;Oops: {0}&amp;quot;, exc.Message)),
        () =&amp;gt; Debug.WriteLine(&amp;quot;Completed.&amp;quot;));&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;You can find the full source code here, by toggling.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:BF48545B-72FC-48CD-B241-BB2967E2EF01:acca0009-d1e0-4add-a90a-2e7f1b75d64f" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush:csharp; gutter:true; first-line: 1; tab-size: 4; toolbar: true; collapse: true; "&gt;public static class StreamExtensions
{
    public static MemoryStream ToMemoryStream(this Stream stream)
    {
        var br = new BinaryReader(stream);
        var outputStream = new MemoryStream();
        var buffer = new byte[1024];
        int cb;
        while ((cb = br.Read(buffer, 0, buffer.Length)) &amp;gt; 0)
        {
            outputStream.Write(buffer, 0, cb);
        }
        outputStream.Position = 0;
        return outputStream;
    }
}

public static class ObservableResource
{
    private const string CacheFolder = &amp;quot;cache&amp;quot;;

    public static void CacheResource(MemoryStream toCache, string cacheKey)
    {
        string targetFile = Path.Combine(CacheFolder, cacheKey);
        using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (!isoFile.DirectoryExists(CacheFolder))
                isoFile.CreateDirectory(CacheFolder);
            if (isoFile.FileExists(targetFile))
                isoFile.DeleteFile(targetFile);
            using (IsolatedStorageFileStream outputStream = isoFile.CreateFile(targetFile))
            {
                toCache.WriteTo(outputStream);
            }
        }
    }

    public static IObservable&amp;lt;MemoryStream&amp;gt; FromCache(string cacheKey)
    {
        return new AnonymousObservable&amp;lt;MemoryStream&amp;gt;(
            observer =&amp;gt;
                {
                    string targetFile = Path.Combine(CacheFolder, cacheKey);

                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!isoFile.FileExists(targetFile))
                        {
                            observer.OnNext(null);
                        }
                        else
                        {
                            using (IsolatedStorageFileStream inputStream =
                                isoFile.OpenFile(targetFile, FileMode.Open, FileAccess.Read))
                            {
                                observer.OnNext(inputStream.ToMemoryStream());
                            }
                        }
                    }
                    observer.OnCompleted();
                    return Disposable.Empty;
                });
    }

    public static IObservable&amp;lt;MemoryStream&amp;gt; FromInternet(Uri onlineResource)
    {
        return
            new AnonymousObservable&amp;lt;WebResponse&amp;gt;(
                observer =&amp;gt;
                    {
                        var httpWebRequest =
                            (HttpWebRequest) WebRequest.Create(onlineResource);
                        httpWebRequest.BeginGetResponse(
                            iar =&amp;gt;
                                {
                                    WebResponse response;
                                    try
                                    {
                                        var requestState = (HttpWebRequest) iar.AsyncState;
                                        response = requestState.EndGetResponse(iar);
                                    }
                                    catch (Exception exception)
                                    {
                                        observer.OnError(exception);
                                        return;
                                    }
                                    observer.OnNext(response);
                                    observer.OnCompleted();
                                }, httpWebRequest);
                        return Disposable.Empty;
                    })
                .Select(
                    response =&amp;gt; response.GetResponseStream().ToMemoryStream());
    }
}&lt;/pre&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/zFo-ZDEO4lc" height="1" width="1"/&gt;</description><pubDate>Thu, 18 Aug 2011 21:52:58 +0200</pubDate><a10:updated>2011-08-18T21:52:58+02:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/08/18/isolated-storage-as-cache-using-reactive-extensions</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/EIG9Y7a5O1I/silverlight--windows-phone-7-behavior-to-enhance-usability-of-textboxes</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>Used to get articles on www.dotnetmag.nl</category><title>Silverlight / Windows Phone 7 Behavior to enhance Usability of TextBoxes</title><description>&lt;p&gt;Yesterday I used an application on my Windows Phone which was very useful. When you gave focus to a TextBox it would immediately select all of the content of the TextBox. Though it’s not difficult to implement I found it very useful, and see it as a productivity enhancement for the users of the application.&lt;/p&gt;  &lt;p&gt;The behavior is applied on any TextBox, and will attach to the GotFocus event and on the occurrence of the event it will execute the SelectAll method of the TextBox.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:16a9b34b-2d1d-45b6-b541-f0b78ba5b1d1" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public class SelectAllOnFocusBehavior : Behavior&amp;lt;TextBox&amp;gt;
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.GotFocus += GotFocus;
    }

    private void GotFocus(object sender, RoutedEventArgs e)
    {
        AssociatedObject.SelectAll();
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.GotFocus -= GotFocus;
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;And using it is really simple. Just like any other Behavior add it to the Interaction.Behaviors collection of the TextBox where you want to apply this behavior.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:99cce013-9b73-4a71-b2d8-0fedb2375f4e" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: xml; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;&amp;lt;TextBox Text=&amp;quot;Some content&amp;quot;&amp;gt;
    &amp;lt;I:Interaction.Behaviors&amp;gt;
        &amp;lt;Behaviors:SelectAllOnFocusBehavior /&amp;gt;
    &amp;lt;/I:Interaction.Behaviors&amp;gt;
&amp;lt;/TextBox&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;The result could like like this, after giving focus to the TextBox.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.monsterconsultancy.nl/Uploads/2011/04/image-2.png"&gt;&lt;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="Behavior applied to the TextBox in a Windows Phone application" border="0" alt="Behavior applied to the TextBox in a Windows Phone application" src="http://mark.monsterconsultancy.nl/Uploads/2011/04/image-thumb.png" width="244" height="126" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/EIG9Y7a5O1I" height="1" width="1"/&gt;</description><pubDate>Wed, 13 Apr 2011 15:00:00 +0200</pubDate><a10:updated>2011-04-13T15:01:02+02:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/04/13/silverlight--windows-phone-7-behavior-to-enhance-usability-of-textboxes</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/G5yXj9G0uuQ/microsoft-devdays-2011-irsquom-attending</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Silverlight</category><category>SIXIN</category><category>Technology</category><category>WP7</category><category>Used to get articles on www.dotnetmag.nl</category><title>Microsoft DevDays 2011 - I&amp;rsquo;m attending</title><description>&lt;p&gt;&lt;a href="http://www.techdays.nl/"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top: 0px; border-right: 0px; padding-top: 0px" title="devdays_lounge" border="0" alt="devdays_lounge" align="right" src="http://mark.monsterconsultancy.nl/Uploads/2011/04/devdays-lounge-3.png" width="111" height="180" /&gt;&lt;/a&gt;Yes I’m attending the &lt;a href="http://www.techdays.nl/DevDays" target="_blank"&gt;DevDays&lt;/a&gt; this year, but only one day. I will be representing &lt;a href="http://www.sixin.nl/Home.aspx" target="_blank"&gt;Sixin&lt;/a&gt; in the Community Lounge on Thursday April 28th. The last day you can find &lt;a href="http://antonidol.wordpress.com/" target="_blank"&gt;Antoni Dol&lt;/a&gt; representing &lt;a href="http://www.sixin.nl/Home.aspx" target="_blank"&gt;Sixin&lt;/a&gt; at the same place.&lt;/p&gt;  &lt;p&gt;If my schedule allows it, I will try to attend a couple of sessions as well. I’m thinking about the following agenda.&lt;/p&gt;  &lt;p&gt;9:15 – 10:45 Keynote by &lt;a href="http://www.robmiles.com/" target="_blank"&gt;Rob Miles&lt;/a&gt;, &lt;a href="http://www.wadewegner.com/" target="_blank"&gt;Wade Wegner&lt;/a&gt;, &lt;a href="http://www.hanselman.com/blog/" target="_blank"&gt;Scott Hanselman&lt;/a&gt; and &lt;a href="http://blogs.msdn.com/b/benriga/" target="_blank"&gt;Ben Riga&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;11:05 – 12:20 &lt;a href="http://live.visitmix.com/MIX11/Sessions/Tagged/Windows-Phone" target="_blank"&gt;Windows Phone 7&lt;/a&gt;, title will be announced after &lt;a href="http://live.visitmix.com/MIX11/Sessions/Tagged/Windows-Phone" target="_blank"&gt;Mix11&lt;/a&gt; by &lt;a href="http://blogs.msdn.com/b/benriga/" target="_blank"&gt;Ben Riga&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;13:30 – 14:45 &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896" target="_blank"&gt;Reactive Extensions&lt;/a&gt; for .NET for the Rest of Us by &lt;a href="http://mtaulty.com/communityserver/blogs/mike_taultys_blog/default.aspx" target="_blank"&gt;Mike Taulty&lt;/a&gt;. I’m really doubting how this session could be a level 300 session, I would expect it to be level 400. &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896" target="_blank"&gt;Rx&lt;/a&gt; had been mind blowing for me so far.&lt;/p&gt;  &lt;p&gt;15:05 – 16:20 Science of Great UI by &lt;a href="http://community.devexpress.com/blogs/markmiller/default.aspx" target="_blank"&gt;Mark Miller&lt;/a&gt;. Though I’m still a developer, not great at UI, but I want to improve my skills.&lt;/p&gt;  &lt;p&gt;But of course see me at the for some talks around Silverlight, for example &lt;a href="http://live.visitmix.com/MIX11/Sessions/Tagged/Silverlight" target="_blank"&gt;Silverlight 5&lt;/a&gt;, &lt;a href="http://create.msdn.com/en-US/" target="_blank"&gt;WP7&lt;/a&gt;, or anything else.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/G5yXj9G0uuQ" height="1" width="1"/&gt;</description><pubDate>Mon, 11 Apr 2011 21:07:36 +0200</pubDate><a10:updated>2011-04-11T21:11:53+02:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/04/11/microsoft-devdays-2011-irsquom-attending</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/7efKq0i3Wgs/validating-our-viewmodel</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>MVVM</category><category>Silverlight</category><category>Technology</category><category>Used to get articles on www.dotnetmag.nl</category><title>Validating our ViewModel</title><description>&lt;p&gt;One of the key features that need to be implemented in a Line of Business application. Although Silverlight supports validation very well it’s not that easy compared to enabling Data Binding your ViewModel.&lt;/p&gt;  &lt;p&gt;When we want our ViewModel to be fully Data Bindable we implement the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=VS.95).aspx" target="_blank"&gt;INotifyPropertyChanged&lt;/a&gt; interface. It’s really an easy interface with an Event that needs to be called when the value of a property has changed. A lot of people don’t implement this interface themselves but use a framework like &lt;a href="http://galasoft.ch/mvvm/getstarted/" target="_blank"&gt;MVVM Light&lt;/a&gt;. I’m using that as well.&lt;/p&gt;  &lt;p&gt;To make the validation work in a similar way we will have to implement &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifydataerrorinfo(v=vs.95).aspx" target="_blank"&gt;INotifyDataErrorInfo&lt;/a&gt;. This is similar but I haven’t found a framework implementing it for me, so I wrote my own implementation of a ViewModelBase that both supports INotifyPropertyChanged and INotifyDataErrorInfo.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2010/06/b4f4072223c8_12102/2011-02-25_1422.png"&gt;&lt;font style="background-color: #ffff00"&gt;&lt;/font&gt;&lt;/a&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2010/06/b4f4072223c8_12102/2011-02-25_1422.png"&gt;&lt;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="INotifyDataErrorInfo interface" border="0" alt="INotifyDataErrorInfo interface" src="http://mark.mymonster.nl/Uploads/2010/06/b4f4072223c8_12102/2011-02-25_1422_thumb.png" width="207" height="208" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Declaring the validation rules&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Now that we have a ViewModel which supports validation we need to use it in our ViewModels. Let’s say that we have a LoginViewModel, which requires a Username and Password to be filled in.&lt;/p&gt;  &lt;p&gt;So we need to declare our properties Username and Password as &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute(v=VS.95).aspx" target="_blank"&gt;Required&lt;/a&gt;. Besides that we also want the message text to be changed to something different than the default, so we set the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.errormessage(v=VS.95).aspx" target="_blank"&gt;ErrorMessage&lt;/a&gt; property.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:6bdfe3b2-d278-4754-bb39-07b99cc207fc" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public class Login : ViewModelBase
{
    private string _password;
    private bool _rememberMe;
    private string _userName;

    [Required(AllowEmptyStrings = false, ErrorMessage = &amp;quot;Username is required&amp;quot;)]
    public string UserName
    {
        get { return _userName; }
        set
        {
            if (_userName != value)
            {
                ValidateProperty(&amp;quot;UserName&amp;quot;, value);
                _userName = value;
                base.RaisePropertyChanged(&amp;quot;UserName&amp;quot;);
            }
        }
    }

    [Required(AllowEmptyStrings = false, ErrorMessage = &amp;quot;Password is required&amp;quot;)]
    public string Password
    {
        get { return _password; }
        set
        {
            if (_password != value)
            {
                ValidateProperty(&amp;quot;Password&amp;quot;, value);
                _password = value;
                base.RaisePropertyChanged(&amp;quot;Password&amp;quot;);
            }
        }
    }

    public bool RememberMe
    {
        get { return _rememberMe; }
        set
        {
            if (_rememberMe != value)
            {
                _rememberMe = value;
                base.RaisePropertyChanged(&amp;quot;RememberMe&amp;quot;);
            }
        }
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Alright this was the usage of one of the most rudimentary validation types. A small overview of all the different supported validation types. &lt;/p&gt;

&lt;p&gt;- &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute(v=VS.95).aspx" target="_blank"&gt;RequiredAttribute&lt;/a&gt; used to check if a property has a value and will return invalid in case of null, empty string, or only white space characters.&lt;/p&gt;

&lt;p&gt;- &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.datatypeattribute(v=VS.95).aspx" target="_blank"&gt;DataTypeAttribute&lt;/a&gt; like it’s name the data type validator validates a value against certain ‘data types’: DateTime, Date, Time, Duration, PhoneNumber, Currency, Text, Html, MultilineText, EmailAddress, Password, Url, ImageUrl.&lt;/p&gt;

&lt;p&gt;- &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute(v=VS.95).aspx" target="_blank"&gt;RangeAttribute&lt;/a&gt; is used to validate int, decimal and double values which need to fall between certain min and max values.&lt;/p&gt;

&lt;p&gt;- &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.regularexpressionattribute(v=VS.95).aspx" target="_blank"&gt;RegularExpressionAttribute&lt;/a&gt; can be used for more advanced scenario’s where you can write the full regular expression which should be used to validate against.&lt;/p&gt;

&lt;p&gt;- &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.stringlengthattribute(v=VS.95).aspx" target="_blank"&gt;StringLengthAttribute&lt;/a&gt; can be used to validate the length of a string in characters, you can specify both the maximum length and minimum length, but one of them is also possible. Be aware that a null value will be seen as valid!&lt;/p&gt;

&lt;p&gt;- &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(v=VS.95).aspx" target="_blank"&gt;CustomValidationAttribute&lt;/a&gt; used in the most complex validation scenario’s. The CustomValidationAttribute needs to be used in conjunction with a static method which returns a ValidationResult. This static method can be used to implement your very complex validation rules.&lt;/p&gt;

&lt;p&gt;And if the above validation types don’t fit, you can always derive from the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute(v=VS.95).aspx#Y826" target="_blank"&gt;ValidationAttribute&lt;/a&gt; and write your own implementation. It’s important to know that in case of a null-value the properties won’t be validated. This is something that’s not always helpful, specially in case of the CustomValidation where you want to implement a conditional required field validation. The Required validation does get fired in case of null-value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tools to enforce our ValidationAttributes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We have the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validator(v=VS.95).aspx" target="_blank"&gt;Validator class&lt;/a&gt; that has a few static methods that can validate an object that’s decorated with &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute(v=VS.95).aspx" target="_blank"&gt;ValidationAttributes&lt;/a&gt;. There is a &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validator.tryvalidateproperty(v=VS.95).aspx" target="_blank"&gt;method for validating a single property&lt;/a&gt;, which is handy in case you want immediate feedback on the change of the value of the property. And there is of course &lt;a href="http://msdn.microsoft.com/en-us/library/dd411772(v=VS.95).aspx" target="_blank"&gt;a method for validating the full object&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Time to implement the INotifyDataErrorInfo&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To give everyone a clear understanding the implementation of INotifyDataErrorInfo will be a step by step implementation. If you’re only interested in the solution, you can of course skip this, and go to the end of the article.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;ErrorsChanged event:&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;To start with the easy stuff, we need a way to notify that there are some errors. So besides the ErrorsChanged event we need a method to fire ErrorsChanged.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:c266ed4b-5709-49e7-9704-21f7f56b55f6" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public event EventHandler&amp;lt;DataErrorsChangedEventArgs&amp;gt; ErrorsChanged;

protected void NotifyErrorsChanged(string propertyName)
{
    if (ErrorsChanged != null)
        ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;GetErrors method and HasErrors property:&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The GetErrors method needs to return errors for a specific property, so what we need is someway to store the errors. To store the errors I added a dictionary where the key would be the property name and the value would be a list of errror messages. GetErrors is in that case easily implemented by just returning data based on the key.&lt;/p&gt;

&lt;p&gt;Further more the HasErrors is a matter of looking whether or not the dictionary has any data.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:eae024ae-673e-4457-868a-b18dad9bd124" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;private readonly IDictionary&amp;lt;string, IList&amp;lt;string&amp;gt;&amp;gt; _errors = new Dictionary&amp;lt;string, IList&amp;lt;string&amp;gt;&amp;gt;();

public IEnumerable GetErrors(string propertyName)
{
    if (_errors.ContainsKey(propertyName))
    {
        IList&amp;lt;string&amp;gt; propertyErrors = _errors[propertyName];
        foreach (string propertyError in propertyErrors)
        {
            yield return propertyError;
        }
    }
    yield break;
}

public bool HasErrors
{
    get { return _errors.Count &amp;gt; 0; }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;But how do we get some errors in the Dictionary?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As you have seen the implementation of INotifyDataErrorInfo is really straightforward, but we don’t do any validation yet. One of the scenario’s that’s very neat I would say is the ability to immediately give feedback to our users about validation problems. So when the value of a property is set (through two way binding for example) we want to validate immediately.&lt;/p&gt;

&lt;p&gt;That’s not particularly difficult if we compare it to the normal MVVM property signature we only need to Validate a property. To keep it similar to the &lt;a href="http://galasoft.ch/mvvm/getstarted/" target="_blank"&gt;MVVM Light&lt;/a&gt; RaisePropertyChanged, we have to include the property name and value as well.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:ceb03d6b-600f-41af-bc51-99ce3ed260b3" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true;  highlight: 9 ;"&gt;[Required(AllowEmptyStrings = false, ErrorMessage = &amp;quot;Username is required&amp;quot;)]
public string UserName
{
    get { return _userName; }
    set
    {
        if (_userName != value)
        {
            ValidateProperty(&amp;quot;UserName&amp;quot;, value);
            _userName = value;
            base.RaisePropertyChanged(&amp;quot;UserName&amp;quot;);
        }
    }
}
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Now we of course want to have an implementation for ValidateProperty. This implementation needs to validate only a specific property value against the rules for that property. We can make use of the Validator class that implements the actual checking against the validation rules. Together with two helper methods to add and remove validation messages from Errors collection we have the following code. We make use of the Validator to validate a property, and after we have the results we notify that Errors have been changed.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:9af83690-cbc2-4841-94f8-46970f605efb" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;protected void ValidateProperty(string propertyName, object value)
{
    ViewModelBase objectToValidate = this;
    var results = new List&amp;lt;ValidationResult&amp;gt;();
    bool isValid = Validator.TryValidateProperty(
        value,
        new ValidationContext(objectToValidate, null, null)
            {
                MemberName = propertyName
            },
        results);

    if (isValid)
        RemoveErrorsForProperty(propertyName);
    else
        AddErrorsForProperty(propertyName, results);

    NotifyErrorsChanged(propertyName);
}

private void AddErrorsForProperty(string propertyName, IEnumerable&amp;lt;ValidationResult&amp;gt; validationResults)
{
    RemoveErrorsForProperty(propertyName);
    _errors.Add(propertyName, validationResults.Select(vr =&amp;gt; vr.ErrorMessage).ToList());
}

private void RemoveErrorsForProperty(string propertyName)
{
    if (_errors.ContainsKey(propertyName))
        _errors.Remove(propertyName);
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This works very well in the conjunction with the View, but somehow we also need to check if the full ViewModel is valid. This is especially important in when we hit for example the buttons that need to save our data to a “repository”. Besides the Validator.TryValidateProperty there also is a Validator.TryValidateObject. So let’s write a similar operation as the ValidateProperty, but now something we are able to use on Commands, so it needs to return a boolean where or not the ViewModel is valid. Again most of the magic is in the Validator.TryValidateObject, afterwards we split the full list of ValidationResults per property, to give feedback to our View.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:23b2dd90-d4ef-44c1-a210-1615750eadbe" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true;  highlight: 6 ;"&gt;public bool ValidateObject()
{
    ViewModelBase objectToValidate = this;
    _errors.Clear();
    var results = new List&amp;lt;ValidationResult&amp;gt;();
    bool isValid = Validator.TryValidateObject(objectToValidate,
                                                new ValidationContext(objectToValidate, null, null), results,
                                                true);
    if (!isValid)
    {
        IEnumerable&amp;lt;string&amp;gt; propertiesWithMessage = results.SelectMany(vr =&amp;gt; vr.MemberNames);
        foreach (string property in propertiesWithMessage)
        {
            IEnumerable&amp;lt;ValidationResult&amp;gt; messages = results.Where(vr =&amp;gt; vr.MemberNames.Contains(property));
            AddErrorsForProperty(property, messages);
            NotifyErrorsChanged(property);
        }
    }
    return isValid;
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Problem to solve&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next is a problem we will need to solve. &lt;em&gt;&lt;strong&gt;When the value of a property is null none of the validation attributes will be enforced&lt;/strong&gt;&lt;/em&gt;, except the RequiredAttribute. This is really a problem for our CustomValidationAttribute when we implement a rule that should do something special in case of a null value.&lt;/p&gt;

&lt;p&gt;After a better investigation I found out that all validation attributes are enforced when we validate a single property with the Validator class. Which isn’t happening when we use the full object validation implemented by the Validator class.&lt;/p&gt;

&lt;p&gt;So why not solve it ourselves, by executing the Validate property method on all properties? Good idea, so I implemented it in our ViewModelBase. It’s pretty straightforward the first get all the properties, and then filter these to get the properties which have ValidationAttributes applied. End will be the call to validate the property for that specific value in line 12.&lt;/p&gt;

&lt;p&gt;
  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:354c6d99-5a36-4977-9153-250827eff9b7" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true;  highlight: 12 ;"&gt;public bool ValidateObject()
{
    ViewModelBase objectToValidate = this;
    _errors.Clear();
    Type objectType = objectToValidate.GetType();
    PropertyInfo[] properties = objectType.GetProperties();
    foreach (PropertyInfo property in properties)
    {
        if (property.GetCustomAttributes(typeof (ValidationAttribute), true).Any())
        {
            object value = property.GetValue(objectToValidate, null);
            ValidateProperty(property.Name, value);
        }
    }

    return !HasErrors;
}&lt;/pre&gt;&lt;/div&gt;
&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Full source&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As always the full source of my ViewModelBase, which enhances the functionality of the &lt;a href="http://galasoft.ch/mvvm/getstarted/" target="_blank"&gt;MVVM Light&lt;/a&gt; ViewModelBase.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:96c79a96-a84e-4465-bc77-e3e74749d277" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true;  collapse: true;"&gt;public abstract class ViewModelBase : GalaSoft.MvvmLight.ViewModelBase, INotifyDataErrorInfo
{
    private readonly IDictionary&amp;lt;string, IList&amp;lt;string&amp;gt;&amp;gt; _errors = new Dictionary&amp;lt;string, IList&amp;lt;string&amp;gt;&amp;gt;();

    protected ViewModelBase()
    {
    }

    protected ViewModelBase(IMessenger messenger)
        : base(messenger)
    {
    }

    #region INotifyDataErrorInfo Members

    public IEnumerable GetErrors(string propertyName)
    {
        if (_errors.ContainsKey(propertyName))
        {
            IList&amp;lt;string&amp;gt; propertyErrors = _errors[propertyName];
            foreach (string propertyError in propertyErrors)
            {
                yield return propertyError;
            }
        }
        yield break;
    }

    public bool HasErrors
    {
        get { return _errors.Count &amp;gt; 0; }
    }

    public event EventHandler&amp;lt;DataErrorsChangedEventArgs&amp;gt; ErrorsChanged;

    #endregion

    protected void NotifyErrorsChanged(string propertyName)
    {
        if (ErrorsChanged != null)
            ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
    }

    protected void ValidateProperty(string propertyName, object value)
    {
        ViewModelBase objectToValidate = this;
        var results = new List&amp;lt;ValidationResult&amp;gt;();
        bool isValid = Validator.TryValidateProperty(
            value,
            new ValidationContext(objectToValidate, null, null)
                {
                    MemberName = propertyName
                },
            results);

        if (isValid)
            RemoveErrorsForProperty(propertyName);
        else
            AddErrorsForProperty(propertyName, results);

        NotifyErrorsChanged(propertyName);
    }

    private void AddErrorsForProperty(string propertyName, IEnumerable&amp;lt;ValidationResult&amp;gt; validationResults)
    {
        RemoveErrorsForProperty(propertyName);
        _errors.Add(propertyName, validationResults.Select(vr =&amp;gt; vr.ErrorMessage).ToList());
    }

    private void RemoveErrorsForProperty(string propertyName)
    {
        if (_errors.ContainsKey(propertyName))
            _errors.Remove(propertyName);
    }

    public bool ValidateObject()
    {
        ViewModelBase objectToValidate = this;
        _errors.Clear();
        Type objectType = objectToValidate.GetType();
        PropertyInfo[] properties = objectType.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            if (property.GetCustomAttributes(typeof (ValidationAttribute), true).Any())
            {
                object value = property.GetValue(objectToValidate, null);
                ValidateProperty(property.Name, value);
            }
        }

        return !HasErrors;
    }
}&lt;/pre&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/7efKq0i3Wgs" height="1" width="1"/&gt;</description><pubDate>Tue, 22 Feb 2011 12:42:26 +0100</pubDate><a10:updated>2011-02-22T12:42:26+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/02/22/validating-our-viewmodel</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/io7LMbl6zVg/make-use-of-wcf-faultcontracts-in-silverlight-clients</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Silverlight</category><category>Technology</category><category>WCF</category><category>Used to get articles on www.dotnetmag.nl</category><title>Make use of WCF FaultContracts in Silverlight clients</title><description>&lt;p&gt;I think every Silverlight developer has seen at least once, an exception showing a message &lt;strong&gt;“The remote server returned an error: NotFound”&lt;/strong&gt; while connecting to a WCF Service. Alright, that message could have been a better message, but why are we getting this message?&lt;/p&gt;  &lt;p&gt;Yes, you probably figured that out yourself, something is wrong with your WCF Service, and it’s not a missing WCF Service. Yes it feels something is seriously wrong, why do we get this strange NotFound message?&lt;/p&gt;  &lt;p&gt;If anything goes wrong, the WCF Service returns some data, but also sets the HTTP Status code to 500. The browser HTTP stack doesn’t allow to read the data when the HTTP Status code is 500.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Solution 1:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;There’s an easy solution to solve this: Don’t use the browser HTTP stack but the client HTTP stack instead. Just a matter of adding the below line of code in the Application_Startup method in the App.xaml.cs.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:3220c22f-bda2-4483-99da-0611ec9e0b07" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: false; "&gt;WebRequest.RegisterPrefix(&amp;quot;http://&amp;quot;, WebRequestCreator.ClientHttp);&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Solution 2:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Because sometimes you don’t want to make use of the client HTTP stack but rather like the browser HTTP stack there’s a solution for that as well. If you’re using the browser HTTP stack you’ll get things like &lt;a href="http://mark.mymonster.nl/2009/05/12/silverlight-using-wcf-with-windows-authentication/" target="_blank"&gt;Windows Authentication&lt;/a&gt; and automatic Cookie handling.&lt;/p&gt;

&lt;p&gt;Because of the extreme flexibility of WCF and really a lot of hook-points we can change the behavior of the HTTP Status code in case of errors. There’s a &lt;a href="http://msdn.microsoft.com/en-us/library/dd470096(v=vs.95).aspx" target="_blank"&gt;MSDN article&lt;/a&gt; which explains this in detail. The only real important part is line 18, which changes the Status code to 200 in case of Faults.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:4734cbb1-4e56-45d5-8f13-c1e340ba1db6" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true;  highlight: 18 ;"&gt;public class SilverlightFaultBehavior : BehaviorExtensionElement, IEndpointBehavior
{

   public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
   {
       var inspector = new SilverlightFaultMessageInspector();
       endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
   }

   public class SilverlightFaultMessageInspector : IDispatchMessageInspector
   {

       public void BeforeSendReply(ref Message reply, object correlationState)
       {
           if (reply.IsFault)
           {
               // Here the response code is changed to 200.
               var property = new HttpResponseMessageProperty { StatusCode = System.Net.HttpStatusCode.OK };

               reply.Properties[HttpResponseMessageProperty.Name] = property;
           }
       }

       public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
       {
           // Do nothing to the incoming message.
           return null;
       }


   }

   public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
   {
   }

   public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
   {
   }


   public void Validate(ServiceEndpoint endpoint)
   {
   }

   public override System.Type BehaviorType
   {
       get { return typeof(SilverlightFaultBehavior); }
   }

   protected override object CreateBehavior()
   {
       return new SilverlightFaultBehavior();
   }

}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Of course you need to configure the services to use this behavior.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:1546cee6-ff45-492f-93bb-d44cc91aa9ff" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: xml; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;&amp;lt;system.serviceModel&amp;gt;
	&amp;lt;extensions&amp;gt;
		&amp;lt;behaviorExtensions&amp;gt;
			&amp;lt;add name=&amp;quot;silverlightFaults&amp;quot;
				type=&amp;quot;Silverlight.Poc.SilverlightFaultBehavior, Silverlight.Poc, Version=1.0.0.0, Culture=neutral&amp;quot;/&amp;gt;
		&amp;lt;/behaviorExtensions&amp;gt;
	&amp;lt;/extensions&amp;gt;
	&amp;lt;services&amp;gt;
	...
	&amp;lt;/services&amp;gt;    
	&amp;lt;behaviors&amp;gt;
		&amp;lt;endpointBehaviors&amp;gt;
			&amp;lt;behavior name=&amp;quot;&amp;quot;&amp;gt;
				&amp;lt;silverlightFaults/&amp;gt;
			&amp;lt;/behavior&amp;gt;
		&amp;lt;/endpointBehaviors&amp;gt;
		&amp;lt;serviceBehaviors&amp;gt;
			&amp;lt;behavior name=&amp;quot;&amp;quot;&amp;gt;
				&amp;lt;serviceMetadata httpGetEnabled=&amp;quot;true&amp;quot; /&amp;gt;
				&amp;lt;serviceDebug includeExceptionDetailInFaults=&amp;quot;false&amp;quot; /&amp;gt;
			&amp;lt;/behavior&amp;gt;
		&amp;lt;/serviceBehaviors&amp;gt;
	&amp;lt;/behaviors&amp;gt;
	&amp;lt;serviceHostingEnvironment aspNetCompatibilityEnabled=&amp;quot;true&amp;quot; multipleSiteBindingsEnabled=&amp;quot;true&amp;quot; /&amp;gt;
&amp;lt;/system.serviceModel&amp;gt;
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;font style="background-color: #ffff00"&gt;&lt;/font&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exception details&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next you might actual want to see the details of exceptions that occur in the service on the client. The simple solution is to just allow the service to include the exception details in Faults.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:cec896de-695d-4d7b-bd9c-1e36f713116d" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: xml; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;&amp;lt;serviceDebug includeExceptionDetailInFaults=&amp;quot;true&amp;quot; /&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;You would want to do this in a development and maybe in a test environment, but not for production. In the production environment you’ll only want to provide known faults. Yes in a lot of situations there are known faults which in essence are very similar to application specific exceptions.&lt;/p&gt;

&lt;p&gt;If you want to enable a known Fault on your WCF Service you will need to create a FaultContract and also decorate the ServiceContract with information about what kind of Faults in can expect. Let’s start with a simple FaultContract which is in this case a simple DataContract.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:b31670a5-ce23-48d4-9b8f-85ed98354efc" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;[DataContract]
public class AuthenticationFault
{
   [DataMember]	
   public string Reason { get; set; }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;We decorate the Service with a FaultContract attribute which references the datacontract we created in the previous step.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:d873e39c-8dab-49ec-a6d9-444cbe7bf067" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;[OperationContract]
[FaultContract(typeof(AuthenticationFault))]
List&amp;lt;Package&amp;gt; FindPackages(PackageQuery query);&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Alright we now only need a way to fire a WCF Fault. This is similar to the way we fire normal exceptions, but an instance of the Fault DataContract will be added to the Fault.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:a922f068-bf6c-497e-8e38-453ef8fec1e8" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: false; first-line: 1; tab-size: 4;  toolbar: true; "&gt;throw new FaultException&amp;lt;AuthenticationFault&amp;gt;(new AuthenticationFault(), new FaultReason(&amp;quot;Authentication failed.&amp;quot;));&lt;/pre&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/io7LMbl6zVg" height="1" width="1"/&gt;</description><pubDate>Thu, 10 Feb 2011 20:52:15 +0100</pubDate><a10:updated>2011-02-10T20:52:15+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/02/10/make-use-of-wcf-faultcontracts-in-silverlight-clients</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/lnqxQCyVUd0/how-to-cancel-the-closing-of-your-silverlight-application-in-browser-and-out-of-browser</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Silverlight</category><category>Technology</category><category>Used to get articles on www.dotnetmag.nl</category><title>How to cancel the closing of your Silverlight application (in-browser and out-of-browser)</title><description>&lt;p&gt;It’s almost &lt;a href="http://mark.mymonster.nl/2009/02/28/integration-of-browsers-unloading-with-silverlight/" target="_blank"&gt;two years ago when I wrote about the concept of canceling the the closing of a Silverlight application&lt;/a&gt;. In that era I was only trying to solve the problems that exist inside the browser. Like someone who accidently closes the tab, or types a new url in the tab of the Silverlight application. These things aren’t always a problem, but in Line of Business applications you would at least want to warn the user when he has unsaved data on the screen he’s about to close.&lt;/p&gt;  &lt;p&gt;Nowadays we have Silverlight applications that run both in the browser and out-of-browser on the desktop. Of course some features can be different between the two versions of the application. But my intend is to have at least a feeling that 100% of the features are equal.&lt;/p&gt;  &lt;p&gt;So I want to give my users a warning when they are exiting the application, either in-browser or out-of-browser. Even more, I want the warning to be much similar.&lt;/p&gt;  &lt;p&gt;I want a simple message to be shown automatically. So let’s implement the ICloseHandler&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:14c1c0f2-c1c2-439d-8c88-465e33ba287e" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public interface ICloseHandler
{
    string Message { get; set; }
    void Initialize();
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Out of Browser&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Although it might sound like a difficult task, it isn’t. Implementing a warning on exiting an out of browser app is as simple as listening to the &lt;em&gt;Closing&lt;/em&gt; event of the &lt;em&gt;MainWindow&lt;/em&gt;. In that occasion we simply show a messagebox and depending on the result we cancel the closing. The implementation of the ICloseHandler looks like this.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:d0237eed-fc22-4368-bb33-2bef9604401d" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public class OutOfBrowserCloseHandler : ICloseHandler
{
    #region ICloseHandler Members

    public void Initialize()
    {
        Application.Current.MainWindow.Closing +=
            (s, e) =&amp;gt;
                {
                    MessageBoxResult boxResult = MessageBox.Show(
                        string.Format(
                            @&amp;quot;Are you sure you want to close the application?{1}{1}{0}&amp;quot;,
                            Message, Environment.NewLine),
                        string.Empty,
                        MessageBoxButton.OKCancel);
                    if (boxResult == MessageBoxResult.Cancel)
                        e.Cancel = true;
                };
    }

    public string Message { get; set; }

    #endregion
}
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;The end result looks like this.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2010/06/Handle-the_11A08/2011-01-30_2149.png"&gt;&lt;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="2011-01-30_2149" border="0" alt="2011-01-30_2149" src="http://mark.mymonster.nl/Uploads/2010/06/Handle-the_11A08/2011-01-30_2149_thumb.png" width="435" height="271" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In browser&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Alright, back to the browser. That’s where everything started for &lt;a href="http://weblogs.asp.net/scottgu/archive/2006/12/04/announcing-the-release-of-the-first-wpf-e-ctp.aspx" target="_blank"&gt;WPF/E&lt;/a&gt;, uh Silverlight. Though I wrote about a solution almost two years ago. I improved it a little bit, to make sure the solution isn’t that depended on the html that’s hosting the Silverlight application. During the initialization of the InBrowserCloseHandler the code attaches to the browser event called &lt;em&gt;onbeforeunload,&lt;/em&gt; a piece of javascript will call back to the Silverlight application to get the message. To enable this we decorate a Silverlight method with the &lt;em&gt;ScriptableMember&lt;/em&gt; attribute and we make sure that the InBrowserCloseHandler is registered as &lt;em&gt;ScriptableObject&lt;/em&gt;.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:0890406f-6286-4e4c-8972-67a156b3c0ac" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public class InBrowserCloseHandler : ICloseHandler
{
    private const string ScriptableObjectName = &amp;quot;InBrowserCloseHandler&amp;quot;;

    #region ICloseHandler Members

    public void Initialize()
    {
        HtmlPage.RegisterScriptableObject(ScriptableObjectName, this);
        string pluginName = HtmlPage.Plugin.Parent.Id;

        HtmlPage.Window.Eval(string.Format(
            @&amp;quot;window.onbeforeunload = function () {{
            var slApp = document.getElementById('{0}').getElementsByTagName('object')[0];
            var result = slApp.Content.{1}.OnBeforeUnload();
            if(result.length &amp;gt; 0)
                return result;
            }}&amp;quot;,
            pluginName, ScriptableObjectName)
            );
    }

    public string Message { get; set; }

    #endregion

    [ScriptableMember]
    public string OnBeforeUnload()
    {
        return Message;
    }
}
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The end result looks different for each browser. Below a few shots on the message shown by the browser. I can understand that you would want to be more in control of the look and feel of these messages. But sadly that’s not possible. However you could improve the looks of the out-of-browser message, but as I said before, I want the features between in-browser and out-of-browser to be similar, as much as possible.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2010/06/Handle-the_11A08/2011-01-30_2141.png"&gt;&lt;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="Warning message of closing in Internet Explorer" border="0" alt="Warning message of closing in Internet Explorer" src="http://mark.mymonster.nl/Uploads/2010/06/Handle-the_11A08/2011-01-30_2141_thumb.png" width="490" height="268" /&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2010/06/Handle-the_11A08/2011-01-30_2143.png"&gt;&lt;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="Warning message of closing in Chrome" border="0" alt="Warning message of closing in Chrome" src="http://mark.mymonster.nl/Uploads/2010/06/Handle-the_11A08/2011-01-30_2143_thumb.png" width="435" height="199" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2010/06/Handle-the_11A08/2011-01-30_2145.png"&gt;&lt;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="2011-01-30_2145" border="0" alt="2011-01-30_2145" src="http://mark.mymonster.nl/Uploads/2010/06/Handle-the_11A08/2011-01-30_2145_thumb.png" width="481" height="254" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Combined solution&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Of course I also have a combined solution, that will do the thinking about either serving the in-browser, or out-of-browser implementation.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:99011c9b-3edb-4c67-9949-567bec15be47" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public class PowerfullCloseHandler : ICloseHandler
{
    private readonly ICloseHandler _closeHandler;

    public PowerfullCloseHandler()
    {
        if (!Application.Current.IsRunningOutOfBrowser)
            _closeHandler = new InBrowserCloseHandler();
        else
            _closeHandler = new OutOfBrowserCloseHandler();
    }

    #region ICloseHandler Members

    public string Message
    {
        get { return _closeHandler.Message; }
        set { _closeHandler.Message = value; }
    }

    public void Initialize()
    {
        _closeHandler.Initialize();
    }

    #endregion
}
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Usage&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;And for the people who are interested in how to use it. I did add a field to the App.xaml.cs for the ICloseHandler and initialized everything in the Application_Startup.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:1d5f3027-7a06-42a1-80e7-1131bd63ff17" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;private ICloseHandler _handler;

private void Application_Startup(object sender, StartupEventArgs e)
{
    RootVisual = new MainPage();


    _handler = new PowerfullCloseHandler();
    _handler.Initialize();
    _handler.Message = &amp;quot;Warning you're closing...&amp;quot;;
}&lt;/pre&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/lnqxQCyVUd0" height="1" width="1"/&gt;</description><pubDate>Sun, 30 Jan 2011 22:14:26 +0100</pubDate><a10:updated>2011-01-30T22:14:26+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2011/01/30/how-to-cancel-the-closing-of-your-silverlight-application-in-browser-and-out-of-browser</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/UjRtol2Mimk/solving-3-problems-with-the-shelltileschedule</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Phone</category><category>Silverlight</category><category>Technology</category><category>WP7</category><category>Used to get articles on www.dotnetmag.nl</category><title>Solving 3 problems with the ShellTileSchedule</title><description>&lt;p&gt;Are the problems with the Shell Tile Schedule? Yes there are, at least I’m in the impression that there are some problems. Although we have those problems I really like the ShellTileSchedule because it enables an app to have an updated tile without the requirement to write server-side code to notify the client for a new tile. The smallest schedule that’s supported is 1-hour. In that situation every hour the tile will be updated with a tile located on the web (static url, which can return a dynamic image of course).&lt;/p&gt;  &lt;p&gt;There are three problems I identified so far.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; You can’t get the status of the ShellTileSchedule. Worse, although you started the schedule it might be stopped because for whatever reason (ex. phone is on Airplane mode) the downloading of the tile failed.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;2.&lt;/strong&gt; You have to wait at least 1 hour before the tile is updated for the first time.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; After you stopped the ShellTileSchedule, the tile will be the last downloaded tile forever. It would be better if automatically the original tile (from the .xap package) is put back.&lt;/p&gt;  &lt;p&gt;Combined a diagram to show the problems.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2010/06/Solving-the_C5D5/image.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 10px; 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://mark.mymonster.nl/Uploads/2010/06/Solving-the_C5D5/image_thumb.png" width="477" height="199" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Solution 1 for problem 1&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Alright, we can’t get the status. So what do we do? We store it locally, in the Isolated Storage. I really like the approach that’s explained by &lt;a href="http://dotnetbyexample.blogspot.com/2010/09/extensions-methods-for-tomb-stoning.html" target="_blank"&gt;Joost van Schaik who created some extension methods for storing the settings in the Isolated Storage&lt;/a&gt;. He’s storing and retrieving to the Phone State on the Tomb Stoning events: Activated and Deactivated. I did store and retrieve from Isolated on all events: Activated, Deactivated, Launching and Closing.&lt;/p&gt;  &lt;p&gt;That’s all about making sure we have a status. But still this status won’t be updated when the schedule stopped. The Windows Phone team suggests to start the schedule on every application start. The code of the Application_Launching event in the App.xaml.cs could look like this.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:a0a1a5ef-e0b7-4c4f-adbf-a74d0f4bb7d9" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;private void Application_Launching(object sender, LaunchingEventArgs e)
{
    Settings = this.RetrieveFromIsolatedStorage&amp;lt;SettingsViewModel&amp;gt;() ?? new SettingsViewModel();
    if(Settings.TileUpdatesEnabled)
    {
        new ShellTileSchedule
        {
            Interval = UpdateInterval.EveryHour,
            MaxUpdateCount = 0,
            Recurrence = UpdateRecurrence.Interval,
            RemoteImageUri = new Uri(@&amp;quot;http://mark.mymonster.nl/Uploads/2010/12/servertile.png&amp;quot;),
            StartTime = DateTime.Now
        }.Start();
    }
}
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Joost mentions that the ViewModelBase of MVVM Light isn’t serializable. So I created a basic ViewModelBase that has the functionality that I’m always using in ViewModelBase (RaisePropertyChanged) and decorated it with the DataContract attribute.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:9aa37195-c923-41ea-a359-b8b3d6271c92" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;[DataContract]
public class ViewModelBase : INotifyPropertyChanged
{
    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    protected void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution 2 for problem 2&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Not many people know it’s possible, but &lt;a href="http://blogs.microsoft.nl/blogs/mhoekstra/" target="_blank"&gt;Matthijs Hoekstra from Microsoft&lt;/a&gt; helped me in the direction to solve this problem. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution: &lt;/strong&gt;Send a Push Notification from the phone itself. And afterwards close the channel and start the ShellTileSchedule.&lt;/p&gt;

&lt;p&gt;It’s important that you send the Push Notification before the actual call to the start the ShellTileSchedule because the ShellTileSchedule is a kind of NotificationChannel of which only one can exist.&lt;/p&gt;

&lt;p&gt;A lot of articles have been written already about how to do Push Notifications. After opening a NotificationChannel you will get a url. After that you send some xml to that url. The xml that has to be send looks like this.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:67c3f525-023d-49f5-a42c-b6de0618014b" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: xml; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;?&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;
&amp;lt;wp:Notification xmlns:wp=&amp;quot;WPNotification&amp;quot;&amp;gt;
  &amp;lt;wp:Tile&amp;gt;
    &amp;lt;wp:BackgroundImage&amp;gt;http://someserver/servertile.png&amp;lt;/wp:BackgroundImage&amp;gt;
    &amp;lt;wp:Count&amp;gt;0&amp;lt;/wp:Count&amp;gt;
  &amp;lt;/wp:Tile&amp;gt;
&amp;lt;/wp:Notification&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The setup of the xml in code:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:d6493349-c5d9-4a7e-ad57-71e4c6f61065" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public void SendTile(Uri notificationUrl, string tileUri, int? count, string title, Action onComplete)
{
    var stream = new MemoryStream();
    var settings = new XmlWriterSettings {Indent = true, Encoding = Encoding.UTF8};
    XmlWriter writer = XmlWriter.Create(stream, settings);
    writer.WriteStartDocument();
    writer.WriteStartElement(&amp;quot;wp&amp;quot;, &amp;quot;Notification&amp;quot;, &amp;quot;WPNotification&amp;quot;);
    writer.WriteStartElement(&amp;quot;wp&amp;quot;, &amp;quot;Tile&amp;quot;, &amp;quot;WPNotification&amp;quot;);
    if (!string.IsNullOrEmpty(tileUri))
    {
        writer.WriteStartElement(&amp;quot;wp&amp;quot;, &amp;quot;BackgroundImage&amp;quot;, &amp;quot;WPNotification&amp;quot;);
        writer.WriteValue(tileUri);
        writer.WriteEndElement();
    }
    if (count.HasValue)
    {
        writer.WriteStartElement(&amp;quot;wp&amp;quot;, &amp;quot;Count&amp;quot;, &amp;quot;WPNotification&amp;quot;);
        writer.WriteValue(count.ToString());
        writer.WriteEndElement();
    }
    if (!string.IsNullOrEmpty(title))
    {
        writer.WriteStartElement(&amp;quot;wp&amp;quot;, &amp;quot;Title&amp;quot;, &amp;quot;WPNotification&amp;quot;);
        writer.WriteValue(title);
        writer.WriteEndElement();
    }
    writer.WriteEndElement();
    writer.Close();
    byte[] payload = stream.ToArray();

	...
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;If you take a look at the &lt;a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=ca23285f-bab8-47fa-b364-11553e076a9a" target="_blank"&gt;Windows Phone 7 Training Kit&lt;/a&gt; you will see an example on how to do a Push Notification. It can be used almost one on one in the Windows Phone application itself. I removed some of the code (for the Raw and Toast Notifications) and refactored it to fit my needs.&lt;/p&gt;

&lt;p&gt;So after the setup of the xml, the sending of the xml and setting of the HTTP headers looks like this:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:c528d078-bec4-438d-a8ab-a458b7fdbf6e" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public void SendTile(Uri notificationUrl, string tileUri, int? count, string title, Action onComplete)
{
	...
	
	byte[] payload = stream.ToArray();

    //Check the length of the payload and reject it if too long
    if (payload.Length &amp;gt; MaxPayloadLength)
        throw new ArgumentOutOfRangeException(
            string.Format(&amp;quot;Payload is too long. Maximum payload size shouldn't exceed {0} bytes&amp;quot;,
                            MaxPayloadLength));

    //Create and initialize the request object
    var request = (HttpWebRequest) WebRequest.Create(notificationUrl);
    request.Method = &amp;quot;POST&amp;quot;;
    request.ContentType = &amp;quot;text/xml; charset=utf-8&amp;quot;;
    //request.ContentLength = payload.Length;
    request.Headers[&amp;quot;X-MessageID&amp;quot;] = Guid.NewGuid().ToString();
    request.Headers[&amp;quot;X-NotificationClass&amp;quot;] = 1.ToString();
    request.Headers[&amp;quot;X-WindowsPhone-Target&amp;quot;] = &amp;quot;token&amp;quot;;

    request.BeginGetRequestStream(
        ar =&amp;gt;
            {
                //Once async call returns get the Stream object
                Stream requestStream = request.EndGetRequestStream(ar);

                //and start to write the payload to the stream asynchronously
                requestStream.BeginWrite(
                    payload, 0, payload.Length,
                    iar =&amp;gt;
                        {
                            //When the writing is done, close the stream
                            requestStream.EndWrite(iar);
                            requestStream.Close();

                            //and switch to receiving the response from MPNS
                            request.BeginGetResponse(
                                iarr =&amp;gt;
                                    {
                                        if (onComplete != null)
                                            onComplete();
                                    },
                                null);
                        },
                    null);
            },
        null);
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Of course we shouldn’t forget the important part: Subscribing to the Notification channel. Take special notice to the Thread.Sleep in line 21. This is to make sure that the Tile update is completed before the unbinding, and more starting the ShellTileSchedule.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:2f48cd6c-459d-44fd-9081-bbbee2f1770d" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true;  highlight: 21 ;"&gt;private void UpdateTileBeforeOperation(Uri imageUri, Action onComplete)
{
    HttpNotificationChannel channel = HttpNotificationChannel.Find(&amp;quot;OneTime&amp;quot;);
    if (channel != null)
        channel.Close();
    else
    {
        channel = new HttpNotificationChannel(&amp;quot;OneTime&amp;quot;);
        channel.ChannelUriUpdated +=
            (s, e) =&amp;gt;
                {
                    if (imageUri.IsAbsoluteUri)
                        channel.BindToShellTile(new Collection&amp;lt;Uri&amp;gt; {imageUri});
                    else
                        channel.BindToShellTile();

                    SendTile(e.ChannelUri, imageUri.ToString(), 0, &amp;quot;&amp;quot;,
                                () =&amp;gt;
                                    {
                                        //Give it some time to let the update propagate
                                        Thread.Sleep(
                                            TimeSpan.FromSeconds(1));

                                        channel.UnbindToShellTile();
                                        channel.Close();
                                        //Do the operation
                                        if (onComplete != null)
                                            onComplete();
                                    }
                        );
                };
        channel.Open();
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Solution 3 for problem 3&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The solution for problem 3 is similar to solution 2. But instead of a remote url the url is an relative url, local to the .xap file.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:de30561a-72cf-4ecb-a59b-de6ea1658921" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "&gt;public void Stop(Action onComplete)
{
    UpdateTileBeforeOperation(new Uri(&amp;quot;/Background.png&amp;quot;, UriKind.Relative),
                                () =&amp;gt; { if (onComplete != null) onComplete(); });
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Again it allows you to include an action that will be called upon completion of the Stop method.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Full solution diagram&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Alright, all problems solved. The diagram now looks like this.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mark.mymonster.nl/Uploads/2010/06/Solving-the_C5D5/image_3.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 10px; 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://mark.mymonster.nl/Uploads/2010/06/Solving-the_C5D5/image_thumb_3.png" width="477" height="227" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Of course you want to have the full code for the SmartShellTileSchedule.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:08a6d6c7-8882-4a8a-9aab-ba2d5d5c9071" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true;  collapse: true;"&gt;public class SmartShellTileSchedule
{
    private const int MaxPayloadLength = 1024;

    public UpdateRecurrence Recurrence { get; set; }

    public int MaxUpdateCount { get; set; }

    public DateTime StartTime { get; set; }

    public UpdateInterval Interval { get; set; }

    public Uri RemoteImageUri { get; set; }

    /// &amp;lt;summary&amp;gt;
    /// If the schedule is enabled (store this in application settings) this operation should be 
    /// called upon each application start.
    /// &amp;lt;/summary&amp;gt;
    public void CheckForStart()
    {
        DelegateSchedule().Start();
    }

    /// &amp;lt;summary&amp;gt;
    /// This will enable the schedule and make sure the tile is updated immediately. Don't call 
    /// this operation on each application start.
    /// &amp;lt;/summary&amp;gt;
    public void Start()
    {
        Start(null);
    }

    /// &amp;lt;summary&amp;gt;
    /// This will enable the schedule and make sure the tile is updated immediately. Don't call 
    /// this operation on each application start.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;onComplete&amp;quot;&amp;gt;will be called upon completion&amp;lt;/param&amp;gt;
    public void Start(Action onComplete)
    {
        UpdateTileBeforeOperation(RemoteImageUri, () =&amp;gt;
                                                        {
                                                            CheckForStart();
                                                            if (onComplete != null) onComplete();
                                                        });
    }

    /// &amp;lt;summary&amp;gt;
    /// This will stop the schedule and make sure the tile is replaced with the original logo-tile.
    /// Assumption is that the logo-tile is called &amp;quot;Background.png&amp;quot;
    /// &amp;lt;/summary&amp;gt;
    public void Stop()
    {
        Stop(null);
    }

    /// &amp;lt;summary&amp;gt;
    /// This will stop the schedule and make sure the tile is replaced with the original logo-tile.
    /// Assumption is that the logo-tile is called &amp;quot;Background.png&amp;quot;
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;onComplete&amp;quot;&amp;gt;will be called upon completion&amp;lt;/param&amp;gt;
    public void Stop(Action onComplete)
    {
        UpdateTileBeforeOperation(new Uri(&amp;quot;/Background.png&amp;quot;, UriKind.Relative),
                                    () =&amp;gt; { if (onComplete != null) onComplete(); });
    }

    private void UpdateTileBeforeOperation(Uri imageUri, Action onComplete)
    {
        HttpNotificationChannel channel = HttpNotificationChannel.Find(&amp;quot;OneTime&amp;quot;);
        if (channel != null)
            channel.Close();
        else
        {
            channel = new HttpNotificationChannel(&amp;quot;OneTime&amp;quot;);
            channel.ChannelUriUpdated +=
                (s, e) =&amp;gt;
                    {
                        if (imageUri.IsAbsoluteUri)
                            channel.BindToShellTile(new Collection&amp;lt;Uri&amp;gt; {imageUri});
                        else
                            channel.BindToShellTile();

                        SendTile(e.ChannelUri, imageUri.ToString(), 0, &amp;quot;&amp;quot;,
                                    () =&amp;gt;
                                        {
                                            //Give it some time to let the update propagate
                                            Thread.Sleep(
                                                TimeSpan.FromSeconds(1));

                                            channel.UnbindToShellTile();
                                            channel.Close();
                                            //Do the operation
                                            if (onComplete != null)
                                                onComplete();
                                        }
                            );
                    };
            channel.Open();
        }
    }

    private ShellTileSchedule DelegateSchedule()
    {
        return new ShellTileSchedule
                    {
                        Interval = Interval,
                        MaxUpdateCount = MaxUpdateCount,
                        Recurrence = Recurrence,
                        RemoteImageUri = RemoteImageUri,
                        StartTime = StartTime
                    };
    }

    public void SendTile(Uri notificationUrl, string tileUri, int? count, string title, Action onComplete)
    {
        var stream = new MemoryStream();
        var settings = new XmlWriterSettings {Indent = true, Encoding = Encoding.UTF8};
        XmlWriter writer = XmlWriter.Create(stream, settings);
        writer.WriteStartDocument();
        writer.WriteStartElement(&amp;quot;wp&amp;quot;, &amp;quot;Notification&amp;quot;, &amp;quot;WPNotification&amp;quot;);
        writer.WriteStartElement(&amp;quot;wp&amp;quot;, &amp;quot;Tile&amp;quot;, &amp;quot;WPNotification&amp;quot;);
        if (!string.IsNullOrEmpty(tileUri))
        {
            writer.WriteStartElement(&amp;quot;wp&amp;quot;, &amp;quot;BackgroundImage&amp;quot;, &amp;quot;WPNotification&amp;quot;);
            writer.WriteValue(tileUri);
            writer.WriteEndElement();
        }
        if (count.HasValue)
        {
            writer.WriteStartElement(&amp;quot;wp&amp;quot;, &amp;quot;Count&amp;quot;, &amp;quot;WPNotification&amp;quot;);
            writer.WriteValue(count.ToString());
            writer.WriteEndElement();
        }
        if (!string.IsNullOrEmpty(title))
        {
            writer.WriteStartElement(&amp;quot;wp&amp;quot;, &amp;quot;Title&amp;quot;, &amp;quot;WPNotification&amp;quot;);
            writer.WriteValue(title);
            writer.WriteEndElement();
        }
        writer.WriteEndElement();
        writer.Close();
        byte[] payload = stream.ToArray();

        //Check the length of the payload and reject it if too long
        if (payload.Length &amp;gt; MaxPayloadLength)
            throw new ArgumentOutOfRangeException(
                string.Format(&amp;quot;Payload is too long. Maximum payload size shouldn't exceed {0} bytes&amp;quot;,
                                MaxPayloadLength));

        //Create and initialize the request object
        var request = (HttpWebRequest) WebRequest.Create(notificationUrl);
        request.Method = &amp;quot;POST&amp;quot;;
        request.ContentType = &amp;quot;text/xml; charset=utf-8&amp;quot;;
        //request.ContentLength = payload.Length;
        request.Headers[&amp;quot;X-MessageID&amp;quot;] = Guid.NewGuid().ToString();
        request.Headers[&amp;quot;X-NotificationClass&amp;quot;] = 1.ToString();
        request.Headers[&amp;quot;X-WindowsPhone-Target&amp;quot;] = &amp;quot;token&amp;quot;;

        request.BeginGetRequestStream(
            ar =&amp;gt;
                {
                    //Once async call returns get the Stream object
                    Stream requestStream = request.EndGetRequestStream(ar);

                    //and start to write the payload to the stream asynchronously
                    requestStream.BeginWrite(
                        payload, 0, payload.Length,
                        iar =&amp;gt;
                            {
                                //When the writing is done, close the stream
                                requestStream.EndWrite(iar);
                                requestStream.Close();

                                //and switch to receiving the response from MPNS
                                request.BeginGetResponse(
                                    iarr =&amp;gt;
                                        {
                                            if (onComplete != null)
                                                onComplete();
                                        },
                                    null);
                            },
                        null);
                },
            null);
    }
}
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Additional I also included my SettingsViewModel which is fully bindable.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:862585d2-c3b6-404e-868d-fa0551e45182" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true;  collapse: true;"&gt;[DataContract]
public class SettingsViewModel : ViewModelBase
{
    private ICommand _enforceTileUpdatesState;
    private bool _executing;
    private ICommand _setScheduleIfEnabled;
    private bool _tileUpdatesEnabled;

    [DataMember]
    public bool TileUpdatesEnabled
    {
        get { return _tileUpdatesEnabled; }
        set
        {
            if (value != _tileUpdatesEnabled)
            {
                _tileUpdatesEnabled = value;
                RaisePropertyChanged(&amp;quot;TileUpdatesEnabled&amp;quot;);
            }
        }
    }

    public bool Executing
    {
        get { return _executing; }
        set
        {
            if (value != _executing)
            {
                _executing = value;
                RaisePropertyChanged(&amp;quot;Executing&amp;quot;);
            }
        }
    }

    public ICommand SetScheduleIfEnabled
    {
        get
        {
            if (_setScheduleIfEnabled == null)
            {
                _setScheduleIfEnabled = new RelayCommand(
                    () =&amp;gt;
                        {
                            if (TileUpdatesEnabled)
                            {
                                Executing = true;
                                GetSchedule().CheckForStart();
                                Executing = false;
                            }
                        });
            }
            return _setScheduleIfEnabled;
        }
    }

    public ICommand EnforceTileUpdatesState
    {
        get
        {
            if (_enforceTileUpdatesState == null)
            {
                _enforceTileUpdatesState = new RelayCommand(
                    () =&amp;gt;
                        {
                            if (TileUpdatesEnabled)
                            {
                                Executing = true;
                                GetSchedule().Start(
                                    () =&amp;gt;
                                    Deployment.Current.Dispatcher.
                                        BeginInvoke(() =&amp;gt; Executing = false));
                            }
                            else
                            {
                                Executing = true;
                                GetSchedule().Stop(
                                    () =&amp;gt;
                                    Deployment.Current.Dispatcher.
                                        BeginInvoke(() =&amp;gt; Executing = false));
                            }
                        });
            }
            return _enforceTileUpdatesState;
        }
    }


    private SmartShellTileSchedule GetSchedule()
    {
        return new SmartShellTileSchedule
                    {
                        Interval = UpdateInterval.EveryHour,
                        RemoteImageUri =
                            new Uri(@&amp;quot;http://someserver/servertile.png&amp;quot;),
                        StartTime = DateTime.Now,
                        Recurrence = UpdateRecurrence.Interval
                    };
    }
}
&lt;/pre&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/UjRtol2Mimk" height="1" width="1"/&gt;</description><pubDate>Sun, 19 Dec 2010 21:03:07 +0100</pubDate><a10:updated>2010-12-19T21:03:07+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2010/12/19/solving-3-problems-with-the-shelltileschedule</feedburner:origLink></item><item><link>http://feedproxy.google.com/~r/MarkMonster/~3/nDUEkqTGK2I/trigger-a-storyboard-on-viewmodel-changes</link><a10:author><a10:name>Mark Monster</a10:name></a10:author><category>.NET</category><category>Silverlight</category><category>Technology</category><category>Used to get articles on www.dotnetmag.nl</category><title>Trigger a Storyboard on ViewModel changes</title><description>&lt;p&gt;Interactions based on ViewModel changes are easy as soon as you understand how it works. A lot of people have been hiding and showing elements in the UI based on a boolean in the ViewModel which is converted to fit the &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.uielement.visibility(v=vs.95).aspx" target="_blank"&gt;Visibility property&lt;/a&gt;. Of course they used an &lt;a href="http://jeffhandley.com/archive/2008/10/27/binding-converters---visibilityconverter.aspx" target="_blank"&gt;IValueConverter that translates a bool to a Visibility enum&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;But sometimes designers are tough, they don’t want to show and hide, they want to play a full animation. Of course I know about the ability to trigger a Storyboard by using &lt;a href="http://msdn.microsoft.com/en-us/library/bb979699(v=vs.95).aspx" target="_blank"&gt;EventTriggers (control Loaded or Clicked for example)&lt;/a&gt;. But did you know about the DataTrigger?&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;DataTrigger&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/ff724015(v=Expression.40).aspx" target="_blank"&gt;DataTrigger&lt;/a&gt; comes Expression Blend, you’ll have to reference the Microsoft.Expression.Interactions library, which can be found here: &lt;em&gt;C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Libraries\Microsoft.Expression.Interactions.dll&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;It’s not really that complex to use. If you only want to start a Storyboard when a specific value is put in the bound property the binding looks very much like this.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:b6b58732-899b-49cc-a5f2-03af033aae94" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: xml; gutter: true; first-line: 1; tab-size: 2;  toolbar: true; "&gt;&amp;lt;Grid x:Name=&amp;quot;LoginGrid&amp;quot;&amp;gt;
	&amp;lt;i:Interaction.Triggers&amp;gt;
		&amp;lt;ei:DataTrigger Binding=&amp;quot;{Binding IsLoggedIn}&amp;quot; Value=&amp;quot;true&amp;quot;&amp;gt;
			&amp;lt;ei:ControlStoryboardAction x:Name=&amp;quot;FadeOutOnLogin&amp;quot; Storyboard=&amp;quot;{StaticResource LoginFadeOut}&amp;quot;/&amp;gt;
		&amp;lt;/ei:DataTrigger&amp;gt;
	&amp;lt;/i:Interaction.Triggers&amp;gt;
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Operators&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you have something more specific where you want to use an operator other than equal it will be just a little bit different. The below only starts the storyboard when the value is less than 1.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:e975fb7f-bd7c-4f77-9b19-e08556e5b590" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: xml; gutter: true; first-line: 1; tab-size: 2;  toolbar: true; "&gt;&amp;lt;Grid x:Name=&amp;quot;LoginGrid&amp;quot;&amp;gt;
 	&amp;lt;i:Interaction.Triggers&amp;gt;
 		&amp;lt;ei:DataTrigger Binding=&amp;quot;{Binding IsLoggedIn}&amp;quot; Value=&amp;quot;1&amp;quot; Comparison=&amp;quot;LessThan&amp;quot;&amp;gt;
 			&amp;lt;ei:ControlStoryboardAction x:Name=&amp;quot;FadeOutOnLogin&amp;quot; Storyboard=&amp;quot;{StaticResource LoginFadeOut}&amp;quot;/&amp;gt;
 		&amp;lt;/ei:DataTrigger&amp;gt;
 	&amp;lt;/i:Interaction.Triggers&amp;gt;
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;You can use any of the following operators: &lt;em&gt;Equal, NotEqual, LessThan, LessThanOrEqual, GreaterThan, GreaterThanOrEqual&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Really complex scenario’s&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Alright, it will start to become more complex when you have more than just on condition that needs to be applied. It would be more clear to make use of a &lt;a href="http://msdn.microsoft.com/en-us/library/ff724010(v=Expression.40).aspx" target="_blank"&gt;PropertyChangedTrigger&lt;/a&gt; in that case, and additional set Conditions. The below example gets a trigger if the &lt;em&gt;IsLoggedIn is changed&lt;/em&gt;, and than will apply the conditions, &lt;em&gt;greater than 1&lt;/em&gt; and &lt;em&gt;less than 10&lt;/em&gt; in this example. If the outcome of the conditions is true the Storyboard will start.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:6ca09e6e-aead-4a19-878b-dfe4753ea9ac" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: xml; gutter: true; first-line: 1; tab-size: 2;  toolbar: true; "&gt;&amp;lt;Grid x:Name=&amp;quot;LoginGrid&amp;quot;&amp;gt;
 	&amp;lt;i:Interaction.Triggers&amp;gt;
 		&amp;lt;ei:PropertyChangedTrigger Binding=&amp;quot;{Binding IsLoggedIn}&amp;quot;&amp;gt;
 			&amp;lt;i:Interaction.Behaviors&amp;gt;
 				&amp;lt;ei:ConditionBehavior&amp;gt;
 					&amp;lt;ei:ConditionalExpression&amp;gt;
 						&amp;lt;ei:ComparisonCondition LeftOperand=&amp;quot;{Binding IsLoggedIn}&amp;quot; Operator=&amp;quot;GreaterThan&amp;quot; RightOperand=&amp;quot;1&amp;quot;/&amp;gt;
 						&amp;lt;ei:ComparisonCondition LeftOperand=&amp;quot;{Binding IsLoggedIn}&amp;quot; Operator=&amp;quot;LessThan&amp;quot; RightOperand=&amp;quot;10&amp;quot;/&amp;gt;
 					&amp;lt;/ei:ConditionalExpression&amp;gt;
 				&amp;lt;/ei:ConditionBehavior&amp;gt;
 			&amp;lt;/i:Interaction.Behaviors&amp;gt;
 			&amp;lt;ei:ControlStoryboardAction x:Name=&amp;quot;FadeOutOnLogin&amp;quot; Storyboard=&amp;quot;{StaticResource LoginFadeOut}&amp;quot;/&amp;gt;
 		&amp;lt;/ei:PropertyChangedTrigger&amp;gt;
 	&amp;lt;/i:Interaction.Triggers&amp;gt;
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Doing other things…&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Yes this isn’t limited to the controlling of a storyboard. You can also use the GoToStateAction or any other action, &lt;a href="http://msdn.microsoft.com/en-us/library/ff723923(v=Expression.40).aspx" target="_blank"&gt;mentioned here&lt;/a&gt;. But it’s not limited to built-in actions, you can &lt;a href="http://www.codeproject.com/Articles/42988/Silverlight-Behaviors-and-Triggers-Making-a-Trigge.aspx" target="_blank"&gt;build your own Trigger Action by implementing TriggerAction&amp;lt;T&amp;gt;&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/MarkMonster/~4/nDUEkqTGK2I" height="1" width="1"/&gt;</description><pubDate>Tue, 14 Dec 2010 15:40:41 +0100</pubDate><a10:updated>2010-12-14T15:40:41+01:00</a10:updated><feedburner:origLink>http://mark.mymonster.nl/2010/12/14/trigger-a-storyboard-on-viewmodel-changes</feedburner:origLink></item></channel></rss>

