<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" media="screen" href="/styles/xslt/rss.xslt"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:c9="http://channel9.msdn.com">
<channel>
	<title>Channel 9</title>
    <atom:link rel="self" type="application/rss+xml" href="http://channel9.msdn.com/Niners/Pedro Lamas/Posts/RSS"></atom:link>
    <itunes:summary></itunes:summary>
    <itunes:author>Microsoft</itunes:author>
    <itunes:subtitle></itunes:subtitle>
    <image>
      <url>http://mschnlnine.vo.llnwd.net/d1/Dev/App_Themes/C9/images/feedimage.png</url>
      <title>Channel 9</title>
      <link>http://channel9.msdn.com/Niners/Pedro Lamas/Posts</link>
    </image>
    <itunes:image href=""></itunes:image>
    <itunes:category text="Technology"></itunes:category>
    <description>Channel 9 keeps you up to date with the latest news and behind the scenes info from Microsoft that developers love to keep up with. From LINQ to SilverLight – Watch videos and hear about all the cool technologies coming and the people behind them.</description>
    <link>http://channel9.msdn.com/Niners/Pedro Lamas/Posts</link>
    <language>en</language>
    <pubDate>Wed, 22 May 2013 18:32:11 GMT</pubDate>
    <lastBuildDate>Wed, 22 May 2013 18:32:11 GMT</lastBuildDate>
    <generator>Rev9</generator>
    <c9:totalResults>2</c9:totalResults>
    <c9:pageCount>1</c9:pageCount>
    <c9:pageSize>25</c9:pageSize>
  <item>
      <title>Currency Converter v2 – Now on Caffeine!</title>
      <description><![CDATA[ <p>Taking user feedback about the application into consideration, it’s time to make some improvements! J</p><p>Here are some of the reports we got from the users:</p><ul><li>The application is too slow when exchanging currencies </li><li>It uses too much data traffic/should cache the exchange rates </li><li>It doesn’t work for some currencies </li><li>The results are inaccurate/using out-of-date exchange rates </li></ul><p>So, what we can see from these comments is that we need a better data source, and that we should use some sort of caching mechanism…</p><p>I think I’ll go ahead and put some coffee on to boil!</p><h3>To Bing or not to Bing…</h3><p>The first version of Currency Converter used Bing to make the exchanges, which resulted in some of the reports you read above!</p><p>For this version, however, we decided to use MSN Money because it has more accurate and up-to-date data, and because it works every time no matter the currency!</p><p>MSN Money provides a very nice page on which we can see current currency exchange rates in relation to US Dollars; just open your Internet Explorer 8.0&#43; and navigate to the following URL:</p><p><a href="http://moneycentral.msn.com/investor/market/exchangerates.aspx">http://moneycentral.msn.com/investor/market/exchangerates.aspx</a></p><p><a href="http://files.channel9.msdn.com/wlwimages/1932b237046e4743a4e79e6800c0220f/image%5B5%5D.png"><img title="image" src="http://files.channel9.msdn.com/wlwimages/1932b237046e4743a4e79e6800c0220f/image_thumb%5B3%5D.png" alt="image" width="589" height="442" border="0"></a></p><p>As you can see here, we have all the data we need to convert from X to USD and from USD to X, and we can even convert from X to USD to Y.</p><p>So, why not just get all of this data on a single request, cache it, and use it offline to make the currency exchanges? J</p><p>Like before, we will retrieve the data we require from the page HTML by using Regular Expressions. To do so, open Internet Explorer Developer Tools (press F12), use the “Select element by click” option (Ctrl &#43; B), and click on the “Argentine Peso” text; you’ll get something looking like this:</p><p><a href="http://files.channel9.msdn.com/wlwimages/1932b237046e4743a4e79e6800c0220f/image%5B10%5D.png"><img title="image" src="http://files.channel9.msdn.com/wlwimages/1932b237046e4743a4e79e6800c0220f/image_thumb%5B6%5D.png" alt="image" width="589" height="442" border="0"></a></p><p>Using the information above, we can see a pattern in the code:</p><p><strong>HTML<br></strong><pre class="brush: html">&lt;tr&gt;
    &lt;td&gt;CURRENCY&lt;/td&gt;
    &lt;td style=”text-align:right”&gt;&lt;a SOMETHING&gt;VALUE_IN_USD&lt;/a&gt;&lt;/td&gt;
    &lt;td style=”text-align:right”&gt;&lt;a SOMETHING&gt;VALUE_PER_USD&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;</pre></p><p>Now that we know the pattern, we are now able to build this regular expression:</p><p><strong>C#<br></strong><pre class="brush: csharp">private static Regex _resultRegex = 
    new Regex(&quot;&lt;tr&gt;&lt;td&gt;(?&lt;currency&gt;[^&lt;&gt;]&#43;)&lt;/td&gt;&lt;td style=&quot;&quot;text-align:right&quot;&quot;&gt;.*?&gt;(?&lt;value&gt;[0-9.,]&#43;)&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);</pre></p><p>Applying this Regular Expression to the retrieved HTML will allows us to get every row matching it, and retrieve the Currency Name and the “Per USD” Exchange Rate!</p><h3>Time for some coding</h3><p>Now that we know how to get all the currency rates from a single URL, it’s time to make the necessary changes to our code to accommodate the new data!</p><p>Like the previous article, we will maintain the MVVM pattern, showing the coding from the pattern’s bottom (Model) to the very top (View).</p><h4>The (Re)Model</h4><p>Here are the changes we need to make on our model in order to accommodate the retrieved and cached currency rates:</p><ul><li>Set each currency to save its exchange rate and last update </li><li>Mark the base currency (US Dollar), giving it an exchange rate of 1.0 (trying to convert from USD to USD? Right…) </li><li>Add an “Update Exchange Rates” operation to the service </li></ul><p>And here is the full Model, with the changes in yellow:</p><p><a href="http://files.channel9.msdn.com/wlwimages/1932b237046e4743a4e79e6800c0220f/image%5B13%5D.png"><img title="image" src="http://files.channel9.msdn.com/wlwimages/1932b237046e4743a4e79e6800c0220f/image_thumb%5B7%5D.png" alt="image" width="547" height="402" border="0"></a></p><p><strong>C#<br></strong><pre class="brush: csharp">using System;public interface ICurrencyExchangeService
{
    ICurrency[] Currencies { get; }    ICurrency BaseCurrency { get; }    void ExchangeCurrency(double amount, ICurrency fromCurrency, ICurrency toCurrency, Action&lt;ICurrencyExchangeResult&gt; callback);    void UpdateCachedExchangeRates(Action&lt;CachedExchangeRatesUpdateResult&gt; callback, object state);
}public interface ICurrency
{
    string Name { get; }    double CachedExchangeRate { get; set; }    DateTime CachedExchangeRateUpdatedOn { get; set; }
}public interface ICurrencyExchangeResult
{
    Exception Error { get; }    string ExchangedCurrency { get; }    double ExchangedAmount { get; }
}public interface ICachedExchangeRatesUpdateResult
{
    Exception Error { get; }    object State { get; }
}</pre></p><p>The ICurrencyExchangeService now has a new BaseCurrency property that we will set with the “US Dollar” currency instance, as well as an UpdateCachedExchangeRates method to update all the exchange rates.</p><p>For the ICurrency, we have two new properties: the CachedExchangeRate to store the currency exchange rate value, and the CachedExchangeRateUpdatedOn for the last update date.</p><p>A new interface called ICachedExchangeRatesUpdateResult has been added in order to return any exception thrown by the ICurrencyExchangeService.UpdateCachedExchangeRates method asynchronous execution to the caller.</p><p>Now let’s look at the interface’s implementation:</p><p><a href="http://files.channel9.msdn.com/wlwimages/1932b237046e4743a4e79e6800c0220f/image%5B16%5D.png"><img title="image" src="http://files.channel9.msdn.com/wlwimages/1932b237046e4743a4e79e6800c0220f/image_thumb%5B8%5D.png" alt="image" width="589" height="392" border="0"></a></p><p>The first new thing to take note of is that we now have a CurrencyBase abstract class. From here, we extend the MsnMoneyCurrency class, adding a single Id property to store the numeric Id for the Currency found in MSN Money.</p><p>Next is the MsnMoneyV2CurrencyExchangeService, a direct implementation of the ICurrencyExchangeService.</p><p>Unlike BingCurrencyExchangeService from the previous version, notice that MsnMoneyV2CurrencyExchangeService does not extend the CurrencyExchangeServiceBase, and that it only requests online data in the UpdateCachedExchangeRates method and not on every ExchangeCurrency method call.</p><p>Here is the code for these classes:</p><p><strong>C#<br></strong><pre class="brush: csharp">public class MsnMoneyV2CurrencyExchangeService : ICurrencyExchangeService
{
    private const string MsnMoneyUrl = &quot;<a href="http://moneycentral.msn.com/investor/market/exchangerates.aspx?selRegion=1&amp;selCurrency=1&quot;;">http://moneycentral.msn.com/investor/market/exchangerates.aspx?selRegion=1&amp;selCurrency=1&quot;;</a>    #region Static Globals    private static Regex _resultRegex = new Regex(@&quot;&lt;tr&gt;&lt;td&gt;(?&lt;currency&gt;[^&lt;&gt;]&#43;)&lt;/td&gt;&lt;td style=&quot;&quot;text-align:right&quot;&quot;&gt;.*?&gt;(?&lt;value&gt;[0-9.,]&#43;)&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);    private static ICurrency[] _currencies = new ICurrency[] { 
        //The currencies exposed by MSN Money will go here
    };    #endregion    #region Properties    public ICurrency[] Currencies
    {
        get
        {
            return _currencies;
        }
    }    public ICurrency BaseCurrency { get; protected set; }    #endregion    public MsnMoneyV2CurrencyExchangeService()
    {
        BaseCurrency = Currencies.First(x =&gt; x.Name == &quot;US Dollar&quot;);
    }    public void ExchangeCurrency(double amount, ICurrency fromCurrency, ICurrency toCurrency, bool useCachedExchangeRates, Action&lt;ICurrencyExchangeResult&gt; callback, object state)
    {
        if (useCachedExchangeRates)
        {
            try
            {
                ExchangeCurrency(amount, fromCurrency, toCurrency, callback, state);                return;
            }
            catch
            {
            }
        }        UpdateCachedExchangeRates(result =&gt;
        {
            if (result.Error != null)
            {
                callback(new CurrencyExchangeResult(result.Error, state));                return;
            }            try
            {
                ExchangeCurrency(amount, fromCurrency, toCurrency, callback, state);
            }
            catch (Exception ex)
            {
                callback(new CurrencyExchangeResult(ex, state));
            }
        }, state);
    }    private void ExchangeCurrency(double amount, ICurrency fromCurrency, ICurrency toCurrency, Action&lt;ICurrencyExchangeResult&gt; callback, object state)
    {
        var fromExchangeRate = fromCurrency.CachedExchangeRate;
        var toExchangeRate = toCurrency.CachedExchangeRate;
        var timestamp = DateTime.Now;        if (fromCurrency == BaseCurrency)
            fromExchangeRate = 1.0;
        else
        {
            if (timestamp &gt; fromCurrency.CachedExchangeRateUpdatedOn)
                timestamp = fromCurrency.CachedExchangeRateUpdatedOn;
        }        if (toCurrency == BaseCurrency)
            toExchangeRate = 1.0;
        else
        {
            if (timestamp &gt; toCurrency.CachedExchangeRateUpdatedOn)
                timestamp = toCurrency.CachedExchangeRateUpdatedOn;
        }        if (fromExchangeRate &gt; 0 &amp;&amp; toExchangeRate &gt; 0)
        {
            var exchangedAmount = amount / fromExchangeRate * toExchangeRate;            callback(new CurrencyExchangeResult(toCurrency, exchangedAmount, timestamp, state));
        }
        else
            throw new Exception(&quot;Conversion not returned!&quot;);
    }    public void UpdateCachedExchangeRates(Action&lt;CachedExchangeRatesUpdateResult&gt; callback, object state)
    {
        var request = HttpWebRequest.Create(MsnMoneyUrl);        request.BeginGetResponse(ar =&gt;
        {
            try
            {
                var response = (HttpWebResponse)request.EndGetResponse(ar);                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string responseContent;                    using (var streamReader = new StreamReader(response.GetResponseStream()))
                    {
                        responseContent = streamReader.ReadToEnd();
                    }                    foreach (var match in _resultRegex.Matches(responseContent).Cast&lt;Match&gt;())
                    {
                        var currencyName = match.Groups[&quot;currency&quot;].Value.Trim();                        var currency = Currencies.FirstOrDefault(x =&gt; string.Compare(x.Name, currencyName, StringComparison.InvariantCultureIgnoreCase) == 0);                        if (currency != null)
                        {
                            currency.CachedExchangeRate = double.Parse(match.Groups[&quot;value&quot;].Value, CultureInfo.InvariantCulture);
                            currency.CachedExchangeRateUpdatedOn = DateTime.Now;
                        }
                    }                    callback(new CachedExchangeRatesUpdateResult(ar.AsyncState));
                }
                else
                {
                    throw new Exception(string.Format(&quot;Http Error: ({0}) {1}&quot;,
                        response.StatusCode,
                        response.StatusDescription));
                }
            }
            catch (Exception ex)
            {
                callback(new CachedExchangeRatesUpdateResult(ex, ar.AsyncState));
            }
        }, state);
    }
}</pre></p><p>Here’s how it works: when the ExchangeCurrency method is called, we pass a parameter (useCachedExchangeRates) that instructs the method to use (or not!) the previously cached exchange rates.</p><p>Next, make the exchange operation and return the results. If the operation throws an exception, or if we didn’t allow for cached exchange rates usage, call the UpdateCachedExchangeRates to update the exchange rates and then run the exchange operation with the new data.</p><p>And that’s about it for the Model!</p><h4>The ViewModel</h4><p>We maintained the full ViewModel from the previous version, but added some new functionality to it. Here’s the coding (main changes are in yellow):</p><p><strong>C#<br></strong><pre class="brush: csharp">public class MainViewModel : INotifyPropertyChanged
{
    //Full previous code    #region Properties    [IgnoreDataMember]
    public ICurrencyExchangeResult Result
    {
        get
        {
            return _result;
        }
        protected set
        {
            if (_result == value)
                return;            _result = value;            RaisePropertyChanged(&quot;Result&quot;);
            RaisePropertyChanged(&quot;ExchangedCurrency&quot;);
            RaisePropertyChanged(&quot;ExchangedAmount&quot;);
            RaisePropertyChanged(&quot;ExchangedTimeStamp&quot;);
        }
    }    [IgnoreDataMember]
    public string ExchangedTimeStamp
    {
        get
        {
            if (_result == null)
                return string.Empty;            return string.Format(&quot;Data freshness:\n{0} at {1}&quot;,
                _result.Timestamp.ToShortDateString(),
                _result.Timestamp.ToShortTimeString());
        }
    }    [DataMember]
    public CurrencyCachedExchangeRate[] CurrenciesCachedExchangeRates
    {
        get
        {
            return Currencies
                .Select(x =&gt; new CurrencyCachedExchangeRate()
                {
                    CurrencyIndex = Array.IndexOf(Currencies, x),
                    CachedExchangeRate = x.CachedExchangeRate,
                    CachedExchangeRateUpdatedOn = x.CachedExchangeRateUpdatedOn
                })
                .ToArray();
        }
        set
        {
            foreach (var currencyData in value)
            {
                if (currencyData.CurrencyIndex &gt;= Currencies.Length)
                    continue;                var currency = Currencies[currencyData.CurrencyIndex];                currency.CachedExchangeRate = currencyData.CachedExchangeRate;
                currency.CachedExchangeRateUpdatedOn = currencyData.CachedExchangeRateUpdatedOn;
            }
        }
    }    #endregion    //Full previous code    public void ExchangeCurrency()
    {
        if (Busy)
            return;        BusyMessage = &quot;Exchanging amount...&quot;;        _currencyExchangeService.ExchangeCurrency(_amount, _fromCurrency, _toCurrency, true, CurrencyExchanged, null);
    }    public void UpdateCachedExchangeRates()
    {
        if (Busy)
            return;        BusyMessage = &quot;Updating cached exchange rates...&quot;;        _currencyExchangeService.UpdateCachedExchangeRates(ExchangeRatesUpdated, null);
    }    private void CurrencyExchanged(ICurrencyExchangeResult result)
    {
        InvokeOnUiThread(() =&gt;
        {
            Result = result;            BusyMessage = null;            if (result.Error != null)
            {
                if (System.Diagnostics.Debugger.IsAttached)
                    System.Diagnostics.Debugger.Break();
                else
                    MessageBox.Show(&quot;An error has ocorred!&quot;, &quot;Error&quot;, MessageBoxButton.OK);
            }
        });
    }    private void ExchangeRatesUpdated(ICachedExchangeRatesUpdateResult result)
    {
        InvokeOnUiThread(() =&gt;
        {
            BusyMessage = null;            Save();            if (result.Error != null)
            {
                if (System.Diagnostics.Debugger.IsAttached)
                    System.Diagnostics.Debugger.Break();
                else
                    MessageBox.Show(&quot;An error has ocorred!&quot;, &quot;Error&quot;, MessageBoxButton.OK);
            }
        });
    }    private void InvokeOnUiThread(Action action)
    {
        var dispatcher = System.Windows.Deployment.Current.Dispatcher;        if (dispatcher.CheckAccess())
            action();
        else
            dispatcher.BeginInvoke(action);
    }    #region Auxiliary Classes    public class CurrencyCachedExchangeRate
    {
        [DataMember]
        public int CurrencyIndex { get; set; }        [DataMember]
        public double CachedExchangeRate { get; set; }        [DataMember]
        public DateTime CachedExchangeRateUpdatedOn { get; set; }
    }    #endregion
}</pre></p><p>The first thing you will notice here is a new ExchangedTimeStamp read-only property that feeds the interface with the date string to denote when the used currency data was obtained. The interface is notified that this property value has changed when the Result property value is also changed.</p><p>Further down there’s another new property, CurrenciesCachedExchangeRates, that stores the cached exchange rates. For this to work, we have an auxiliary class called CurrencyCachedExchangeRate that stores the currency index along with the exchange rate as well as the update timestamp.</p><p>The UpdateCachedExchangeRates method allows users to manually force an update over the cached exchange rates.</p><p>The CurrencyExchanged and ExchangeRatesUpdated callbacks use the InvokeOnUiThread method to make sure that their codes run properly on the UI thread.</p><h4>The View</h4><p>Two simple changes have been made in the MainPage.xaml (our main View): an area on the screen has been added to show the exchange operation result timestamp, and a menu option has been added to force a full exchange rate update.</p><p>To make the first change, add a simple TextArea on the bottom StackPanel and bind it to the ExchangedTimeStamp property of the ViewModel:</p><p><strong>XAML<br></strong><pre class="brush: text">&lt;StackPanel x:Name=&quot;ContentPanel&quot; Grid.Row=&quot;1&quot; Margin=&quot;12,0,12,0&quot;&gt;
    &lt;TextBlock Margin=&quot;12,0,0,-5&quot; Style=&quot;{StaticResource PhoneTextSubtleStyle}&quot;&gt;Amount&lt;/TextBlock&gt;
    &lt;TextBox InputScope=&quot;TelephoneNumber&quot; Text=&quot;{Binding Amount, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}&quot; /&gt;
    &lt;TextBlock Margin=&quot;12,10,0,-5&quot; Style=&quot;{StaticResource PhoneTextSubtleStyle}&quot;&gt;From&lt;/TextBlock&gt;
    &lt;toolkit:ListPicker ItemsSource=&quot;{Binding Currencies}&quot; SelectedItem=&quot;{Binding FromCurrency, Mode=TwoWay}&quot; FullModeHeader=&quot;FROM CURRENCY&quot; Style=&quot;{StaticResource CurrencyListPicker}&quot; /&gt;
    &lt;TextBlock Margin=&quot;12,10,0,-5&quot; Style=&quot;{StaticResource PhoneTextSubtleStyle}&quot;&gt;To&lt;/TextBlock&gt;
    &lt;toolkit:ListPicker ItemsSource=&quot;{Binding Currencies}&quot; SelectedItem=&quot;{Binding ToCurrency, Mode=TwoWay}&quot; FullModeHeader=&quot;TO CURRENCY&quot; Style=&quot;{StaticResource CurrencyListPicker}&quot; /&gt;
    &lt;StackPanel&gt;
        &lt;TextBlock Style=&quot;{StaticResource PhoneTextGroupHeaderStyle}&quot; Text=&quot;{Binding ExchangedCurrency}&quot;&gt;&lt;/TextBlock&gt;
        &lt;TextBlock Margin=&quot;25, 0, 0, 0&quot; Style=&quot;{StaticResource PhoneTextTitle1Style}&quot; Text=&quot;{Binding ExchangedAmount}&quot;&gt;&lt;/TextBlock&gt;
        &lt;TextBlock Style=&quot;{StaticResource PhoneTextSubtleStyle}&quot; Text=&quot;{Binding ExchangedTimeStamp}&quot; TextWrapping=&quot;Wrap&quot; TextAlignment=&quot;Right&quot;&gt;&lt;/TextBlock&gt;
    &lt;/StackPanel&gt;
&lt;/StackPanel&gt;</pre></p><p>As for the “update exchange rates” menu option, add a new ApplicationBarMenuItem to the MenuItems collection, set the appropriate text, and add a handler for the click event:</p><p><strong>XAML<br></strong><pre class="brush: text">&lt;phone:PhoneApplicationPage.ApplicationBar&gt;
    &lt;shell:ApplicationBar IsVisible=&quot;True&quot; IsMenuEnabled=&quot;True&quot;&gt;
        &lt;shell:ApplicationBarIconButton IconUri=&quot;/Images/appbar.money.usd.png&quot; Text=&quot;Exchange&quot; Click=&quot;ExchangeIconButton_Click&quot; /&gt;
        &lt;shell:ApplicationBar.MenuItems&gt;
            &lt;shell:ApplicationBarMenuItem Text=&quot;update exchange rates&quot; Click=&quot;UpdateExchangeRatesMenuItem_Click&quot; /&gt;
            &lt;shell:ApplicationBarMenuItem Text=&quot;about&quot; Click=&quot;AboutMenuItem_Click&quot; /&gt;
        &lt;/shell:ApplicationBar.MenuItems&gt;
    &lt;/shell:ApplicationBar&gt;
&lt;/phone:PhoneApplicationPage.ApplicationBar&gt;</pre></p><p>Now, all that is missing is implementing the UpdateExchangeRatesMenuItem_To do so, click the event handler in the MainPage.xaml.cs:</p><p><strong>C#<br></strong><pre class="brush: csharp">private void UpdateExchangeRatesMenuItem_Click(object sender, EventArgs e)
{
    var viewModel = DataContext as MainViewModel;    if (viewModel == null)
        return;    Dispatcher.BeginInvoke(() =&gt;
    {
        viewModel.UpdateCachedExchangeRates();
    });
}</pre></p><h3>Conclusion</h3><p>The bottom line is that your application is as good as the data source you use. By utilizing a new (better) data source, some really simple changes to the code, we now have the Currency Converter—faster than ever!</p><p>And just in time: the coffee is ready!</p><h3>About The Author</h3><p>Pedro Lamas is a Portuguese .Net Senior Developer on Microsoft’s Partner DevScope, where he works with all the cool stuff that Microsoft .Net has to offer its developers!</p><p>He’s also one of the administrators of PocketPT.net, the largest Windows Phone Portuguese community, where his contribution is mostly visible on support for Windows Phone developers, and as a speaker for Windows Phone Development in Microsoft Portugal Events.</p><p>You can read his <a href="http://www.pedrolamas.com">blog</a> or contact him via <a href="http://twitter.com/pedrolamas">twitter</a>!</p> <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/Pedro Lamas/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:f1949595c4fb4be1924f9ed4011b1714">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Currency-Converter-v2--Now-on-Caffeine</comments>
      <itunes:summary> Taking user feedback about the application into consideration, it’s time to make some improvements! J Here are some of the reports we got from the users: The application is too slow when exchanging currencies It uses too much data traffic/should cache the exchange rates It doesn’t work for some currencies The results are inaccurate/using out-of-date exchange rates So, what we can see from these comments is that we need a better data source, and that we should use some sort of caching mechanism… I think I’ll go ahead and put some coffee on to boil! To Bing or not to Bing…The first version of Currency Converter used Bing to make the exchanges, which resulted in some of the reports you read above! For this version, however, we decided to use MSN Money because it has more accurate and up-to-date data, and because it works every time no matter the currency! MSN Money provides a very nice page on which we can see current currency exchange rates in relation to US Dollars; just open your Internet Explorer 8.0&amp;#43; and navigate to the following URL: http://moneycentral.msn.com/investor/market/exchangerates.aspx  As you can see here, we have all the data we need to convert from X to USD and from USD to X, and we can even convert from X to USD to Y. So, why not just get all of this data on a single request, cache it, and use it offline to make the currency exchanges? J Like before, we will retrieve the data we require from the page HTML by using Regular Expressions. To do so, open Internet Explorer Developer Tools (press F12), use the “Select element by click” option (Ctrl &amp;#43; B), and click on the “Argentine Peso” text; you’ll get something looking like this:  Using the information above, we can see a pattern in the code: HTML&amp;lt;tr&amp;gt;
    &amp;lt;td&amp;gt;CURRENCY&amp;lt;/td&amp;gt;
    &amp;lt;td style=”text-align:right”&amp;gt;&amp;lt;a SOMETHING&amp;gt;VALUE_IN_USD&amp;lt;/a&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;td style=”text-align:right”&amp;gt;&amp;lt;a SOMETHING&amp;gt;VALUE_PER_USD&amp;lt;/a&amp;gt;&amp;lt;/td&amp;gt;
&amp;lt;/tr&amp;gt; Now th</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Currency-Converter-v2--Now-on-Caffeine</link>
      <pubDate>Mon, 02 May 2011 12:00:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Currency-Converter-v2--Now-on-Caffeine</guid>
      <media:thumbnail url="http://files.channel9.msdn.com/thumbnail/d2ef20a2-9867-4013-9399-5c9a685add18.png" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://files.channel9.msdn.com/thumbnail/79fa25a3-94ee-45da-a789-4929539801c5.png" height="165" width="220"></media:thumbnail>      
      <dc:creator>Pedro Lamas</dc:creator>
      <itunes:author>Pedro Lamas</itunes:author>
      <slash:comments>6</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Currency-Converter-v2--Now-on-Caffeine/RSS</wfw:commentRss>
      <category>MVVM</category>
      <category>Silveright</category>
      <category>Silverlight</category>
      <category>Web Services</category>
      <category>Windows Phone</category>
      <category>XAML</category>
    </item>
  <item>
      <title>Currency Converter for Windows Phone 7</title>
      <description><![CDATA[ <p>The purpose of this article is to show how you can make your very own, very simple Currency Converter application for Windows Phone 7, using Bing to make all the hard exchanging work!</p><h2><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/conversion_splash.png"><img title="conversion_splash" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/conversion_splash_thumb.png" alt="conversion_splash" width="288" height="480" border="0"></a>Introduction</h2><p>Microsoft has done an absolutely amazing job with the Windows Phone 7, giving each and every one of us all of the necessary tools to make our applications blend nicely on it; and the best part—the tools are, and will always be, free!!! J</p><h2>Using Bing for the currency exchange</h2><p>First let's look at what happens when I open up Bing on my browser, and enter a search query like “1 US Dollar in Euros”:</p><p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image.png"><img title="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_thumb.png" alt="image" width="500" height="375" border="0"></a></p><p>As you can see, Bing correctly understood my query, and knew that I was looking for an exchange rate. Then MSN Money made the exchange and presented the result.</p><p>Also, notice that the address displays as:</p><p>http://www.bing.com/search?q=<strong>1&#43;US&#43;Dollar&#43;in&#43;Euros</strong>&amp;go=&amp;form=QBRE&amp;qs=n&amp;sk=&amp;sc=1-20</p><p>OK, but how can we use this to feed the WP7 application? Call the Internet Explorer Developer Tools (just press F12 on your IE8&#43;) and use the “Select element by click” option (Ctrl &#43; B) to select the result on the page and see its HTML code. The result will look just like this:</p><p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_3.png"><img title="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_thumb_3.png" alt="image" width="500" height="406" border="0"></a></p><p>Now we know how to build the Bing currency exchange search query (using “http://www.bing.com/search?q=<strong>{VALUE}</strong>&#43;<strong>{SOURCE_CURRENCY}</strong>&#43;in&#43;<strong>{DESTINATION_CURRENCY}</strong>&amp;go=&amp;form=QBRE&amp;qs=n&amp;sk=&amp;sc=1-20”) and also how to find the results on the returned HTML (search the “&lt;span class=&quot;sc_bigLine&quot;&gt;<strong>RESULT</strong>&lt;/span&gt;”).</p><p>The final task is selecting that span tag on the full HTML and then extracting the converted amount; for this task, I'll be using the following Regular Expression (using System.Text.RegularExpressions):</p><p><strong>C# <br></strong></p><pre class="csharpcode"><span class="kwrd">static</span> Regex _resultRegex =   <span class="kwrd">new</span> Regex(<span class="str">&quot;&lt;span class=\&quot;sc_bigLine\&quot;&gt;.*? = (?&lt;value&gt;[0-9.,]&#43;).*?&lt;/span&gt;&quot;</span>);</pre><p>&nbsp;</p><p>This expression searches the HTML code for a span with class “sc_bigLine” and inner content matching something like the above example: “1 USD = 0.71270 EUR”.</p><p>The expression also allows me to extract the number after the “=” sign by using Groups[“value&quot;].value property.</p><h2>MVVM is our friend!</h2><p>I'll start by quoting the Wikipedia:</p><p><em>The Model View ViewModel (MVVM) is an architectural pattern used in software engineering (…) is targeted at modern UI development platforms (Windows Presentation Foundation and Silverlight) in which there is a User Experience (UX) developer who has different requirements than a more “traditional” developer (i.e. oriented toward business logic and back end development).</em></p><p>Basically, the point is to clearly separate the user interface from all the business logic and data that our application will use!</p><p>We can summarize the MVVM pattern with this schema:</p><p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_4.png"><img title="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_thumb_4.png" alt="image" width="295" height="290" border="0"></a></p><p>The View is the basic XAML for the user interface (although sometimes it can have a C# file attached to it) that will use Data Binding to read and change properties on the ViewModel, and Actions to invoke the methods.</p><p>The ViewModel is the abstraction of the View and will do all the work for binding the View to the Model, with the necessary data conversion.</p><p>The Model can represent the actual object model instance in a known state, or just a data access layer.</p><p>There is one basic rule in MVVM: don't look up! The Model has no knowledge of either the ViewModel or the View, and the ViewModel has no knowledge of the View.</p><p>This brings a new challenge on how to make the three components talk between themselves, and that's where notifications come along!</p><p>We use notifications to communicate changes from a lower component to an upper one; when the upper component gets notified, it will then query the lower for what changed and act accordingly to the new state!</p><p>You can read more about MVVM throughout the internet, but there is an article by Shawn Wildermuth that's one of the best I've seen; you can read it here: <a href="http://msdn.microsoft.com/en-us/magazine/dd458800.aspx">http://msdn.microsoft.com/enus/magazine/dd458800.aspx</a>.</p><h2>The Model</h2><p>We will start at the very bottom (a.k.a. the Model), and as such I've created the following Interfaces to support our Data Model:</p><p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_5.png"><img title="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_thumb_5.png" alt="image" width="401" height="150" border="0"></a><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_6.png"><img title="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_thumb_6.png" alt="image" width="147" height="115" border="0"></a></p><p><strong>C# <br></strong></p><pre class="csharpcode"><span class="kwrd">using</span> System; <span class="kwrd">public</span> <span class="kwrd">interface</span> ICurrencyExchangeService{    ICurrency[] Currencies { get; }    <span class="kwrd">void</span> ExchangeCurrency(        <span class="kwrd">double</span> amount,         ICurrency fromCurrency,         ICurrency toCurrency,         Action&lt;ICurrencyExchangeResult&gt; callback);} <span class="kwrd">public</span> <span class="kwrd">interface</span> ICurrency{    <span class="kwrd">string</span> Name { get; }} <span class="kwrd">public</span> <span class="kwrd">interface</span> ICurrencyExchangeResult{    Exception Error { get; }    <span class="kwrd">string</span> ExchangedCurrency { get; }    <span class="kwrd">double</span> ExchangedAmount { get; }}</pre><p>&nbsp;</p><p>From these three interfaces, we will extend our Bing Currency Exchange provider:</p><p>The abstract CurrencyExchangeServiceBase class implements the ICurrencyExchangeService.ExchangeCurrency method to do all the asynchronous work required to request data from a webserver and retrieve the resulting HTML; to achieve its goal, the CurrencyExchangeServiceBase has two abstract methods that must be implemented: CreateRequestUrl, to get the request url that will be passed to the WebRequest, and GetResultFromResponseContent, to parse the received HTML and return the exchanged value.</p><p>We then extend the BingCurrencyExchangeService from CurrencyExchangeServiceBase, implementing the CreateRequestUrl and GetResultFromResponseContent required methods and the ICurrencyExchangeService.Currencies property including all currencies supported by this service instance.</p><p>We have also a basic ICurrency interface implementation class called BingCurrency.</p><p>This is the CurrencyExchangeServiceBase abstract class implementation:</p><p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_7.png"><img title="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_thumb_7.png" alt="image" width="454" height="412" border="0"></a></p><p><strong>C#</strong></p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> CurrencyExchangeServiceBase : ICurrencyExchangeService{   <span class="kwrd">public</span> <span class="kwrd">abstract</span> ICurrency[] Currencies { get; }   <span class="kwrd">protected</span> <span class="kwrd">abstract</span> <span class="kwrd">string</span> CreateRequestUrl(        <span class="kwrd">double</span> amount,         ICurrency fromCurrency,         ICurrency toCurrency);   <span class="kwrd">protected</span> <span class="kwrd">abstract</span> <span class="kwrd">double</span>         GetResultFromResponseContent(<span class="kwrd">string</span> responseContent);   <span class="kwrd">public</span> <span class="kwrd">void</span> ExchangeCurrency(        <span class="kwrd">double</span> amount,         ICurrency fromCurrency,         ICurrency toCurrency,         Action&lt;ICurrencyExchangeResult&gt; callback)   {      var url = CreateRequestUrl(amount, fromCurrency, toCurrency);      var request = HttpWebRequest.Create(url);      request.BeginGetResponse(ar =&gt;       {         <span class="kwrd">try</span>         {            var response = (HttpWebResponse)request.EndGetResponse(ar);            <span class="kwrd">if</span> (response.StatusCode == HttpStatusCode.OK)            {               <span class="kwrd">string</span> responseContent;               <span class="kwrd">using</span> (var streamReader =                   <span class="kwrd">new</span> StreamReader(response.GetResponseStream()))               {                  responseContent = streamReader.ReadToEnd();               }               var exchangedCurrency =                   GetResultFromResponseContent(responseContent);               callback(                  <span class="kwrd">new</span> CurrencyExchangeResult(                     toCurrency.Name,                      exchangedCurrency));            }            <span class="kwrd">else</span>            {               <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(                <span class="kwrd">string</span>.Format(<span class="str">&quot;Http Error: ({0}) {1}&quot;</span>,                  response.StatusCode,                  response.StatusDescription));            }         }         <span class="kwrd">catch</span> (Exception ex)         {            callback(<span class="kwrd">new</span> CurrencyExchangeResult(ex));         }      }, <span class="kwrd">null</span>);   }}</pre><p>&nbsp;</p><p>As I said before, this is an abstract class that requires any inheritor to implement the Currencies property as well as the CreateRequestUrl and GetResultFromResponseContent functions—and that's exactly what the BingCurrencyExchangeService class does:</p><p><strong>C# <br></strong></p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> BingCurrencyExchangeService : CurrencyExchangeServiceBase{   <span class="kwrd">private</span> <span class="kwrd">static</span> Regex _resultRegex =       <span class="kwrd">new</span> Regex(<span class="str">&quot;&lt;span class=\&quot;sc_bigLine\&quot;&gt;.*? = (?&lt;value&gt;[0-9.,]&#43;).*?&lt;/span&gt;&quot;</span>);   <span class="kwrd">private</span> <span class="kwrd">static</span> ICurrency[] _currencies = <span class="kwrd">new</span> ICurrency[] {       <span class="kwrd">new</span> BingCurrency(<span class="str">&quot;Euro&quot;</span>),      <span class="kwrd">new</span> BingCurrency(<span class="str">&quot;US Dollar&quot;</span>)      <span class="rem">//all available currencies will go here!</span>   };   <span class="preproc">#endregion</span>   <span class="kwrd">public</span> <span class="kwrd">override</span> ICurrency[] Currencies   {      get      {         <span class="kwrd">return</span> _currencies;      }   }   <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">string</span> CreateRequestUrl(<span class="kwrd">double</span> amount, ICurrency fromCurrency, ICurrency toCurrency)   {      <span class="kwrd">return</span> <span class="kwrd">string</span>.Format(         <span class="str">@&quot;http://www.bing.com/search?q={0}&#43;{1}&#43;in&#43;{2}&amp;scope=web&amp;mkt=en-US&amp;FORM=W0LH&quot;</span>,         amount,         fromCurrency.Name.Replace(<span class="str">&quot; &quot;</span>, <span class="str">&quot;&#43;&quot;</span>),         toCurrency.Name.Replace(<span class="str">&quot; &quot;</span>, <span class="str">&quot;&#43;&quot;</span>));   }   <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">double</span> GetResultFromResponseContent(<span class="kwrd">string</span> responseContent)   {      var match = _resultRegex.Match(responseContent);      <span class="kwrd">if</span> (match.Success)         <span class="kwrd">return</span> <span class="kwrd">double</span>.Parse(            match.Groups[<span class="str">&quot;value&quot;</span>].Value,             CultureInfo.InvariantCulture);      <span class="kwrd">else</span>         <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="str">&quot;Conversion not returned!&quot;</span>);   }}</pre><p>&nbsp;</p><p>As you can see here, the BingCurrencyExchangeService class knows how to build the Bing search url if given the currencies and the value of exchange, and also how to get the converted value out of the response HTML code (notice the usage of our regular expression).</p><h2>The ViewModel</h2><p>The ViewModel has a basic inheritance requirement: using INotifyPropertyChanged to notify the user interface of property value changes.</p><p>Our MainViewModel class will have to expose three base data properties for the user interface controls: FromCurrency, ToCurrency, and Amount.</p><p>All assembled, this is how the ViewModel looks:</p><p><strong>C# <br></strong></p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MainViewModel : INotifyPropertyChanged{   <span class="kwrd">private</span> ICurrencyExchangeService _currencyExchangeService;   <span class="kwrd">private</span> <span class="kwrd">double</span> _amount;   <span class="kwrd">private</span> ICurrency _fromCurrency;   <span class="kwrd">private</span> ICurrency _toCurrency;   <span class="kwrd">public</span> ICurrencyExchangeService CurrencyExchangeService   {      get      {         <span class="kwrd">return</span> _currencyExchangeService;      }      set      {         <span class="kwrd">if</span> (_currencyExchangeService == <span class="kwrd">value</span>)            <span class="kwrd">return</span>;         _currencyExchangeService = <span class="kwrd">value</span>;         _fromCurrency = Currencies.FirstOrDefault(x =&gt; x.Name == <span class="str">&quot;US Dollar&quot;</span>) ?? Currencies[0];         _toCurrency = Currencies.FirstOrDefault(x =&gt; x.Name == <span class="str">&quot;Euro&quot;</span>) ?? Currencies[1];         RaisePropertyChanged(<span class="str">&quot;CurrencyExchangeService&quot;</span>);         RaisePropertyChanged(<span class="str">&quot;Currencies&quot;</span>);      }   }   <span class="kwrd">public</span> ICurrency[] Currencies   {      get      {         <span class="kwrd">return</span> _currencyExchangeService.Currencies;      }   }   <span class="kwrd">public</span> <span class="kwrd">string</span> Amount   {      get      {         <span class="kwrd">return</span> _amount.ToString(<span class="str">&quot;0.00&quot;</span>);      }      set      {         <span class="kwrd">double</span> amount;         <span class="kwrd">if</span> (<span class="kwrd">double</span>.TryParse(<span class="kwrd">value</span>, <span class="kwrd">out</span> amount))         {            <span class="kwrd">if</span> (_amount == amount)               <span class="kwrd">return</span>;            _amount = amount;            RaisePropertyChanged(<span class="str">&quot;Amount&quot;</span>);         }         <span class="kwrd">else</span>            <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="str">&quot;Please enter a valid Amount&quot;</span>);      }   }   <span class="kwrd">public</span> ICurrency FromCurrency   {      get      {         <span class="kwrd">return</span> _fromCurrency;      }      set      {         <span class="kwrd">if</span> (_fromCurrency == <span class="kwrd">value</span>)            <span class="kwrd">return</span>;         _fromCurrency = <span class="kwrd">value</span>;         RaisePropertyChanged(<span class="str">&quot;FromCurrency&quot;</span>);      }   }   <span class="kwrd">public</span> ICurrency ToCurrency   {      get      {         <span class="kwrd">return</span> _toCurrency;      }      set      {         <span class="kwrd">if</span> (_toCurrency == <span class="kwrd">value</span>)            <span class="kwrd">return</span>;         _toCurrency = <span class="kwrd">value</span>;         RaisePropertyChanged(<span class="str">&quot;ToCurrency&quot;</span>);      }   }   <span class="kwrd">public</span> MainViewModel()   {      CurrencyExchangeService = <span class="kwrd">new</span> BingCurrencyExchangeService();      Amount = <span class="str">&quot;100&quot;</span>;   }   <span class="kwrd">public</span> <span class="kwrd">event</span> PropertyChangedEventHandler PropertyChanged;   <span class="kwrd">private</span> <span class="kwrd">void</span> RaisePropertyChanged(<span class="kwrd">string</span> propertyName)   {      <span class="kwrd">if</span> (PropertyChanged != <span class="kwrd">null</span>)         PropertyChanged(<span class="kwrd">this</span>, <span class="kwrd">new</span> PropertyChangedEventArgs(propertyName));   }}</pre><p>&nbsp;</p><p>In order to allow the user to change the FromCurrency and ToCurrency properties, we need to list the available ones; as such, we added a Currencies property to return the ICurrency[] Currencies property of the Model instance.</p><p>On the MainViewModel constructor, set the CurrencyExchangeService property to a new BingCurrencyExchangeService instance, making it retrieve “Euro” and “US Dollar” (if available; if not, get the 1<sup>st</sup> and 2<sup>nd</sup> one instead) as the two default exchange currencies, and then set the Amount property to an initial value of “100.”</p><p>The PropertyChanged event is a basic implementation of the INotifyPropertyChanged interface, with a helper method called RaisePropertyChanged used to invoke the event.</p><p>Now we need to add functionality to request a currency exchange operation and show the results on the user interface:</p><p><strong>C# <br></strong></p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MainViewModel : INotifyPropertyChanged{    <span class="rem">//remaining code...</span>    <span class="kwrd">private</span> ICurrencyExchangeResult _result;    <span class="kwrd">public</span> ICurrencyExchangeResult Result    {        get        {            <span class="kwrd">return</span> _result;        }        <span class="kwrd">protected</span> set        {            <span class="kwrd">if</span> (_result == <span class="kwrd">value</span>)                <span class="kwrd">return</span>;            _result = <span class="kwrd">value</span>;            RaisePropertyChanged(<span class="str">&quot;Result&quot;</span>);            RaisePropertyChanged(<span class="str">&quot;ExchangedCurrency&quot;</span>);            RaisePropertyChanged(<span class="str">&quot;ExchangedAmount&quot;</span>);        }    }    <span class="kwrd">public</span> <span class="kwrd">string</span> ExchangedCurrency    {        get        {            <span class="kwrd">if</span> (_result == <span class="kwrd">null</span>)                <span class="kwrd">return</span> <span class="kwrd">string</span>.Empty;            <span class="kwrd">return</span> _result.ExchangedCurrency;        }    }    <span class="kwrd">public</span> <span class="kwrd">string</span> ExchangedAmount    {        get        {            <span class="kwrd">if</span> (_result == <span class="kwrd">null</span>)                <span class="kwrd">return</span> <span class="kwrd">string</span>.Empty;            <span class="kwrd">return</span> _result.ExchangedAmount.ToString(<span class="str">&quot;N2&quot;</span>);        }    }    <span class="kwrd">public</span> <span class="kwrd">void</span> ExchangeCurrency()    {        _currencyExchangeService.ExchangeCurrency(_amount, _fromCurrency, _toCurrency, CurrencyExchanged);    }    <span class="kwrd">private</span> <span class="kwrd">void</span> CurrencyExchanged(ICurrencyExchangeResult result)    {        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =&gt;        {            Result = result;        });    }}</pre><p>&nbsp;</p><p>The ExchangeCurrency method will be used to request a currency exchange operation on the Model instance, including the entered data. When the operation ends, the CurrencyExchanged method will be invoked and we will then get an ICurrencyExchangeResult instance with the results; this method will be asynchronously called on another thread, so we will need get the current Dispatcher and use it to invoke the changes to the MainViewModel.Result property (so that they are made on the interface thread).</p><p>As the Result property gets changed, it will also make property changed notifications to the ExchangedCurrency and ExchangedAmount properties, allowing the user interface to show the returned values.</p><h2>The View</h2><p>The View that will support our application is really quite simple!</p><p>The basic requirements are two ListPicker controls (these are implemented on the Silverlight Toolkit): one for each Currency (the MainViewModel FromCurrency and ToCurrency properties) and a TextBox for the Amount.</p><p>We also need two more TextAreas to show the currency exchange results (one for the ExchangedCurrency property and the other for the ExchangedAmount property, both from our MainViewModel).</p><p>Using the current MainPage.xaml, start by adding a reference to the Silverlight for Windows Phone Toolkit, like so:</p><p><strong>XAML <br></strong></p><pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">phone:PhoneApplicationPage</span><span class="attr">xmlns:toolkit</span><span class="kwrd">=&quot;clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit&quot;</span>&amp;<span class="attr">lt</span>;!<span class="attr">--remaining</span> <span class="attr">code</span>... <span class="attr">--</span><span class="kwrd">&gt;</span></pre><p>&nbsp;</p><p>Then, I'll change the default ContentPanel control from a Grid to a StackPanel, and add the required controls to edit the Currencies and the entry Value:</p><p><strong>XAML <br></strong></p><pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">StackPanel</span> <span class="attr">x:Name</span><span class="kwrd">=&quot;ContentPanel&quot;</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Margin</span><span class="kwrd">=&quot;12,0&quot;</span><span class="kwrd">&gt;</span>   <span class="kwrd">&lt;</span><span class="html">TextBlock</span>       <span class="attr">Margin</span><span class="kwrd">=&quot;12,0,0,-5&quot;</span>       <span class="attr">Style</span><span class="kwrd">=&quot;{StaticResource PhoneTextSubtleStyle}&quot;</span><span class="kwrd">&gt;</span>      Amount   <span class="kwrd">&lt;/</span><span class="html">TextBlock</span><span class="kwrd">&gt;</span>   <span class="kwrd">&lt;</span><span class="html">TextBox</span>       <span class="attr">InputScope</span><span class="kwrd">=&quot;TelephoneNumber&quot;</span>       <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Amount, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}&quot;</span> <span class="kwrd">/&gt;</span>   <span class="kwrd">&lt;</span><span class="html">TextBlock</span>       <span class="attr">Margin</span><span class="kwrd">=&quot;12,10,0,-5&quot;</span>       <span class="attr">Style</span><span class="kwrd">=&quot;{StaticResource PhoneTextSubtleStyle}&quot;</span><span class="kwrd">&gt;</span>         From   <span class="kwrd">&lt;/</span><span class="html">TextBlock</span><span class="kwrd">&gt;</span>   <span class="kwrd">&lt;</span><span class="html">toolkit:ListPicker</span>       <span class="attr">ItemsSource</span><span class="kwrd">=&quot;{Binding Currencies}&quot;</span>       <span class="attr">SelectedItem</span><span class="kwrd">=&quot;{Binding FromCurrency, Mode=TwoWay}&quot;</span>       <span class="attr">FullModeHeader</span><span class="kwrd">=&quot;FROM CURRENCY&quot;</span>       <span class="attr">Style</span><span class="kwrd">=&quot;{StaticResource CurrencyListPicker}&quot;</span> <span class="kwrd">/&gt;</span>   <span class="kwrd">&lt;</span><span class="html">TextBlock</span>       <span class="attr">Margin</span><span class="kwrd">=&quot;12,10,0,-5&quot;</span>       <span class="attr">Style</span><span class="kwrd">=&quot;{StaticResource PhoneTextSubtleStyle}&quot;</span><span class="kwrd">&gt;</span>      To   <span class="kwrd">&lt;/</span><span class="html">TextBlock</span><span class="kwrd">&gt;</span>   <span class="kwrd">&lt;</span><span class="html">toolkit:ListPicker</span>       <span class="attr">ItemsSource</span><span class="kwrd">=&quot;{Binding Currencies}&quot;</span>       <span class="attr">SelectedItem</span><span class="kwrd">=&quot;{Binding ToCurrency, Mode=TwoWay}&quot;</span>       <span class="attr">FullModeHeader</span><span class="kwrd">=&quot;TO CURRENCY&quot;</span>       <span class="attr">Style</span><span class="kwrd">=&quot;{StaticResource CurrencyListPicker}&quot;</span> <span class="kwrd">/&gt;</span>   <span class="kwrd">&lt;</span><span class="html">StackPanel</span><span class="kwrd">&gt;</span>      <span class="kwrd">&lt;</span><span class="html">TextBlock</span>          <span class="attr">Style</span><span class="kwrd">=&quot;{StaticResource PhoneTextGroupHeaderStyle}&quot;</span>          <span class="attr">Text</span><span class="kwrd">=&quot;{Binding ExchangedCurrency}&quot;</span> <span class="kwrd">/&gt;</span>      <span class="kwrd">&lt;</span><span class="html">TextBlock</span>          <span class="attr">Margin</span><span class="kwrd">=&quot;25, 0, 0, 0&quot;</span>          <span class="attr">Style</span><span class="kwrd">=&quot;{StaticResource PhoneTextTitle1Style}&quot;</span>          <span class="attr">Text</span><span class="kwrd">=&quot;{Binding ExchangedAmount}&quot;</span> <span class="kwrd">/&gt;</span>   <span class="kwrd">&lt;/</span><span class="html">StackPanel</span><span class="kwrd">&gt;</span><span class="kwrd">&lt;/</span><span class="html">StackPanel</span><span class="kwrd">&gt;</span></pre><p>&nbsp;</p><p>Here's how it looks right now:</p><p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_8.png"><img title="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10098706/image_thumb_8.png" alt="image" width="287" height="292" border="0"></a></p><p>Notice the CurrencyListPicker style applied to the two ListPicker controls on the code above? Here it is:</p><p><strong>XAML <br></strong></p><pre class="csharpcode">&lt;phone:PhoneApplicationPage.Resources&gt;   &lt;Style x:Key=<span class="str">&quot;CurrencyListPicker&quot;</span> TargetType=<span class="str">&quot;toolkit:ListPicker&quot;</span>&gt;      &lt;Setter          Property=<span class="str">&quot;DisplayMemberPath&quot;</span>          Value=<span class="str">&quot;Name&quot;</span> /&gt;      &lt;Setter          Property=<span class="str">&quot;CacheMode&quot;</span>          Value=<span class="str">&quot;BitmapCache&quot;</span> /&gt;      &lt;Setter Property=<span class="str">&quot;FullModeItemTemplate&quot;</span>&gt;         &lt;Setter.Value&gt;            &lt;DataTemplate&gt;               &lt;StackPanel                      Orientation=<span class="str">&quot;Horizontal&quot;</span>                      Margin=<span class="str">&quot;16 21 0 20&quot;</span>&gt;                  &lt;TextBlock                      Text=<span class="str">&quot;{Binding Name}&quot;</span>                      FontSize=<span class="str">&quot;43&quot;</span>                      FontFamily=<span class="str">&quot;{StaticResource PhoneFontFamilyLight}&quot;</span>/&gt;               &lt;/StackPanel&gt;            &lt;/DataTemplate&gt;         &lt;/Setter.Value&gt;      &lt;/Setter&gt;   &lt;/Style&gt;&lt;/phone:PhoneApplicationPage.Resources&gt;</pre><p>&nbsp;</p><p>This style sets the initial values of three properties on the ListPickers: the DisplayMemberPath (it will be binded to the ICurrency.Name property), the CacheMode (for optimization only), and, most importantly, the FullModeItemTemplate, which indicates how to show each item when the ListPicker window pops up.</p><p>The next step will be adding the “Exchange” button to the bottom ApplicationBar, like so:</p><p><strong>XAML <br></strong></p><pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">phone:PhoneApplicationPage.ApplicationBar</span><span class="kwrd">&gt;</span>   <span class="kwrd">&lt;</span><span class="html">shell:ApplicationBar</span>       <span class="attr">IsVisible</span><span class="kwrd">=&quot;True&quot;</span>       <span class="attr">IsMenuEnabled</span><span class="kwrd">=&quot;False&quot;</span><span class="kwrd">&gt;</span>      <span class="kwrd">&lt;</span><span class="html">shell:ApplicationBarIconButton</span>          <span class="attr">IconUri</span><span class="kwrd">=&quot;/Images/appbar.money.usd.png&quot;</span>          <span class="attr">Text</span><span class="kwrd">=&quot;Exchange&quot;</span>          <span class="attr">Click</span><span class="kwrd">=&quot;ExchangeIconButton_Click&quot;</span> <span class="kwrd">/&gt;</span>   <span class="kwrd">&lt;/</span><span class="html">shell:ApplicationBar</span><span class="kwrd">&gt;</span><span class="kwrd">&lt;/</span><span class="html">phone:PhoneApplicationPage.ApplicationBar</span><span class="kwrd">&gt;</span> </pre><p>&nbsp;</p><p>Remember to create an Images folder in your project and copy the required “appbar.money.usd.png” image to it (you can find this and other ApplicationBar icons in your “%ProgramFiles%\Microsoft SDKs\Windows Phone\v7.0\Icons\dark”); then, set its “Build” and “Copy to Output Directory” properties to “Content” and “Copy always”, respectively.</p><p>On the MainPage.xaml.cs, we'll add the ExchangeIconButton_Click() method:</p><p><strong>C# <br></strong></p><pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ExchangeIconButton_Click(<span class="kwrd">object</span> sender, EventArgs e){   var viewModel = DataContext <span class="kwrd">as</span> MainViewModel;   <span class="kwrd">if</span> (viewModel == <span class="kwrd">null</span>)      <span class="kwrd">return</span>;   Focus();   Dispatcher.BeginInvoke(() =&gt;   {      <span class="kwrd">if</span> (!NetworkInterface.GetIsNetworkAvailable())      {         MessageBox.Show(            <span class="str">&quot;No network connection found!&quot;</span>,             <span class="str">&quot;Error&quot;</span>,             MessageBoxButton.OK);         <span class="kwrd">return</span>;      }      viewModel.ExchangeCurrency();   });}</pre><p>&nbsp;</p><p>This method will check for a valid MainViewModel set on the DataContext, remove the Focus from any TextBox (thus hiding the on-screen keyboard), check if there is a valid network connection, and then call the MainViewModel.ExchangeCurrency() method.</p><h2>Tombstoning</h2><p>The final piece to developing this into the perfect Windows Phone 7 application is making it “Tombstoning” aware!</p><p>Since WP7 doesn't allow multitasking, every time an application is deactivated or closed you should save its state and then restore it when the application is reactivated or reopened; this process is called “Tombstoning.”</p><p>To do this, we use the System.Runtime.Serialization classes, namely, the DataMemberAttribute to mark all the properties of the MainViewModel we want to save (FromCurrency, ToCurrency, and Amount), and the IgnoreDataMemberAttribute to mark the ones we don't (CurrencyExchangeService, Currencies, Result, ExchangedCurrency, and ExchangedAmount).</p><p>We can't (or at least, shouldn't!) directly save the state of the FromCurrency and ToCurrency properties because they have complex values (rather than a base type like Int or String), so we mark these with the IgnoreDataMemberAttribute and add two new properties, one for each, that will get/set the relative index of the Currencies array:</p><p><strong>C# <br></strong></p><pre class="csharpcode">[DataMember] <span class="kwrd">public</span> <span class="kwrd">int</span> FromCurrencyIndex{    get    {        <span class="kwrd">return</span> Array.IndexOf(Currencies, FromCurrency);    }    set    {        FromCurrency = Currencies[<span class="kwrd">value</span>];    }}[DataMember] <span class="kwrd">public</span> <span class="kwrd">int</span> ToCurrencyIndex{    get    {        <span class="kwrd">return</span> Array.IndexOf(Currencies, ToCurrency);    }    set    {        ToCurrency = Currencies[<span class="kwrd">value</span>];    }}</pre><p>&nbsp;</p><p>Now add the methods to Load and Save the state of the MainViewModel instance; since the Save method has to be called on the App.xaml.cs Application_Deactivated() and Application_Closing() events, the best way is to make our View Model a singleton. To do this, add the following code to the MainViewModel class:</p><p><strong>C# <br></strong></p><pre class="csharpcode">[IgnoreDataMember] <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> SettingFileName = <span class="str">&quot;mainviewmodel.dat&quot;</span>; <span class="kwrd">public</span> <span class="kwrd">static</span> MainViewModel Instance { get; <span class="kwrd">protected</span> set; } <span class="kwrd">static</span> MainViewModel(){    Instance = Load();} <span class="kwrd">public</span> <span class="kwrd">static</span> MainViewModel Load(){    <span class="kwrd">return</span> StorageHelper.LoadContract&lt;MainViewModel&gt;(SettingFileName, <span class="kwrd">true</span>);} <span class="kwrd">public</span> <span class="kwrd">void</span> Save(){    StorageHelper.SaveContract(SettingFileName, <span class="kwrd">this</span>, <span class="kwrd">true</span>);}</pre><p>&nbsp;</p><p>The StorageHelper class you see here is just a helper used to serialize and deserialize a file on the application's IsolatedStorage.</p><p>Now all we have to do is change the MainPage.xaml.cs constructor so it uses the singleton instead of creating a new MainViewModel instance:</p><p><strong>C# <br></strong></p><pre class="csharpcode"><span class="kwrd">public</span> MainPage(){    InitializeComponent();    <span class="kwrd">this</span>.DataContext = MainViewModel.Instance;}</pre><p>&nbsp;</p><p>Finally, invoke the Save method on the two required events of the App.xaml.cs file:</p><p><strong>C# <br></strong></p><pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> Application_Deactivated(<span class="kwrd">object</span> sender, DeactivatedEventArgs e){    MainViewModel.Instance.Save();} <span class="kwrd">private</span> <span class="kwrd">void</span> Application_Closing(<span class="kwrd">object</span> sender, ClosingEventArgs e){    MainViewModel.Instance.Save();}</pre><p>&nbsp;</p><p>And that is it! To test the application, open it, press the windows key so that the Windows Phone main screen appears, wait a couple of seconds, and press the back key to return to the application: you will see a “resuming” message appear when the application state restores!</p><p>The application can now be Tombstoned anytime, and when it gets opened again, it will appear as if it never closed!</p><h2>Conclusion</h2><p>As you see here, you can build simple applications for Windows Phone 7 by using basic MVVM architecture, and still have time to go out and have a coffee with your friends!</p><p>Remember: If you want to try this out, the download link for the source code is at the top of the article!</p><p>The sample code uses the BingCurrencyExchangeService, but it also has a second provider for MSN Money, the MsnMoneyCurrencyExchangeService, which you can check out!</p><h2>About The Author</h2><p>Pedro Lamas is a Portuguese .Net Senior Developer on Microsoft's Partner DevScope, where he works with all the cool stuff that Microsoft .Net has to offer its developers!</p><p>He's also one of the administrators of PocketPT.net, the largest Windows Phone Portuguese community, where his contribution is mostly visible on support for Windows Phone developers, and as a speaker for Windows Phone Development in Microsoft Portugal Events.</p><p>You can read his <a href="http://www.pedrolamas.com">blog</a> or contact him via <a href="http://twitter.com/pedrolamas">twitter</a>!</p> <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/Pedro Lamas/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:c06ad9bf51dc4c27a50c9e7600c7076d">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Currency-Converter-for-Windows-Phone-7</comments>
      <itunes:summary> The purpose of this article is to show how you can make your very own, very simple Currency Converter application for Windows Phone 7, using Bing to make all the hard exchanging work! IntroductionMicrosoft has done an absolutely amazing job with the Windows Phone 7, giving each and every one of us all of the necessary tools to make our applications blend nicely on it; and the best part—the tools are, and will always be, free!!! J Using Bing for the currency exchangeFirst let&#39;s look at what happens when I open up Bing on my browser, and enter a search query like “1 US Dollar in Euros”:  As you can see, Bing correctly understood my query, and knew that I was looking for an exchange rate. Then MSN Money made the exchange and presented the result. Also, notice that the address displays as: http://www.bing.com/search?q=1&amp;#43;US&amp;#43;Dollar&amp;#43;in&amp;#43;Euros&amp;amp;go=&amp;amp;form=QBRE&amp;amp;qs=n&amp;amp;sk=&amp;amp;sc=1-20 OK, but how can we use this to feed the WP7 application? Call the Internet Explorer Developer Tools (just press F12 on your IE8&amp;#43;) and use the “Select element by click” option (Ctrl &amp;#43; B) to select the result on the page and see its HTML code. The result will look just like this:  Now we know how to build the Bing currency exchange search query (using “http://www.bing.com/search?q={VALUE}&amp;#43;{SOURCE_CURRENCY}&amp;#43;in&amp;#43;{DESTINATION_CURRENCY}&amp;amp;go=&amp;amp;form=QBRE&amp;amp;qs=n&amp;amp;sk=&amp;amp;sc=1-20”) and also how to find the results on the returned HTML (search the “&amp;lt;span class=&amp;quot;sc_bigLine&amp;quot;&amp;gt;RESULT&amp;lt;/span&amp;gt;”). The final task is selecting that span tag on the full HTML and then extracting the converted amount; for this task, I&#39;ll be using the following Regular Expression (using System.Text.RegularExpressions): C#  static Regex _resultRegex =   new Regex(&amp;quot;&amp;lt;span class=\&amp;quot;sc_bigLine\&amp;quot;&amp;gt;.*? = (?&amp;lt;value&amp;gt;[0-9.,]&amp;#43;).*?&amp;lt;/span&amp;gt;&amp;quot;);&amp;nbsp; This expression searches the HTML code for a span with class “sc_bigLine” and inner co</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Currency-Converter-for-Windows-Phone-7</link>
      <pubDate>Tue, 30 Nov 2010 23:51:54 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Currency-Converter-for-Windows-Phone-7</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/10098706_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/10098706_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Pedro Lamas</dc:creator>
      <itunes:author>Pedro Lamas</itunes:author>
      <slash:comments>8</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Currency-Converter-for-Windows-Phone-7/RSS</wfw:commentRss>
      <category>MVVM</category>
      <category>Silverlight</category>
      <category>Web Services</category>
      <category>XAML</category>
    </item>    
</channel>
</rss>