C# (6)


Counting up to one trillion

How long does it take a computer to count up to one trillion?

This is a question that came after a discussion with a colleague of mine at the university. He was telling me about some company worth over 20 trillion dollars – and he just couldn’t imagine how that much money would look like in cash. Just to get an idea of it we calculated how many hundred dollar bills it would take to circle the Earth once – the answer was I believe around 240.000.000 meaning around 24 billion US dollars. That’s a lot of money. How much would it take a person to count that much money? Well, I can’t say for sure.

What we can do to get an idea is see how much it would take a computer to count up to that value. To simply iterate, no other action in between. For that I’ve wrote a simple piece of code which measures how much it takes to count up to one million and then does some simple math to estimate how much it would take to count up to different values and then displays the results in a friendly way using a method courtesy of StackOverflow.

The results are interesting. And the answer is: it depends on your machine. Even on the same machine you will get different results depending on the load. But let’s look at mine for a bit:

  • one billion (9 zeros) is being reached fast – 15 seconds
  • but to get to one trillion (12 zeros) – the difference is amazing – 4 hours and 10 minutes. Basically 1000 times more.
  • the differences get even more impressive as we go up to quadrillions (15 zeros)  which would take 173 days and then quintillions (18 zeros) which would take 475 years
  • the last one for which I did the math is one sextillion (21 zeros) and get ready – it would take my laptop exactly 7708 years, 292 days, 6 hours, 43 minutes and 52 seconds to iterate up to that value.



Adding speech recognition to your WP8 app

To add speech recognition to our app we will be using the newly released version of the Windows Phone toolkit (release June 2013) – which adds a nice new control called SpeechTextBox (that does exactly what you think). You can get the latest build using NuGet or you can download the source from CodePlex.

Once you’ve referenced the toolkit in you project all you are left to do is add the control:

<toolkit:SpeechTextBox SpeechRecognized="SpeechTextBox_SpeechRecognized" />

Handling the SpeechRecognized event is not necessary. I’ve left it there just to point out that you can choose what you want to do with the speech recognition result. The event comes with a SpeechRecognizedEventArgs parameter which allows you to check the level of confidence for the recognized phrase and also get details about the phrase semantics.




Periodically update your live tiles using ScheduledTaskAgent

I’ve covered in a previous post how to create wide tiles for your Windows Phone 7 application. Now it’s time to bring them to life. The easiest way to do so is by using a ScheduledTaskAgent. To create one go ahead and add a new project to your solution and from the project templates list choose ‘Windows Phone Scheduled Task Agent’.

Before we go any further – go ahead and add this new (task agent) project as a reference in the main application project.

This will create for you a class called ‘ScheduledAgent’ which inherits ‘ScheduledTaskAgent’. You can leave the constructor of the class and the exception handler as they are. The method that interests us is ‘OnInvoke’. This is the method that will be called for us periodically for as long as the agent is running.

This is the method in which we will update our live tile. Let’s say we update our tile from a RSS feed. So the first thing we need to do is download our feed.

protected override void OnInvoke(ScheduledTask task)
{
    WebClient client = new WebClient();
    client.DownloadStringCompleted += (s, e) =&gt;
        {
            DownloadStringCompleted(s, e);
            NotifyComplete();
        };
    client.DownloadStringAsync(new Uri(&quot;http://blogs.windows.com/windows_phone/b/windowsphone/rss.aspx&quot;));
}

Once downloaded, deserialize it, take the first (latest) item and use the title and image to update your live tile.

private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        StringReader stringReader = new StringReader(e.Result);
        XmlReader xmlReader = XmlReader.Create(stringReader);
        SyndicationFeed feed = SyndicationFeed.Load(xmlReader);

        var latestArticle = feed.Items.FirstOrDefault();
        var tile = ShellTile.ActiveTiles.FirstOrDefault();
        if (tile != null)
        {
            var tileData = new FlipTileData();
            tileData.Title = &quot;Windows Phone Blog&quot;;

            var content = latestArticle.Title.Text + &quot; - &quot; + latestArticle.Summary.Text;
            var image = latestArticle.Links.FirstOrDefault(l =&gt; l.MediaType != null &amp;&amp; l.MediaType.Contains(&quot;image&quot;)).Uri;

            tileData.BackContent = content;
            tileData.BackgroundImage = image;

            tileData.WideBackContent = content;
            tileData.WideBackgroundImage = image;
            tile.Update(tileData);
        }
    }
}

Pay attention to where I call NotifyComplete()! This method releases all the resources used by the agent. It is important to call this method because otherwise the task will never end and thus will never start again. It is also very important to call it when everything is done – in this particular case in the DownloadStringCompleted event, after updating the live tiles.

This leaves us with only one thing left to do: registering the scheduled task. We will do this in the Application_Launching event (found in App.xaml.cs).

private void Application_Launching(object sender, LaunchingEventArgs e)
{
    var taskName = &quot;WindowsPhoneBlogSTA&quot;;
    PeriodicTask periodicTask = ScheduledActionService.Find(taskName) as PeriodicTask;
    if (periodicTask != null)
        ScheduledActionService.Remove(taskName);

    periodicTask = new PeriodicTask(taskName) { Description = &quot;Periodic task to update the tile of &lt;your app&gt;.&quot; };
    try
    {
        ScheduledActionService.Add(periodicTask);
        #if DEBUG
            ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(30));
        #endif
    }
    catch (InvalidOperationException) { }
}



Creating wide tiles for your Windows Phone 7 app

I’ve recently come across an article in the Nokia Developer Wiki about creating live tiles (including wide tile) for both Windows Phone 7 and Windows Phone 8 by writing a single piece of code that works in both versions of the OS.

To do this you will need to use the MangoPollo library which you can easily get from NuGet. The library uses reflection to create your live tiles depending on the OS version the app is running in. Creating your tiles is easy:

var tile = ShellTile.ActiveTiles.FirstOrDefault();
if (tile != null)
{
    var tileData = new FlipTileData();
    tileData.Title = "Start Debugging";

    tileData.BackContent = "switch to windows phone, we've got candy";
    tileData.BackgroundImage = new Uri("Assets/tileBackground.png", UriKind.Relative);
    tileData.BackBackgroundImage = new Uri("Assets/tileBackBackground.png", UriKind.Relative);

    tileData.WideBackContent = "switch to windows phone, we've got candy";
    tileData.WideBackgroundImage = new Uri("Assets/wideTileBackground.png", UriKind.Relative);
    tileData.WideBackBackgroundImage = new Uri("Assets/wideTileBackBackground.png", UriKind.Relative);

    tile.Update(tileData);
}

That’s all you need to do. Both the normal and wide live tiles should now be available when resizing the tile of your app. Now all that’s left for you to do is to update it.

Also, one thing that wasn’t so obvious for me – you can use absolute URIs for the tile images. eaning that you can give as a source a image directly from the internet and the OS will download and cache it for you.

tileData.WideBackgroundImage = new Uri("http://cdn.marketplaceimages.windowsphone.com/v8/images/0a539106-8940-4898-99c2-744cbc7a6097?imageType=ws_icon_small", UriKind.Absolute);



Extension Method: Hex To Color

Below you have an extension method that can help you convert any hex color code to a Color object.

public static Color ToColor(this string hexColor)
{
   return Color.FromArgb(
      Convert.ToByte(hexColor.ToString().Substring(1, 2), 16),
      Convert.ToByte(hexColor.ToString().Substring(3, 2), 16),
      Convert.ToByte(hexColor.ToString().Substring(5, 2), 16),
      Convert.ToByte(hexColor.ToString().Substring(7, 2), 16));
}

The method above can only convert 8 characters ARGB color codes.
In order to convert simple RGB codes too we will check for the length of the string (9 = ARGB and 7 = RGB) and in case it’s 7 we will add the alpha to our string as FF ( 255 – opaque) and only then return the color.

public static Color ToColor(this string hexColor)
{
   string tempHexColor = string.Empty;
   if (hexColor.Length == 7)
      tempHexColor = "#FF" + hexColor.Substring(1,6);
   return Color.FromArgb(
      Convert.ToByte(tempHexColor.Substring(1, 2), 16),
      Convert.ToByte(tempHexColor.Substring(3, 2), 16),
      Convert.ToByte(tempHexColor.Substring(5, 2), 16),
      Convert.ToByte(tempHexColor.Substring(7, 2), 16));
}

We should also do something in case the hex color code is not actually a hex color code. So add another if statement after the one we added already and check again for the length of the string; if it’s not equal to 9 then it’s not good so feel free to return any color you want (I will return transparent). The final method looks like this:

public static Color ToColor(this string hexColor)
{
   string tempHexColor = string.Empty;
   if (tempHexColor.Length == 7)
      tempHexColor = "#FF" + hexColor.Substring(1,6);
   if (tempHexColor.Length != 9)
      tempHexColor = "#00000000";
   return Color.FromArgb(
      Convert.ToByte(tempHexColor.Substring(1, 2), 16),
      Convert.ToByte(tempHexColor.Substring(3, 2), 16),
      Convert.ToByte(tempHexColor.Substring(5, 2), 16),
      Convert.ToByte(tempHexColor.Substring(7, 2), 16));
}

How to use it:

string myHexString = "#78196DFD";
Color myColor = new Color();
mycolor = myHexString.ToColor();



Improve productivity by using code snippets

Code snippets are a great way of improving your productivity because they allow you to define pieces of code which you can later on insert into your projects by using a short alias.

Although they’ve been in Visual Studio for quite some time not many people know what they are, what exactly they do and how to use them in their advantage. Hearing about them is one thing, using them it’s another thing. Almost every one of us (those who write code) used them at least once in our lives and the best example I can think of while saying this is: foreach. I mean, how many times have you typed in foreach and then pressed TAB twice for some code to magically appear at your cursor’s location? Yea, that’s a code snippet! And there is a lot more from where that came from. There are code snippets for things like class definition, constructors, destructors, structures, for, do-while, etc. and a complete list (for C#) can be found here: Visual C# Default Code Snippets.

But those are just a small part of what code snippets can offer, those are the default code snippets that come with Visual Studio. The really nice thing about code snippets is that you can define your own and then use them to insert code in your projects wherever and whenever you want.  I will try and create a simple tutorial on how to create your own code snippet sometime next week, until then you can check out this page.

For those of you looking for a couple of general snippets to add to the already existing one, there’s a nice project on codeplex which contains exactly 38 C# code snippets ready to be added to your collection. Adding them to your Visual Studio is easy: just download the zip file from the link mentioned above and extract the file. Then go to Tools -> Code Snippet Manager or press Ctrl + K, Ctrl + B and click on Import. Browse to the folder where you’ve extracted the zip file, select all the code snippets inside the folder and hit Open, then select which folder / category to add them in (My Code Snippets by default) and click finish. And voila! they are ready to be used. To try them out and see if they really work you can try for example typing task or thread somewhere and hitting TAB twice – your code should be automatically inserted.

So, that’s it for now. As I’ve promised, how to create your own code snippets and maybe also something about some snippet designers coming up next week.