Socket not working after WP7 tombstone resume

I’ve written an app that needs to connect to a WiFi router and broadcasts UDP packets. I was finding that after a tombstone and resume, the packets were no longer seen on the network using Wireshark. No errors were returned, the app was getting Success for the send and connect but it clearly wasn’t working.

It turns out that when the app resumed and the socket was reconnected, instead of defaulting to Wifi, it defaulted to MobileBroadbandGsm so it was sending the packets successfully but on the wrong network interface.

The solution turned out to be calling:

socket.SetNetworkRequirement(NetworkSelectionCharacteristics.NonCellular);

Thanks to Pat Long for his assistance.

Control your lights from Windows Phone 7 using LightwaveRF

Using a Nokia Lumia or one of the other windows phones you can now control your lights and other appliances (UK only I think).

The system is using LightwaveRF no PC required!

Step 1: Buy one of these LightwaveRF Wifi things and plug it into your Wifi router

http://amzn.to/GCkwtR

LightwaveRF Wifi-link for Remote Iphone or Android Mobile Phone Lighting Control

Step 2: Swap your existing light switch for one of these (variety of colours available):

http://amzn.to/HDRQ4h

LightwaveRF Remote 1 Gang Dimmer 250w Black Chrome Light Switch

Step 3: Get the unofficial Home Remote RF app from the market place

http://www.windowsphone.com/en-GB/apps/41666473-fb72-4dd8-a2b0-5d6056acd846

1 of 5

I thought pairing the devices was pretty easy (much easier than X10 if you’ve used that and more reliable). LightwaveRF also has the advantage of remembering dim levels.

Read an in-depth review at: http://www.automatedhome.co.uk/Reviews/LightwaveRF-Home-Automation-System-In-Depth-Review.html

Although the app featured in the review is for the official iPhone app not the unofficial WP7 one.

There was an error processing type ‘{0}’. Type member ‘{1}’ declared in ‘{2}’ is missing required ‘{3}’ property. If one class in the class hierarchy uses explicit sequencing feature ({3}), then its base class and all derived classes have to do the same.

This was due to having Order on some but not all DataMembers of the data contract (might have been more helpful if the error had actually contained values for the format parameters).

Useful frameworks and controls for WP7

Since I find myself using a common bag of goodies for WP7 development I thought I’d start listing them here.

Mvvm light*

http://mvvmlight.codeplex.com/

NInject IoC

https://github.com/ninject/ninject/downloads

AgFX* (although using in conjunction with MVVM light you may find grating since concept of view model and model is a bit blurred although still blendable using the Sample Data approach).

http://agfx.codeplex.com/

Windows Phone Toolkit

http://silverlight.codeplex.com

Jump List Control

http://www.scottlogic.co.uk/blog/colin/2011/01/a-windows-phone-7-jump-list-control/

(although you should follow the suggestion in one of the follow up posts if you get an “unspecified error” because it doesn’t look as though Colin has updated the code).

* Also available on NuGET

Other stuff I want to look at but haven’t had a chance yet

WP7 Contrib – Caching, Messaging, Communciations, Services, Diagnostics and a bringing together of some good public WP7 controls.

http://wp7contrib.codeplex.com/

AgFx–Looks Awesome!

http://agfx.codeplex.com/

WP7 framework for managing web-service calls including caching, queuing, priority, login handling, progress showing and blend-ability.

So I’ve joined the party of this framework late but it looks awesome. In my previous WP7 app I spent a lot of time creating queues of web requests, ensuring I could cancel pending requests if navigating away from pages but I didn’t have time to put the excellent features that AgFx appears to support.

The only issue I’ve got at the moment it doesn’t appear to pass back or accept the HTTP headers, just the response stream. Also you have to kind of forget MVVM light a bit since although there’s the separation of view and model, there isn’t much of a separation between viewmodel and model.

File or assembly name ‘System.Windows.debug.resources, Version=2.0.5.0, Culture=en-US, PublicKeyToken=7cec85d7bea7798e’, or one of its dependencies, was not found.

This is apparently a known issue in WP7 Mango beta 2 & RC and can make debugging that bit more interesting.

One tip is to look at the Call Stack and ensure that “Show Parameter Values” is ticked (off by default):

image

Also see this post for some more discussion. It suggests this happens when you are checking for all thrown exceptions (Debug –> Exceptions…).

image

WP7 Emulator: intercepting and decoding SSL traffic

So fiddler doesn’t yet work with the WP7 emulator but Wireshark does.

  1. Open WireShark
  2. Edit -> Preferences…
  3. Expand Protocols and select SSL
    • Check Reassemble SSL Records…
    • Check Reassemble SSL Application…
    • RSA keys list: 0.0.0.0,443,http,C:\pathToYourKey.pem
    • SSL debug file: c:\temp\wireshark.pkg
      Now capture the traffic as you use the emulator then after stopping the capture, right click on an SSL entry and choose “Follow SSL stream”
  4. image

Of course this only works if you have access to the SSL key.

WP7 Detecting Memory Leaks

In a WP7 application, if the app exceeds 90mb it is likely to be torn down without any exceptions. The app will appear to hang for a few seconds before the user is returned to the menu.

Finding memory leaks in a Silverlight app is a bit more challenging since you don’t have memory profiling tools like CLR Profiler which can be used for WPF.

Note the emulator does not currently enforce the same limit so your app may appear to work perfectly reliably until you finally get a device to test on.

Although the garbage collector does a good job, it will only clean up objects that are no longer reachable. With event subscriptions, timers and anonymous delegates it’s very easy to inadvertently make an object reachable. Here are the techniques I used to locate a memory leak.

1. Monitor the current and peak memory usage

See http://wotudo.net/blogs/wotudo/archive/2010/09/23/wp7-memory-monitoring-tip.aspx).

Setup a timer in your app.xaml like this (tip: you might want to wrap in #if (DEBUG)):           

Code Snippet
  1. System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
  2. timer.Interval = TimeSpan.FromMilliseconds(1000d);
  3. timer.Tick += timer_Tick;
  4. timer.Start();

Then handle the tick:

Code Snippet
  1. void timer_Tick(object sender, EventArgs e)
  2. {
  3.     long deviceTotalMemory = (long)Microsoft.Phone.Info.DeviceExtendedProperties.GetValue(“DeviceTotalMemory”);
  4.     long applicationCurrentMemoryUsage = (long)Microsoft.Phone.Info.DeviceExtendedProperties.GetValue(“ApplicationCurrentMemoryUsage”);
  5.     long applicationPeakMemoryUsage = (long)Microsoft.Phone.Info.DeviceExtendedProperties.GetValue(“ApplicationPeakMemoryUsage”);
  6.     System.Diagnostics.Debug.WriteLine(DateTime.Now.ToLongTimeString());
  7.     System.Diagnostics.Debug.WriteLine(“Device Total : “ + deviceTotalMemory);
  8.     System.Diagnostics.Debug.WriteLine(“App Current : “ + applicationCurrentMemoryUsage);
  9.     System.Diagnostics.Debug.WriteLine(“App Peak : “ + applicationPeakMemoryUsage);
  10. }

 

2. Add debug output to finalizers

Add this to each page and output when they are being finalized – you could add this to every class but perhaps the most important are the ones that can consume large amounts of memory such as pages with Panoramas and shouldn’t live for the lifetime of the app:

Code Snippet
  1. #if(DEBUG)
  2.         /// <summary>
  3.         /// Add a finalizer to check for memory leaks
  4.         /// </summary>
  5.         ~MyPage()
  6.         {
  7.             System.Diagnostics.Debug.WriteLine(“Finalizing “ + this.GetType().FullName);
  8.         }
  9. #endif

Navigate around your application, when you finally come to quit the app you shouldn’t see a finalizer being repeatedly called for an object that you assumed would be garbage collected. You can also call the following to force a collection, if you don’t see your object being collected then you may have a leak:

Code Snippet
  1. GC.Collect();
  2. GC.WaitForPendingFinalizers();

3. Event handlers

Check code for any event handlers that are not subscribing to their own events and ensure that you are unsubscribing from the event.

Watch out for anonymous event handlers that refer to members or variables in the parent scope/class (see modified closure) or subscriptions to events that don’t unsubscribe. For more information on this see:

http://blogs.msdn.com/b/ericlippert/archive/2007/06/06/fyi-c-and-vb-closures-are-per-scope.aspx

http://blogs.msdn.com/b/oldnewthing/archive/2006/08/02/686456.aspx

4. Timers and DispatcherTimer

From MSDN: “A DispatcherTimer will keep an object alive whenever the object’s methods are bound to the timer”. Note the timer can only be garbage collected when disabled.

Bad code!
  1. public MyPage()
  2. {
  3.     InitializeComponent();
  4.     DispatcherTimer timer = new DispatcherTimer();
  5.     timer.Interval = TimeSpan.FromSeconds(1);
  6.     timer.Tick += (s, a) =>
  7.         {
  8.             this.txt.Text = “This causes a memory leak”;
  9.         };
  10.     timer.Start();
  11. }

 5. Consider using a WeakReference based Messaging approach

Such as the one in Laurent Bugnion’s MVVM Light Toolkit. This uses WeakReferences to ensure that subscribers to messages can still be garbage collected.

Finally

The issue I tracked down was to do with InteractionTriggers in MVVM Light, the Loaded event and static ViewModels which you can read about here. It’s worth keeping on top of current issues in whatever framework you’re using. For open Memory Leak issues in MVVM light, see here, it looks like they’re scheduled to be fixed in V4 (currently in beta).