Monitor network connectivity in WP7 apps

Fri, May 27, 2011, 04:32 PM under MobileAndEmbedded

Most interesting Windows Phone apps rely on some network service for their functionality. So at some point in your app you may need to know programmatically if there is network connection available or not.

For example, the Translator by Moth app relies on the Bing Translation service for translations. When a request for translation (text or voice) is made, the network call may fail. The failure reason is not evident from any of the return results, so I check the connection to see if it is present. Dependent on that, a different message is shown to the user. Before the translation phase is even reached, at the app start up time the Bing service is queried for its list of  languages; in that case I don't want to show the user a message and instead want to be notified when the network is available in order to send the query out again.

So for those two requirements (which I imagine are common in other apps) I wrote a simple wrapper MyNetwork static class to the framework APIs:

  1. Call once MyNetwork.MonitorNetworkAvailability() method so it monitors the network change
  2. At any time check the MyNetwork.IsConnected property to check for network presence
  3. Subscribe to its MyNetwork.ConnectionEstablished event
  4. Optionally, during debugging use its MyNetwork.ChangeStatus method to simulate a change in network status

As usual, there may be better ways to achieve this, but this class works perfectly for my scenarios. You can download the code here: MyNetworks.cs.


Supporting copy 'n paste in your Windows Phone app

Tue, May 3, 2011, 09:36 PM under MobileAndEmbedded

Some Windows Phone 7 owners already have the NoDo update, and others are getting it soon. This update brings, among other things, copy & paste support for text boxes. NoDo_CopyPasteThe user taps on a piece of text (and can drag in either direction to select more/less words), a popup icon appears that when tapped copies the text to the clipboard, and then at any app that shows the soft input panel there is an icon option to paste the copied text into the associated textbox. For more read this 'how to'. Note that there is no programmatic access to the clipboard, only the end user experience I just summarized, so there is nothing you need to do for your app's textboxes to support copy & paste: it just works.

The only issue may be if in your app you use static TextBlock controls, for which the copy support will not appear, of course. That was the case with my Translator by Moth app where the translated text appears in a TextBlock.

So, I wanted the user to be able to copy directly from the translated text (without offering an editable TextBox for an area where user input does not make sense). Take a look at a screenshot of my app before I made any changes to it. I then made changes to it preserving the look and feel, yet with additional copy support (see screenshot on the right)!

So how did I achieve that? Simply by using my co-author's template (thanks Peter!): Copyable TextBlock for Windows Phone.

 

(aside: in my app even without this change there is a workaround, the user could use the "swap" feature to swap the source and target, so they can copy from the text box)


Watermark TextBox for Windows Phone

Fri, April 22, 2011, 08:01 PM under MobileAndEmbedded

In my Translator by Moth app, in the textbox where the user enters a translation I show a "prompt" for the user that goes away when they tap on it to enter text (and returns if the textbox remains/becomes empty). imageSee screenshot on the right (or download the free app to experience it).

Back in June 2006 I had shown how to achieve this for Windows Vista (TextBox prompt), and a month later implemented a pure managed version for both desktop and Windows Mobile: TextBox with Cue Banner.

So when I encountered the same need for my WP7 app, the path of least resistance for me was to convert my existing code to work for the phone.

Usage:

  1. Instead of TextBox, in your xaml use TextBoxWithPrompt.
  2. Set the TextPrompt property to the text that you want the user to be prompted with.
  3. Use the MyText property to get/set the actual entered text (never use the Text property).
  4. Optionally, via properties change the default centered alignment and italic font, for the prompt text.

It is that simple! You can grab my class here: TextBoxWithPrompt.cs

Note, that there are many alternative (probably better) xaml-based solutions, so search around for those. Like I said, since I had solved this before, it was easier for my scenario to re-use my implementation – this does not represent best practice :-)


What changes were made to a document

Thu, March 31, 2011, 01:55 PM under Random

Part of my job is writing functional specs. Due to the inevitable iterative and incremental nature of software design/development, these specs need to be updated with additions/deletions/changes over a period of time. When the time comes for a developer to implement features or update their design document (or a tester to test the feature or update their test specs) they need to be doing that against the latest spec. The problem is that if they have reviewed this document already, they need a quick way to find the delta from the last time they reviewed it to see what changes exist and how their existing plans may be affected (instead of having to read the entire document again).

Doing that is very easy assuming your Word documents are hosted on SharePoint.

1. Every time you review a document note the SharePoint version and/or date (if it is a printed copy, make sure your printout includes the date in the footer – all my specs do)

image

2. When you need to see what changed, open the document (make sure you are not using a cached or local offline copy) and on the ribbon go to the "Review" tab and then  click on the "Compare" button.

image

3. Click on the "Specific Version…" option. In the dialog that pops up pick the last version you reviewed and click the "Compare" button. [TIP for authors: before checkin of your document, always compare against the "Last Version" on the SharePoint so you can add appropriate more complete check in comments]

image

4. What you see now is that in addition to the document you have open, two other documents just opened up. One is in the background (flashing on your task bar) – close that one as it is the old version.

image

5. The other document is in the foreground and contains all the changes between the old version and the latest one. Be sure not to make edits to this document, use it only for reading the changes. To find all the changes, on the ribbon under the "Review" tab, click on the "Reviewing Pane" to open the reviewing pane on the left. You can now click on each pink change to see what it is.

image

6. When you are done reviewing changes close the document and don't save any changes (remember if you want to make edits/additions/comments make them in the original document which is still open).

And now I have a URL to point to people that keep asking about this – enjoy  :-)


RTL (Arabic and Hebrew) Support for Windows Phone 7

Tue, February 15, 2011, 11:12 PM under MobileAndEmbedded

Problem and Background

Currently there is no support for Right-To-Left rendering in Windows Phone 7, when developing with Silverlight (itself built on .NET Compact Framework). When I encountered that limitation, I had a flashback to 2005 when I complained about the luck of RTL on NETCF. Unfortunately, the partial solution I proposed back then requires PInvoke and there is no such support on Windows Phone today.

Fortunately, my RTL requirements this time were more modest: all I wanted to do was display correctly a translation (of Hebrew or Arabic) in my FREE WP7 translator app. For v1.0 of the app, the code received a string from the service and just put it up on the screen as the translated text. In Arabic and Hebrew, that string (incorrectly) appeared reversed. I knew that, but decided that since it is a platform limitation, I could live with it and so could the users. Yuval P, a colleague at Microsoft, pushed me to offer support for Hebrew (something that I wasn't motivated to pursue if I am honest). After many back and forths, we landed on some code that works. It is certainly not the most efficient code (quite the opposite), but it works and met the bar of minimum effort for v1.1. Thanks Yuval for insisting and contributing most of the code!

After Hebrew support was there, I thought the same solution would work for Arabic. Apparently, reversing the Arabic text is not enough: Arabic characters render themselves differently dependent on what preceded/succeeds them(!). So I needed some kind of utility that takes a reversed Arabic string and returns the same string but with the relevant characters "fixed". Luckily, another MS colleague has put out such a library (thanks Bashar): http://arabic4wp7.codeplex.com/.

RTL Solution

So you have a reversed RTL string and want to make it "right" before displaying on the screen. This is what worked for me (ymmv).

  1. Need to split the string into "lines". Not doing this and just reversing the string and sticking it a wrapping text control means that the user not only has to read right to left, they also have to read bottom up.
  2. The previous step must take into account a line length that works for both portrait and landscape modes, and of course, not break words in the middle, i.e. find natural breaks.
  3. For each line, break it up into words and reverse the order of the words and the order of the letters within each word
  4. On the previous step, do not reverse words that should be preserved, e.g. Windows and other such English words that are mixed in with the Arabic or Hebrew words. The same exclusion from reversal applies to numbers.
  5. Specifically, for Arabic, once there is a word that is reversed also change its characters.
  6. For some code paths, the above has to take into account whether the translation is "from" an RTL language or if it is "to" an RTL language.

I packaged the solution in a single code file containing a static class (see the 'Background" section above for… background and credits).

Download RTL.cs for your Windows Phone app (to see its usage in action download for FREE "The best translator app")

using RTL.cs

Enjoy, and if you decide to improve on the code, feel free to share back with me…


"Translator by Moth"

Tue, January 4, 2011, 09:47 PM under MobileAndEmbedded

updated for v2

This article serves as the manual for the Windows Phone 7 app called "Translator by Moth". The app is available from the following link:

http://social.zune.net/redirect?type=phoneApp&id=bcd09f8e-8211-e011-9264-00237de2db9e

"current" page

The "current" page is the main page of the app with language pickers, translation boxes and the application bar.

Language list pickers

The "current" page allows you to pick the "from" and "to" languages, which are populated at start time. Tapping on either of them brings up on a full screen popup the list of languages to pick from, formatted as English Name followed by Native Name (when the latter is known). In addition to the language names, they indicate which languages have playback support via a * in front of the language name. When making a selection for the "to" language, and if there is text entered for translation, a translation is performed (so there is no need to tap on the "translate" application bar button). Note that both language choices are remembered between different launches of the application.

text for translation

The textbox where you enter the translation is always enabled. When there is nothing entered in it, it displays (centered and in italics) text prompting you to enter some text for translation. When you tap on it, the prompt text disappears and it becomes truly empty, waiting for input via the keyboard that automatically pops up. The text you type is left aligned and not in italic font. The keyboard shows suggestions of text as you type. The keyboard can be dismissed either by tapping somewhere else on the screen, or via tapping on the Windows Phone hardware "back" button, or via taping on the "enter" key. In the latter case (tapping on the "enter" key), if there was text entered and if the "from" language is not blank, a translation is performed (so there is no need to tap on the "translate" application bar button). The last text entered is remembered between application launches.

translated text

The translated text appears below the "to" language (left aligned in normal font). You can tap on the translated text to copy (parts of) it. Until a translation is performed, there is a message in that space informing you of what to expect (translation appearing there). When the "current" page is cleared via the "clear" application bar button, the translated text reverts back to the message.

Note a subtle point: when a translation has been performed and subsequently you change the "from" language or the text for translation, the translated text remains in place but is now in italic font (attempting to indicate that it may be out of date). In any case, this text is not remembered between application launches.

application bar buttons and menus

There are 4 application bar buttons:

  • "translate" button takes the text for translation and translates it to the translated text, via a single network call to the bing Microsoft Translator service. If the network call fails, the user is informed via a message box. The button is disabled when there is no "from" language available or when there is not text for translation entered.
  • "play" button takes the translated text and plays it out loud in a native speaker's voice (of the "to" language), via a single network call to the bing Microsoft Translator service. If the network call fails, the user is informed via a message box. The button is disabled when there is no "to" language available or when there is no translated text available.
  • "clear" button clears any user text entered in the text for translation box and any translation present in the translated text box. If both of those are already empty, the button is disabled. It also stops any playback if there is one in flight.
  • "save" button saves the entire translation ("from" language, "to" language, text for translation, and translated text) to the bottom of the "saved" page (described later), and simultaneously switches to the "saved" page. The button is disabled if there is no translation or the translation is not up to date (i.e. one of the elements have been changed).

…and there are also 6 application bar menus:

  • "swap to and from languages" menu swaps around the "from" and "to" languages. It also takes the translated text and inserts it in the text for translation area. The translated text area becomes blank. The menu is disabled when there is no "from" and "to" language info. This command is also useful if you wish to copy the translated text (simply swap and then select it).
  • "send translation via sms" menu takes the translated text and creates an SMS message containing it. The menu is disabled when there is no translation present.
  • "send translation via email" menu takes the translated text and creates an email message containing it (after you choose which email account you want to use). The menu is disabled when there is no translation present.
  • "post to social network" menu opens a new phone page where you can choose the social networks to which you want to post the translation. The social network options depend on what you have configured on your phone, and can be Facebook, windows live, LinkedIn, and twitter.
  • "pin to start" menu pins the current translation to the start screen. See description further down.
  • "about" menu shows the "about" page described later.

"saved" page

The "saved" page is initially empty. You can add translations to it by translating text on the "current" page and then tapping the application bar "save" button. Once a translation appears in the list, you can read it all offline (both the "from" and "to" text). Thus, you can create your own phrasebook list, which is remembered between application launches (it is stored on your device). To listen to the translation, simply tap on it – this is only available for languages that support playback, as indicated by the * in front of them. The sound is retrieved via a single network call to the bing Microsoft Translator service (if it fails an appropriate message is displayed in a message box). Tap and hold on a saved translation to bring up a context menu with 5 items:

  • "pin to start" menu pins the selected saved translation to the start screen. See description further down.
  • "move to top" menu moves the selected item to the top of the saved list (and scrolls there so it is still in view)
  • "copy to current" menu takes the "from" and "to" information (language and text), and populates the "current" page with it (switching at the same time to the current page). This allows you to make tweaks to the translation (text or languages) and potentially save it back as a new item. Note that the action makes a copy of the translation, so you are not actually editing the existing saved translation (which remains intact).
  • "delete" menu deletes the selected translation.
  • "delete all" menu deletes all saved translations from the "saved" page – there is no way to get that info back other than re-entering it, so be cautious.

Note: Once playback of a translation has been retrieved via a network call, your Windows Phone caches the results. What this means is that as long as you play a saved translation once, it is likely that it will be available to you for some time, even when there is no network connection.

"about" page

The "about" page provides some textual information including version, credits, the ability to tap on the logo icon to rate the app, and a link to the creator's blog (that you can follow on your Windows Phone device). Use that link to discover the email for any feedback.

Live and secondary tiles

When you pin the app tile to the start screen, you'll observe that the tile will "flip" at certain intervals. While the front of the tile is the familiar logo and app title, the back of the tile will show the text and language selection from the last time you closed the app.

In addition, you can pin secondary tiles from within the app, either from the current page (see the app bar menu above) or from the saved page (see the context menu above). In either case, a new tile will be created for you on the start screen for the selected translation. On these secondary tiles, on the front is the familiar logo and the target translation language in English; on the back of the tile is the translated text and the language in the native alphabet. When you tap on these secondary tiles, they will open the "Translator by Moth" app and have preloaded the selected translation language and translation. So these secondary tiles are shortcuts directly to the translation you were interested in.

Other UI design info

"Translator by Moth" has been designed from scratch for Windows Phone, using the nice pivot control and application bar. It also supports both portrait and landscape orientations, and looks equally good in both the light and the dark theme. Other than the default black and white colors, it uses the user's chosen accent color. Finally, it has been updated to take advantage of new NoDo/7.x/Mango/8.x phone features

Feedback and support

Please report (via the email on the blog) any bugs you encounter or opportunities for performance improvements and they will be fixed in the next update. Suggestions for new features will be considered. If you like the app, don't forget to rate "Translator by Moth" on the marketplace.


Best of "The Moth" 2010

Sat, January 1, 2011, 01:10 AM under Personal

It is the time again (like in 2004, 2005, 2006, 2007, 2008, 2009) to look back at my blog for the past year and identify areas of interest that seem to be more prominent than others. After doing so, representative posts follow in my top 5 list (in random order).

1. This was the year where I had to move for the first time since 2004 my blog engine (blogger.com –> dasBlog), host provider (zen –> godaddy), web server technology and OS (apache on Linux –> IIS on Windows Server). My goal was not to break any permalinks or the look and feel of this website. A series of posts covered how I achieved that goal, culminating in a tool for others to use if they wanted to do the same: Tool to convert blogger.com content to dasBlog. Going forward I aim to be sharing more small code utilities like that one…

2. At work I am known for being fairly responsive on email, and more importantly never dropping email balls on the floor. This is due to my email processing system, which I shared here: Processing Email in Outlook. I will be sharing more tips with regards to making the best of the Office products.

3. There is no doubt in my mind that this is the year people will remember as the one where Microsoft finally fights back in the mobile space. Even though the new platform means my Windows Mobile book sales will dwindle :-), I am ecstatic about Windows Phone 7 both as a consumer and as a developer. On the release day, to get you started I shared the top 10 Windows Phone 7 developer resources. I will be sharing my tips from my experience in writing code for and consuming this new platform…

4. For my HPC developer friends using Visual Studio, I shared Slides and code for MPI Cluster Debugger and also gave you all the links you need for getting started with Dryad and DryadLINQ from MSR. Expect more from me on cluster development in the coming year…

5. Still in the HPC space, but actually also in the game and even mainstream development, the big disruption and opportunity comes in the form of GPGPU and, on the Microsoft platform, (currently) DirectCompute. Expect more from me on gpgpu development in the coming year…

Subscribe via the link on the left to stay tuned for 2011… I wish you a very Happy New Year (with whatever definition of happiness works for you)!


Guide.BeginShowMessageBox wrapper

Thu, December 30, 2010, 12:38 AM under MobileAndEmbedded

imageWhile coding for Windows Phone 7 using Silverlight, I was really disappointed with the built-in MessageBox class, so I found an alternative. My disappointment was the fact that:

  1. Display of the messagebox causes the phone to vibrate (!)
  2. Display of the messagebox causes the phone to make an annoying sound.
  3. You can only have "ok" and "cancel" buttons (no other button captions).

I was using the messagebox something like this:

      // Produces unwanted sound and vibration. 
      // ...plus no customization of button captions.
      if (MessageBox.Show("my message", "my caption", MessageBoxButton.OKCancel)
              == MessageBoxResult.OK)
      {
        // Do something
        Debug.WriteLine("OK");
      }

…and wanted to make minimal changes throughout my code to change it to this:

      // no sound or vibration
      // ...plus bonus of customizing button captions
      if (MyMessageBox.Show("my message", "my caption", "ok, got it", "that sucks")
              == MyMessageBoxResult.Button1)
      {
        // Do something
        Debug.WriteLine("OK");
      }

It turns out there is a much more powerful class in the XNA framework that delivered on my requirements (and offers even more features that I didn't need like choice of sounds and not blocking the caller): Guide.BeginShowMessageBox. You can use it simply by adding an assembly reference to Microsoft.Xna.Framework.GamerServices.

I wrote a little wrapper for my needs and you can find it here (ready to enhance with your needs): MyMessageBox.cs.old.txt.

UPDATE 2013: If you don’t mind using await in front of the call to MyMessageBox.Show, I have an updated class that works for both Windows Phone 8 and for Windows 8 Store apps here: MyMessageBox.cs.txt.


Filing bugs

Sat, November 13, 2010, 07:14 PM under SoftwareProcess

I've previously wrote a lengthy post on Bug Triage, and I just came across a related lengthy post by Eric that is definitely worth reading: how to file bugs.


UX Movement

Sat, November 13, 2010, 07:10 PM under Links | UserInterfaceDesign

A few months ago I shared a UX blog that I found interesting. Today I'll share another: UX Movement. They have interesting design articles (e.g. this, this, this, this and that) and occasionally shares great UX resources (e.g. this and that).

Let me know if there are other UX resources you recommend…