Damian Mehers' Blog Android, VR and Wearables from Geneva, Switzerland.


Windows Phone 7 Watermark on PasswordBox

For my textboxes I’ve been using a modified version Johan Danforth’s Watermark behaviour (binding the watermark text to a ViewModel property instead of hardcoding the text), but when I needed to do something similar for a PasswordBox I thought I was stuck.

I’ve come up with an incredibly basic, simple solution that seems to work well. Instead of just having a PasswordBox, I also have a TextBox behind it which I make invisible when the PasswordBox has content, or has focus.  Because the watermark TextBox is behind the PasswordBox, it never gets focus: it is purely visual.

Code Snippet
    <TextBox x:Name="PasswordWatermark" TextWrapping="Wrap" Text="{Binding Labels.password, Mode=OneTime}" Foreground="{StaticResource PhoneTextBoxReadOnlyBrush}" IsHitTestVisible="False"/>
    <PasswordBox x:Name="Password" LostFocus="PasswordLostFocus" Opacity="0" GotFocus="PasswordGotFocus" Password="{Binding Password, Mode=TwoWay}"/>

In the code-behind I hide/show the watermark TextBox and the PasswordBox as appropriate.  Note that I show and hide them by changing their opacity, not by setting their visibility. 

Because the PasswordBox is in front of the the watermark Textbox, when the user clicks in that area he always clicks on the PasswordBox, even if it is invisible.

Code Snippet
  1. private void PasswordLostFocus(object sender, RoutedEventArgs e)
  2. {
  3.     CheckPasswordWatermark();
  4. }
  6. public void CheckPasswordWatermark()
  7. {
  8.     var passwordEmpty = string.IsNullOrEmpty(Password.Password);
  9.     PasswordWatermark.Opacity = passwordEmpty ? 100 : 0;
  10.     Password.Opacity = passwordEmpty ? 0 : 100;
  11. }
  13. private void PasswordGotFocus(object sender, RoutedEventArgs e)
  14. {
  15.     PasswordWatermark.Opacity = 0;
  16.     Password.Opacity = 100;
  17. }

When populating the PasswordBox, you can call CheckPasswordWatermark() to show/hide the watermark as appropriate.

Filed under: WP7 14 Comments

Restoring Pivot Scroll on WP7 Tombstone resume

Putting the user back to the correct pivot item when they return to a tombestoned application whose last visited page contained a Pivot is pretty easy, but ensuring that they are put back to the right scroll position if they’ve scrolled down a list isn’t quite as easy.

In the code below I have a method which returns the first ScrollViewer under an item.  This works well for me, but if your PivotItem’s contents contain ScrollViewers then you’ll need something more sophistacated.

In the OnNavigatedFrom I follow the standard pattern Microsoft recommends, and store away the scroll offset in the page state.

In the OnNavigatedTo I recuperate the scroll position, but cannot yet scroll because the PivotItem’s contents have not been loaded.  Instead I store the scroll position, and then when the pivot has been loaded I then scroll.  In my XAML I hook up each PivotItem’s Loaded event to invoke PivotItemLoaded

Code Snippet
  1. static ScrollViewer FindScrollViewer(DependencyObject parent)
  2. {
  3.     var childCount = VisualTreeHelper.GetChildrenCount(parent);
  4.     for (var i = 0; i < childCount; i++)
  5.     {
  6.         var elt = VisualTreeHelper.GetChild(parent, i);
  7.         if (elt is ScrollViewer) return (ScrollViewer)elt;
  8.         var result = FindScrollViewer(elt);
  9.         if (result != null) return result;
  10.     }
  11.     return null;
  12. }
  14. protected override void
  15.     OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
  16. {
  17.     base.OnNavigatedFrom(e);
  19.     State["MainPivot.SelectedIndex"] = MainPivot.SelectedIndex;
  20.     var pivot = (PivotItem)MainPivot.SelectedItem;
  21.     var scrollViewer = FindScrollViewer(pivot);
  22.     State["scrollViewer.VerticalOffset"] = scrollViewer.VerticalOffset;
  23.     _newPageInstance = false;
  24.     State["PreservingPageState"] = true;
  25. }
  27. // Communicates scroll position between OnNavigatedTo and PivotLoaded
  28. private double _pivotScroll;
  30. protected override void
  31.     OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  32. {
  33.     base.OnNavigatedTo(e);
  35.     if (!_newPageInstance || !State.ContainsKey("PreservingPageState"))
  36.     {
  37.         return;
  38.     }
  40.     MainPivot.SelectedIndex = (int)State["MainPivot.SelectedIndex"];
  42.     // Can't scroll now because Pivot's contents won't have been loaded
  43.     _pivotScroll = (double)State["scrollViewer.VerticalOffset"];
  44. }
  46. // Hooked up to each pivot item's Loaded event handler.
  47. private void PivotLoaded(object sender, RoutedEventArgs e)
  48. {
  49.     if (_pivotScroll == 0 || sender != MainPivot.SelectedItem) return;
  51.     var pivot = (PivotItem)sender;
  52.     var scrollViewer = FindScrollViewer(pivot);
  53.     scrollViewer.ScrollToVerticalOffset(_pivotScroll);
  54.     _pivotScroll = 0;
  55. }

Filed under: WP7 1 Comment

Generating Silverlight / Windows Phone compatible Thrift proxies

Thrift is a software framework for scalable cross-language services development. It combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, Smalltalk, and OCaml. http://thrift.apache.org/

There are two reasons for this post:

  • to float some ideas for C#changes to the Thrift development community.
  • to remind myself in the future what I need to do to download, modify and build the Windows Thrift compiler, and

The idea is to maintain backwards compatibility, whilst at the same time generating Silverlight (and consequently Windows Phone 7) compatible proxies.

There are two sets of changes.  One to the C# code generator (t_cpp_generator.cpp), and the other to the runtime files (mainly THttpClient.cs).

Downloading and building the thrift compiler

To try out these changes on Windows, first install the latest version of Cygwin from http://cygwin.com/, then install the various packages as described here: http://wiki.apache.org/thrift/ThriftInstallationWin32

You’ll also need to install Subversion.

Next pop open the Cygwin shell, and fetch the latest source, as described here: http://thrift.apache.org/download/

Finally, build the source you downloaded, again as described here:


In my environment I build using:


And then I run the new thrift compiler:


Code Generator changes

The code generator (t_cpp_generator.cpp) changes involve generating two additional methods for each “standard” method: a Begin_… method and an End_… method.

Whereas previously there might just have been a method such as this:

   1: SyncState getSyncState(string authenticationToken);

Now, two additional methods get generated:


   2: IAsyncResult Begin_getSyncState(AsyncCallback callback, object state, string authenticationToken);

   3: SyncState End_getSyncState(IAsyncResult asyncResult);

   4: #endif

The two methods allow for the asynchronous invocation of methods, using the standard .NET asynchronous invocation pattern.

In addition, the generated standard method (“getSyncState”) method is modified when building for Silverlight, to make use of the Begin… and End… methods:

   1: public SyncState getSyncState(string authenticationToken)

   2: {

   3:     #if !SILVERLIGHT

   4:     send_getSyncState(authenticationToken);

   5:     return recv_getSyncState();


   7: #else

   8:     var asyncResult = Begin_getSyncState(null, null, authenticationToken);

   9:     return End_getSyncState(asyncResult);


  11: #endif

  12: }

As you can see, when not running Silverlight the standard code path is invoked, but when running Silverlight the asynchronous methods are invoked (the End… method blocks the current thread until the Begin… method completes).  This is not something you should be doing on the UI thread.

The generated Begin… and End… methods are pretty thin:

   1: public IAsyncResult Begin_getSyncState(AsyncCallback callback, object state, string authenticationToken)

   2: {

   3:     return send_getSyncState(callback, state, authenticationToken);

   4: }


   6: public SyncState End_getSyncState(IAsyncResult asyncResult)

   7: {

   8:     oprot_.Transport.EndFlush(asyncResult);

   9:     return recv_getSyncState();

  10: }

Note the call to EndFlush above – this is one of the changes made to the runtime.  The other is invoked by the generated send_getSyncState method:


   2: public IAsyncResult send_getSyncState(AsyncCallback callback, object state, string authenticationToken)

   3: #else

   4: public void send_getSyncState(string authenticationToken)

   5: #endif

   6: {

   7:     oprot_.WriteMessageBegin(new TMessage("getSyncState", TMessageType.Call, seqid_));

   8:     getSyncState_args args = new getSyncState_args();

   9:     args.AuthenticationToken = authenticationToken;

  10:     args.Write(oprot_);

  11:     oprot_.WriteMessageEnd();


  13:     return oprot_.Transport.BeginFlush(callback, state);

  14: #else

  15:     oprot_.Transport.Flush();

  16: #endif

  17: }

The generated recv_getSyncState() has not changed.

The changes in the generated code boil down to asynchronous invocations at the transport layer (BeginFlush and EndFlush).

There are also changes to #ifdef out the Serializable attribute for generated structs, since this is not supported by Silverlight.

Runtime changes

There are minor tweaks required to THashSet, TProtocol and TBinaryProtocol because Silverlight does not support the full .NET framework API.

The main change is to TTransport.cs to introduce the BeginFlush and EndFlush methods shown above, and then to THttpClient.cs to actually implement these methods.

The existing Flush method is #ifdefed out when building using Silverlight, because it makes synchronous calls which are not supported by Silverlight.

Instead, the BeginFlush builds a request and then invokes the HttpWebRequest.BeginGetRequestStream method, passing a local GetRequestStreamCallback method as the callback.

The GetRequestStreamCallback method is invoked once the runtime has the request stream.  It then writes out the data and invokes the HttpWebRequest.BeginGetResponse method, passing a local GetResponseCallback method as callback.

The GetResponseCallback notifies the original caller (in the generated code) that the request has now completed.

The EndFlush method waits for the corresponding BeginFlush method to complete, and if there was an exception thrown at any point, it raises the corresponding exception.

The changes

The changes files are here.  If there is interest and these changes make sense, I’ll submit a patch.

Filed under: Uncategorized 8 Comments