Prabhu Kumar

a tech twaddler..

Archive for the ‘Uncategorized’ Category

VSTS Incident Postmorten

without comments

Taylor Lafrinere from our VSTS team published two Root Cause Analyses which are really a good read. Sometime we all hit that one issue which makes you pull your hair out :-) I still remember the caching bug we hit in my previous team, where cache read/write were messing up validity check with dd/mm and mm/dd, maybe I should write about it someday. Here are RCA links,

Preliminary postmortem

Complete postmortem

Written by Prabhu Kumar

March 5th, 2018 at 6:24 pm

Posted in Uncategorized

The case of curious characters

with 2 comments

We stumbled upon an interesting issue the other day at work. A was working on adding search feature to a table/grid of cells, consisting of multiple string and date fields. The implementation used a client side search utility provided by our client SDK, which internally used tries for indexing and searching on string tokens.

The feature was working well overall, but strangely the search was not working on date fields in IE (v11). It worked fine on other browsers. So if you searched for a string like ‘3/23’, it would work in Chrome and Firefox, but not in IE o_O

What is special about these date fields, we wondered, that makes this issue specific to IE? On a closer look, we found that the trie wasn’t getting properly constructed in IE. We jumped into the client SDK code, looked around but did not find anything suspicious, we also tried a bunch of other things like changing system date format, trying to enter date in a string field in another column and searching on it but the results didn’t really provide any clues.

V then stepped in and looked at the part of SDK where the trie was getting built and found that it somehow was failing to add date fields to the index. On debugging further, V found that the date string contained characters we had not expected, it wasn’t a usual string, it had stuff in it that was failing the trie construction.

How were the date fields getting added to the index?

Our implementation was calling toLocaleDateString() on the Date object and passing the string off to the search utility to build the index. It turns out that toLocaleDateString() were returning different values in Chrome vs in IE. Here’s a small piece of code that demonstrates this,

If you run this code in Chrome and IE, this is what you’ll see.




IE (v11)


What? Chrome reports length of the string as 8, which is what you’d expect. IE has got its own characters to the party. Turns out IE adds Left-to-Right markers in the string. The value 0x200E is the unicode code point for Left-to-Right mark. This marker gets added before every token in the date string, thus adding 5 characters to the string length.

The answer on this stackoverflow thread sums up the issue nicely,

Any of the output of toLocaleString, toLocaleDateString, or toLocaleTimeString are meant for human-readable display only

If the intent is anything other than to display to the user, then you should use one of these functions instead:

  • toISOString will give you an ISO8601/RFC3339 formatted timestamp
  • toGMTString or toUTCString will give you an RFC822/RFC1123 formatted timestamp
  • getTime will give you an integer Unix Timestamp with millisecond precision

Written by Prabhu Kumar

April 4th, 2017 at 11:31 pm

Posted in Uncategorized

To patch or not to patch

with 2 comments

I was reading this post on designing rest APIs on, when I remembered an interesting discussion I had had a while ago when working on a feature. Warning: This might be mostly rant.

The feature in discussion here allowed the publisher of an extension to reply to reviews left by users on the extensions product page. The publisher could only create and edit a reply, delete had to be done via a support email to our team, but rest APIs were available to delete a reply that required admin permissions. As you can notice, these nicely fall into crud operations. Now, the reviews feature had already been implemented, modeled using REST. How would you model or design the new reply feature in terms of REST?

Do you consider the reply as a separate resource, and model crud operations on the new resource? Do you expect someone to HTTP GET a reply only? Does a reply make sense without the context of the review? Treat the reply like a sub-resource with its own crud operations?

Or are you the kind that thinks of replies as a property of reviews? A review either has a reply or not. Creating a reply would be like updating the review so you do it via a patch review call. Editing a reply is pretty much same so that too is done via patch. In this case the patch payload has instructions on what to do for the server. If the payload says update-reply, you either create or edit the reply. If the payload says delete-reply then you delete the reply associated with that review. But is this scheme ugly?

If you think of replies as a property, a call to get reviews for a product returns all the reviews and each review object has a reply object if one exists. Do you think getting replies should be optional and done based on a request Param? Something like get /extensions/my-awesome-extension/reviews?filteroption=includeReplies

We went with the latter approach. What are your thoughts on this?

Written by Prabhu Kumar

March 27th, 2017 at 11:22 pm

Posted in Uncategorized

Hello VS!

without comments

After having worked for AppEx (a.k.a Bing Apps or MSN Apps) for over 3 years, it’s time for me to move on. We shipped the MSN Sports app on pretty much every platform over the last few years, and it was fun all along! Met some great folks in the team, made some amazing friends and got to learn a lot from some of the smartest out there. The next chapter begins at Visual Studio Online, with an exciting new project! It’s going to be hardcore tech and I’m really looking forward to all the fun :-)

Also, this blog could use some updates once in a while ;-)

Written by Prabhu Kumar

March 22nd, 2015 at 10:16 pm

Posted in Uncategorized

Learning By Slipping

without comments

Here’s an old, but still relevant, post by Steven Sinofsky on shipping products,

Some excerpts,

“In order to slip you need to know the ship date. When people talk about projects shipping “first quarter” that is about 90 different dates and so that leaves everyone (on the team and elsewhere) guessing what the ship date might be.  A date is a date.  All projects should have a date.  While software itself is not launching to hit a Mars orbit, it is important that everyone agree on a single date.  Whether that date is public or not is a different question.”

“Interestingly, the error rate in short-term, continuous projects can often (in my experience) be much higher.  The view of continuously shipping can lead to a “project” lasting only a month or two.  The brain doesn’t think much of missing by a week or two, but that can be a 25 – 50% error rate.  On a 12 month project that can mean it would stretch to 15-18 months, which does sound like a disaster.”

“When a task cannot be partitioned because of sequential constraints, the application of more effort has no effect on schedule.  The bearing of a child takes nine months, no matter how many women are assigned. The Mythical Man-Month – Frederic P. Brooks

“Quality is the most difficult to manage and why the test leadership is such a critical part of the management structure of any project.  Quality is not something you think about at the end of the project nor is it particularly malleable.  While a great test manager knows quality is not binary at a global level, he/she knows that much like error bars in physics a little bit of sub-par quality across many parts of the project compounds and leads to a highly problematic, or buggy, product.  Quality is not just bugs but also includes scale, performance, reliability, security, and more.”

“Quality is difficult to manage because it is often where people want to cut corners.  A product might work for most cases but the boundary conditions or edge cases show much different results.  As we all know, you only get one chance to make a first impression.”

On the same topic, if you know that you suck at planning and factor this in next time, it might actually prove a little useful ;-)

Written by Prabhu Kumar

February 14th, 2014 at 6:16 pm

Posted in Uncategorized

Get ‘Programming Windows 6th Edition’ by Charles Petzold for $10!

without comments

Programming Windows 6th Edition

O’Reilly has a special offer on the new book that Charles Petzold is working on, Programming Windows 6th Edition. This should be a great book covering Windows 8 app development in C# and XAML.

You can get this book for $10 now (offer lasts till 31st May), and future editions of this book, as and when new chapters are added, will be available to you for free.

Read more at Charles’ blog here:

Shop at:

Written by Prabhu Kumar

May 30th, 2012 at 8:37 pm

Posted in Uncategorized

‘CODE’ by Charles Petzold: An absolute must read

without comments

You know how sometimes you come across a book and you go “I wish I had read this years ago!”. CODE is just that book. It’s a book about how computers work and the way in which Charles Petzold flows through the topics is pure artistry. Those electronics class lessons in college would have been much more interesting if I had read this book then ;)

The book starts off with two best friends trying to communicate from across the street using only flashlights. This is how the idea of ‘code’ is introduced. It then takes you through a journey involving Morse Code, Braille and how telegraphs and relays were used to send codes over long distances. For me, the most interesting part is when he starts building logic gates from relays and switches. This lays a solid foundation for things to come. These logic gates are then used to build half-adders, full-adders (using two half-adders), oscillators, flip-flops and latches; finally getting assembled into a unit of Random Access Memory. Towards the end, a simple computer with processing, input and output systems is designed. The book might be a little old but still very relevant.

The most amazing thing about this book? It teaches you concepts at such a fundamental level that your mind will be blown. And before you know it you will be building ripple counters from flip-flops! If you have anything to do with computers go read this book. You won’t be disappointed.

CODE on flipkart

CODE on Amazon

Written by Prabhu Kumar

November 15th, 2011 at 12:33 am

Posted in Uncategorized

Windows Phone 7: Building a simple dictionary web client

without comments

Like I mentioned in this post a while back, I came across a dictionary web service called Aonaware that serves up word definitions from various dictionaries and is really easy to use. The services page on their website,, lists all the operations that are supported by the dictionary service. Here they are,

Word Dictionary Web Service

The following operations are supported. For a formal definition, please review the Service Description.

  • Define
    Define given word, returning definitions from all dictionaries
  • DefineInDict
    Define given word, returning definitions from specified dictionary
  • DictionaryInfo
    Show information about the specified dictionary
  • DictionaryList
    Returns a list of available dictionaries
  • DictionaryListExtended
    Returns a list of advanced dictionaries (e.g. translating dictionaries)
  • Match
    Look for matching words in all dictionaries using the given strategy
  • MatchInDict
    Look for matching words in the specified dictionary using the given strategy
  • ServerInfo
    Show remote server information
  • StrategyList
    Return list of all available strategies on the server

Follow the links above to get more information on each API.

In this post we will be building a simple windows phone 7 client which uses this service to get word definitions for words entered by the user. The application will also allow the user to select a dictionary from all the available ones and look up the word definition in that dictionary. So of all the apis above we will be using only two, DictionaryList() to get a list of all supported dictionaries and DefineInDict() to get the word definition from a particular dictionary.

Before we get started, a note to you all; I would have liked to implement this application using concepts from data binding, item templates, data templates etc. I have a basic understanding of what they are but, being a beginner, I am not very comfortable with those topics yet so I didn’t use them. I thought I’ll get this version out of the way and maybe in the next version I could give those a try.

A somewhat scary mock-up of the what the final application will look like,


Select Dictionary is a list picker control from the silverlight toolkit (you need to download and install the toolkit if you haven’t already). Below it is a textbox where the user can enter words to look up and a button beside it to fetch the word definition when clicked. Finally we have a textblock which occupies the remaining area and displays the word definition from the selected dictionary.

Create a silverlight application for windows phone 7, AonawareDictionaryClient, and add references to the silverlight toolkit and the web service. From the solution explorer right on References and select Microsoft.Phone.Controls.Toolkit from under the .NET tab,


Next, add a reference to the web service. Again right click on References and this time select Add Service Reference In the resulting dialog paste the service url in the Address field and press go, (url –>


once the service is discovered, provide a name for the NameSpace, in this case I’ve called it AonawareDictionaryService. Press OK. You can now use the classes and functions that are generated in the AonawareDictionaryClient.AonawareDictionaryService namespace.

Let’s get the UI done now. In MainPage.xaml add a namespace declaration to use the toolkit controls,


the content of LayoutRoot is changed as follows, (sorry, no syntax highlighting in this post)

<StackPanel x:Name=”TitlePanel” Grid.Row=”0″ Margin=”12,5,0,5″>
<TextBlock x:Name=”ApplicationTitle” Text=”AONAWARE DICTIONARY CLIENT” Style=”{StaticResource PhoneTextNormalStyle}”/>
<!–<TextBlock x:Name=”PageTitle” Text=”page name” Margin=”9,-7,0,0″ Style=”{StaticResource PhoneTextTitle1Style}”/>–>

<!–ContentPanel – place additional content here–>
<Grid x:Name=”ContentPanel” Grid.Row=”1″ Margin=”12,0,12,0″>
<RowDefinition Height=”Auto”/>
<RowDefinition Height=”Auto”/>
<RowDefinition Height=”*”/>
<toolkit:ListPicker Grid.Row=”0″ x:Name=”listPickerDictionaryList”
Header=”Select Dictionary :”>

<Grid Grid.Row=”1″ Margin=”0,5,0,0″>
<ColumnDefinition Width=”*”/>
<ColumnDefinition Width=”Auto” />

<TextBox x:Name=”txtboxInputWord” Grid.Column=”0″ GotFocus=”OnTextboxInputWordGotFocus” />
<Button x:Name=”btnGo” Grid.Column=”1″ Click=”OnButtonGoClick” >
<Image Source=”/images/button-go.png”/>

<ScrollViewer Grid.Row=”2″ x:Name=”scrollViewer”>
<TextBlock  Margin=”12,5,12,5″  x:Name=”txtBlockWordMeaning” HorizontalAlignment=”Stretch”
VerticalAlignment=”Stretch” TextWrapping=”Wrap”
FontSize=”26″ />

I have commented out the PageTitle as it occupies too much valuable space, and the ContentPanel is changed to contain three rows. First row contains the list picker control, second row contains the textbox and the button, and the third row contains a textblock within a scroll viewer.

The designer will now be showing the final ui,


Now go to MainPage.xaml.cs, and add the following namespace declarations,

using Microsoft.Phone.Controls;
using AonawareDictionaryClient.AonawareDictionaryService;
using System.IO.IsolatedStorage;

A class called DictServiceSoapClient would have been created for you in the background when you added a reference to the web service. This class functions as a wrapper to the services exported by the web service. All the web service functions that we saw at the start can be access through this class, or more precisely through an object of this class.

Create a data member of type DictServiceSoapClient in the Mainpage class, and a function which initializes it,

DictServiceSoapClient DictSvcClient = null;

private DictServiceSoapClient GetDictServiceSoapClient()
if (null == DictSvcClient)
DictSvcClient = new DictServiceSoapClient();

return DictSvcClient;

We have two major tasks remaining. First, when the application loads we need to populate the list picker with all the supported dictionaries and second, when the user enters a word and clicks on the arrow button we need to fetch the word’s meaning.

Populating the List Picker

In the OnNavigatingTo event of the MainPage, we call the DictionaryList() api. This can also be done in the OnLoading event handler of the MainPage; not sure if one has an advantage over the other. Here’s the code for OnNavigatedTo,

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
DictServiceSoapClient client = GetDictServiceSoapClient();

client.DictionaryListCompleted += new EventHandler<DictionaryListCompletedEventArgs>(OnGetDictionaryListCompleted);



Windows Phone 7 supports only async calls to web services. When we added a reference to the dictionary service, asynchronous versions of all the functions were generated automatically. So in the above function we register a handler to the DictionaryListCompleted event which will occur when the call to DictionaryList() gets a response from the server. Then we call the DictionaryListAsync() function which is the async version of the DictionaryList() api. The result of this api will be sent to the handler OnGetDictionaryListCompleted(),

void OnGetDictionaryListCompleted(object sender, DictionaryListCompletedEventArgs e)
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
Dictionary[] listOfDictionaries;

if (e.Error == null)
listOfDictionaries = e.Result;
PopulateListPicker(listOfDictionaries, settings);
else if (settings.Contains(“SavedDictionaryList”))
listOfDictionaries = settings[“SavedDictionaryList”] as Dictionary[];
PopulateListPicker(listOfDictionaries, settings);
MessageBoxResult res = MessageBox.Show(“An error occured while retrieving dictionary list, do you want to try again?”, “Error”, MessageBoxButton.OKCancel);

if (MessageBoxResult.OK == res)


I have used IsolatedStorageSettings to store a few things; the entire dictionary list and the dictionary that is selected when the user exits the application, so that the next time when the user starts the application the current dictionary is set to the last selected value. First we check if the api returned any error, if the error object is null e.Result will contain the list (actually array) of Dictionary type objects. If there was an error, we check the isolated storage settings to see if there is a dictionary list stored from a previous instance of the application and if so, we populate the list picker based on this saved list. Note that in this case there are chances that the dictionary list might be out of date if there have been changes on the server. Finally, if none of these cases are true, we display an error message to the user and try to fetch the list again.

PopulateListPicker() is passed the array of Dictionary objects and the settings object as well,

void PopulateListPicker(Dictionary[] listOfDictionaries, IsolatedStorageSettings settings)

foreach (Dictionary dictionary in listOfDictionaries)

settings[“SavedDictionaryList”] = listOfDictionaries;

string savedDictionaryName;
if (settings.Contains(“SavedDictionary”))
savedDictionaryName = settings[“SavedDictionary”] as string;
savedDictionaryName = “WordNet (r) 2.0”; //default dictionary, wordnet

foreach (string dictName in listPickerDictionaryList.Items)
if (dictName == savedDictionaryName)
listPickerDictionaryList.SelectedItem = dictName;

settings[“SavedDictionary”] = listPickerDictionaryList.SelectedItem as string;

We first clear all the items from the list picker, add the dictionary names from the array and then create a key in the settings called SavedDictionaryList and store the dictionary list in it. We then check if there is saved dictionary available from a previous instance, if there is, we set it as the selected item in the list picker. And if not, we set “WordNet ® 2.0” as the default dictionary. Before returning, we save the selected dictionary in the “SavedDictionary” key of the isolated storage settings.
Fetching word definitions

Getting this part done is very similar to the above code. We get the input word from the textbox, call into DefineInDictAsync() to fetch the definition and when DefineInDictAsync completes, we get the result and display it in the textblock. Here is the handler for the button click,

private void OnButtonGoClick(object sender, RoutedEventArgs e)
txtBlockWordMeaning.Text = “Please wait..”;

IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

if (txtboxInputWord.Text.Trim().Length <= 0)
MessageBox.Show(“Please enter a word in the textbox and press ‘Go'”);
Dictionary[] listOfDictionaries = settings[“SavedDictionaryList”] as Dictionary[];
string selectedDictionary = listPickerDictionaryList.SelectedItem.ToString();

string dictId = “wn”; //default dictionary is wordnet (wn is the dict id)

foreach (Dictionary dict in listOfDictionaries)
if (dict.Name == selectedDictionary)
dictId = dict.Id;

DictServiceSoapClient client = GetDictServiceSoapClient();

client.DefineInDictCompleted += new EventHandler<DefineInDictCompletedEventArgs>(OnDefineInDictCompleted);
client.DefineInDictAsync(dictId, txtboxInputWord.Text.Trim());

We validate the input and then select the dictionary id based on the currently selected dictionary. We need the dictionary id because the api DefineInDict() expects the dictionary identifier and not the dictionary name. We could very well have stored the dictionary id in isolated storage settings too. Again, same as before, we register a event handler for the DefineInDictCompleted event and call the DefineInDictAsync() method passing in the dictionary id and the input word.

void OnDefineInDictCompleted(object sender, DefineInDictCompletedEventArgs e)
WordDefinition wd = e.Result;


if (wd == null || e.Error != null || wd.Definitions.Length == 0)
txtBlockWordMeaning.Text = String.Format(“No definitions were found for ‘{0}’ in ‘{1}'”, txtboxInputWord.Text.Trim(), listPickerDictionaryList.SelectedItem.ToString().Trim());
foreach (Definition def in wd.Definitions)
string str = def.WordDefinition;
str = str.Replace(”  “, ” “); //some formatting
txtBlockWordMeaning.Text = str;

When the api completes, e.Result will contain a WordDefnition object. This class is also generated in the background while adding the service reference. We check the word definitions within this class to see if any results were returned, if not, we display a message to the user in the textblock. If a definition was found the text on the textblock is set to display the definition of the word.

Adding final touches, we now need to save the current dictionary when the application exits. A small but useful thing is selecting the entire word in the input textbox when the user selects it. This makes sure that if the user has looked up a definition for a really long word, he doesn’t have to press ‘clear’ too many times to enter the next word,

protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

settings[“SavedDictionary”] = listPickerDictionaryList.SelectedItem as string;



private void OnTextboxInputWordGotFocus(object sender, RoutedEventArgs e)
TextBox txtbox = sender as TextBox;

if (txtbox.Text.Trim().Length > 0)
txtbox.SelectionStart = 0;
txtbox.SelectionLength = txtbox.Text.Length;

OnNavigatingFrom() is called whenever you navigate away from the MainPage, since our application contains only one page that would mean that it is exiting (or getting tombstoned).

I leave you with a short video of the application in action, but before that if you have any suggestions on how to make the code better and improve it please do leave a comment.

Until next time…

Written by Prabhu Kumar

December 30th, 2010 at 2:33 pm

Posted in Uncategorized

Windows Phone 7 : Dragging and flicking UI controls

with one comment

Who would want to flick and drag UI controls!? There might not be many use cases but I think some concepts here are worthy of a post.

So we will create a simple silverlight application for windows phone 7, containing a canvas element on which we’ll place a button control and an image and then, as the title says, drag and flick the controls. Here’s Mainpage.xaml,

  1. <Grid x:Name=”LayoutRoot” Background=”Transparent”>
  2. <Grid.RowDefinitions>
  3. <RowDefinition Height=”Auto”/>
  4. <RowDefinition Height=”*”/>
  5. </Grid.RowDefinitions>
  6. <!–TitlePanel contains the name of the application and page title–>
  7. <StackPanel x:Name=”TitlePanel” Grid.Row=”0″ Margin=”12,17,0,28″>
  8. <TextBlock x:Name=”ApplicationTitle” Text=”KINETICS” Style=”{StaticResource PhoneTextNormalStyle}”/>
  9. <TextBlock x:Name=”PageTitle” Text=”drag and flick” Margin=”9,-7,0,0″ Style=”{StaticResource PhoneTextTitle1Style}”/>
  10. </StackPanel>
  11. <!–ContentPanel – place additional content here–>
  12. <Grid x:Name=”ContentPanel” Grid.Row=”1″ >
  13. <Canvas x:Name=”MainCanvas” HorizontalAlignment=”Stretch” VerticalAlignment=”Stretch”>
  14. <Canvas.Background>
  15. <LinearGradientBrush StartPoint=”0 0″ EndPoint=”0 1″>
  16. <GradientStop Offset=”0″ Color=”Black”/>
  17. <GradientStop Offset=”1.5″ Color=”BlanchedAlmond”/>
  18. </LinearGradientBrush>
  19. </Canvas.Background>
  20. </Canvas>
  21. </Grid>
  22. </Grid>

the second row in the main grid contains a canvas element, MainCanvas, with its horizontal and vertical alignment set to stretch so that it occupies the entire grid. The canvas background is a linear gradient brush starting with Black and ending with BlanchedAlmond. We’ll add the button and image control to this canvas at run time.

Moving to Mainpage.xaml.cs the Mainpage class contains the following members,

  1. public partial class MainPage : PhoneApplicationPage
  2. {
  3. Button FlickButton;
  4. Image FlickImage;
  5. FrameworkElement ElemToMove = null;
  6. double ElemVelX, ElemVelY;
  7. const double SPEED_FACTOR = 60;
  8. DispatcherTimer timer;

FlickButton and FlickImage are the controls that we’ll add to the canvas. ElemToMove, ElemVelX and ElemVelY will be used by the timer callback to move the ui control. SPEED_FACTOR is used to scale the velocities of ui controls.

Here’s the Mainpage constructor,

  1. // Constructor
  2. public MainPage()
  3. {
  4. InitializeComponent();
  5. AddButtonToCanvas();
  6. AddImageToCanvas();
  7. timer = new DispatcherTimer();
  8. timer.Interval = TimeSpan.FromMilliseconds(35);
  9. timer.Tick += new EventHandler(OnTimerTick);
  10. }

We’ll look at those AddButton and AddImage functions in a moment. The constructor initializes a timer which fires every 35 milliseconds, this timer will be started after the flick gesture completes with some inertia.

Back to AddButton and AddImage functions,

  1. void AddButtonToCanvas()
  2. {
  3. LinearGradientBrush brush;
  4. GradientStop stop1, stop2;
  5. Random rand = new Random(DateTime.Now.Millisecond);
  6. FlickButton = new Button();
  7. FlickButton.Content = “”;
  8. FlickButton.Width = 100;
  9. FlickButton.Height = 100;
  10. brush = new LinearGradientBrush();
  11. brush.StartPoint = new Point(0, 0);
  12. brush.EndPoint = new Point(0, 1);
  13. stop1 = new GradientStop();
  14. stop1.Offset = 0;
  15. stop1.Color = Colors.White;
  16. stop2 = new GradientStop();
  17. stop2.Offset = 1;
  18. stop2.Color = (Application.Current.Resources[“PhoneAccentBrush”] as SolidColorBrush).Color;
  19. brush.GradientStops.Add(stop1);
  20. brush.GradientStops.Add(stop2);
  21. FlickButton.Background = brush;
  22. Canvas.SetTop(FlickButton, rand.Next(0, 400));
  23. Canvas.SetLeft(FlickButton, rand.Next(0, 200));
  24. MainCanvas.Children.Add(FlickButton);
  25. //subscribe to events
  26. FlickButton.ManipulationDelta += new EventHandler<ManipulationDeltaEventArgs>(OnManipulationDelta);
  27. FlickButton.ManipulationCompleted += new EventHandler<ManipulationCompletedEventArgs>(OnManipulationCompleted);
  28. }

this function is basically glorifying a simple task. After creating the button and setting its height and width, its background is set to a linear gradient brush. The direction of the gradient is from top towards bottom and notice that the second stop color is the PhoneAccentColor, which changes along with the theme of the device. The line,

stop2.Color = (Application.Current.Resources[“PhoneAccentBrush”] as SolidColorBrush).Color;

does the magic of extracting the PhoneAccentBrush from application’s resources, getting its color and assigning it to the gradient stop.

AddImage function is straight forward in comparison,

  1. void AddImageToCanvas()
  2. {
  3. Random rand = new Random(DateTime.Now.Millisecond);
  4. FlickImage = new Image();
  5. FlickImage.Source = new BitmapImage(new Uri(“/images/Marble.png”, UriKind.Relative));
  6. Canvas.SetTop(FlickImage, rand.Next(0, 400));
  7. Canvas.SetLeft(FlickImage, rand.Next(0, 200));
  8. MainCanvas.Children.Add(FlickImage);
  9. //subscribe to events
  10. FlickImage.ManipulationDelta += new EventHandler<ManipulationDeltaEventArgs>(OnManipulationDelta);
  11. FlickImage.ManipulationCompleted += new EventHandler<ManipulationCompletedEventArgs>(OnManipulationCompleted);
  12. }

The ManipulationDelta and ManipulationCompleted handlers are same for both the button and the image.

OnManipulationDelta() should look familiar, a similar implementation was used in the previous post,

  1. void OnManipulationDelta(object sender, ManipulationDeltaEventArgs args)
  2. {
  3. FrameworkElement Elem = sender as FrameworkElement;
  4. double Left = Canvas.GetLeft(Elem);
  5. double Top = Canvas.GetTop(Elem);
  6. Left += args.DeltaManipulation.Translation.X;
  7. Top += args.DeltaManipulation.Translation.Y;
  8. //check for bounds
  9. if (Left < 0)
  10. {
  11. Left = 0;
  12. }
  13. else if (Left > (MainCanvas.ActualWidth – Elem.ActualWidth))
  14. {
  15. Left = MainCanvas.ActualWidth – Elem.ActualWidth;
  16. }
  17. if (Top < 0)
  18. {
  19. Top = 0;
  20. }
  21. else if (Top > (MainCanvas.ActualHeight – Elem.ActualHeight))
  22. {
  23. Top = MainCanvas.ActualHeight – Elem.ActualHeight;
  24. }
  25. Canvas.SetLeft(Elem, Left);
  26. Canvas.SetTop(Elem, Top);
  27. }

all it does is calculate the control’s position, check for bounds and then set the top and left of the control.

OnManipulationCompleted() is more interesting because here we need to check if the gesture completed with any inertia and if it did, start the timer and continue to move the ui control until it comes to a halt slowly,

  1. void OnManipulationCompleted(object sender, ManipulationCompletedEventArgs args)
  2. {
  3. FrameworkElement Elem = sender as FrameworkElement;
  4. if (args.IsInertial)
  5. {
  6. ElemToMove = Elem;
  7. Debug.WriteLine(“Linear VelX:{0:0.00}  VelY:{1:0.00}”, args.FinalVelocities.LinearVelocity.X,
  8. args.FinalVelocities.LinearVelocity.Y);
  9. ElemVelX = args.FinalVelocities.LinearVelocity.X / SPEED_FACTOR;
  10. ElemVelY = args.FinalVelocities.LinearVelocity.Y / SPEED_FACTOR;
  11. timer.Start();
  12. }
  13. }

ManipulationCompletedEventArgs contains a member, IsInertial, which is set to true if the manipulation was completed with some inertia. args.FinalVelocities.LinearVelocity.X and .Y will contain the velocities along the X and Y axis. We need to scale down these values so they can be used to increment the ui control’s position sensibly. A reference to the ui control is stored in ElemToMove and the velocities are stored as well, these will be used in the timer callback to access the ui control. And finally, we start the timer.

The timer callback function is as follows,

  1. void OnTimerTick(object sender, EventArgs e)
  2. {
  3. if (null != ElemToMove)
  4. {
  5. double Left, Top;
  6. Left = Canvas.GetLeft(ElemToMove);
  7. Top = Canvas.GetTop(ElemToMove);
  8. Left += ElemVelX;
  9. Top += ElemVelY;
  10. //check for bounds
  11. if (Left < 0)
  12. {
  13. Left = 0;
  14. ElemVelX *= -1;
  15. }
  16. else if (Left > (MainCanvas.ActualWidth – ElemToMove.ActualWidth))
  17. {
  18. Left = MainCanvas.ActualWidth – ElemToMove.ActualWidth;
  19. ElemVelX *= -1;
  20. }
  21. if (Top < 0)
  22. {
  23. Top = 0;
  24. ElemVelY *= -1;
  25. }
  26. else if (Top > (MainCanvas.ActualHeight – ElemToMove.ActualHeight))
  27. {
  28. Top = MainCanvas.ActualHeight – ElemToMove.ActualHeight;
  29. ElemVelY *= -1;
  30. }
  31. Canvas.SetLeft(ElemToMove, Left);
  32. Canvas.SetTop(ElemToMove, Top);
  33. //reduce x,y velocities gradually
  34. ElemVelX *= 0.9;
  35. ElemVelY *= 0.9;
  36. //when velocities become too low, break
  37. if (Math.Abs(ElemVelX) < 1.0 && Math.Abs(ElemVelY) < 1.0)
  38. {
  39. timer.Stop();
  40. ElemToMove = null;
  41. }
  42. }
  43. }

if ElemToMove is not null, we get the top and left values of the control and increment the values with their X and Y velocities. Check for bounds, and if the control goes out of bounds we reverse its velocity. Towards the end, the velocities are reduced by 10% every time the timer callback is called, and if the velocities reach too low values the timer is stopped and ElemToMove is made null.

Here’s a short video of the program, the video is a little dodgy because my display driver refuses to run the animations smoothly. The flicks aren’t always recognised but the program should run well on an actual device (or a pc with better configuration),

You can download the source code from here:

Written by Prabhu Kumar

December 19th, 2010 at 2:35 pm

Posted in Uncategorized

Dictionary Web Service

without comments

Today I came across this web service called aonaware which serves up word definitions from various dictionary databases, so I wrote up a quick windows phone 7 app to check it out and it’s kinda neat.

Here’s a video of the app running on the emulator, I’ll write a post soon.

Written by Prabhu Kumar

November 29th, 2010 at 2:36 pm

Posted in Uncategorized