Windows Support Number

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Monday, 21 March 2011

Considerations when building a caching mechanism for WP7Contrib.

Posted on 14:39 by Unknown
For anyone wanting to build a cache for an application, there are several guidelines(may be rules) you want to beware of and more than likely abid by.

Firstly, more than likely you are going to have an in-memory representation of the cache as well as a persisted format if the cache is to survive application restarts. Now an in-memory representation is more than likely going to be a hash-table - especially if you want acceptable retrieval time. Now this is where 'GetHashCode' comes into play and the importance of this is explained perfectly by Eric Lippert,

Secondly, and this follows on from a statement in Eric's post - 'the integer returned by GetHashCode should never change', if you're using the internal state of a class to calculate the hash code, you can't allow that state to change overtime. So this means you are more than likely going to have create a copy of the instance before using it as a 'key' when adding to the cache, because this will then negate this issue,

Thirdly, the data in the cache will be become stale at some point, so expirying data out of the cache will be a requirement, a cache is not a replacement for permanent persistence store like a database or files etc,

Finally, the cache should be transparent to the application, what I mean by this is if the cache fails during execution the only observable difference should be in application performance, the application should still be fully functional. This means if an exception occurs inside the cache it shouldn't be propergated to the host application.

So when we defined the cache providers in WP7Contrib we added an extra interface to the 'Common' project - ICloneable<T>. This is there to help define how an object will be copied\cloned, it defines methods for both shallow and deep copying. We use this interface for any class we wish to use as a 'key' when adding to a cache provider.
Read More
Posted in Caching, CodePlex, WP7, WP7Contrib | No comments

Thursday, 17 March 2011

WP7Contrib: RESTful communications using HttpWebRequest & Rx extensions

Posted on 14:50 by Unknown
20/03/2011 UPDATE: code samples after changes to WP7Contrib code base.

Simply I want to show how we do communication with web services when using WP7Contrib.

When using web services from WP7 devices you have several options on how you are going to communicate  with the service. What follows are the steps required to achieve this using the WP7Contrib. We show how to use a third party web service and how this pattern is very advantageous in this scenario.

We aren't advocating this is a better approach than using WCF data services (or any of other implementation), we've just been burnt before by WCF and prefer to possibly go through the pain of hand crafting resources (DTOs) than deal with WCF configs and it's short comings in Silverlight.

In Silverlight as we all know communication with web services has to be asynchronous, this in it's self is not a problem, but it can make the code ugly at best and difficult to understand. This is where Reactive Extensions come to the rescue, they allow you to handle asynchronous calls in a synchronous programming manner - I can write the code in a synchronous manner and it will execute in an asynchronous manner.

In the example below I'm using one of the 'secret' services available via the Google API - there's a great post here giving more info. The example uses the Google Weather API, this is a read only service that gives weather information for any location around the world, you access the data via a HTTP GET request.

Below is the code to make a HTTP request and debug out when the response is returned:

weatherResource.Get<xml_api_reply>("london")
   .ObserveOnDispatcher()
   .Subscribe(weather =>
   {
      Debug.WriteLine("we got weather news!");
   });

As you can see the code is very simple and has abstracted away the complexity of using the HttpWebRequest class. The other thing to note is the use of 'ObserveOnDispatcher' and 'Subscribe', these are method provided by the Reactive Extensions framework, if you're not familiar I would recommend doing some research. The 'ObserveOnDispatcher' method makes sure the asynchronous method invocation is on the dispatcher thread so we don't get any surprises when binding data. The 'Subscribe' method allows you to register as an observer.

Below is the code to initialise the 'weatherResource':

   weatherResource = new ResourceClient()
      .ForType(ResourceType.Xml)
      .UseUrlForGet("http://www.google.com/ig/api?weather={0}");

We use a class called 'ResourceClient' which implements an interface IHandleResources. The methods POST & PUT have 2 generic types, one for the request resource and one for the response resource. The reason why we don't just a single generic type is because this pattern is not just for making RESTful calls to REST services but can be used to make calls to SOAP services. The 2 other methods of interested are used to defined how the resource is serialized (JSON or XML) - 'ForType' and the  templated URL to use for a HTTP GET request. The parameters passed in the previous example to the 'Get' method are combined with the templated URL to create a valid url - http://www.google.com/ig/api?weather=london (make sure you 'view source' to see what is returned).

Below is the code defining the 'weatherResource':

   private IHandleResources weatherResource;

As you can see we define the interface 'IHandleResources<TRequest, TResponse>' this defines the operations that are supported - GET, PUT, POST & DELETE, along with a set of methods for configuring the URLs (for the operations), authentication, namespaces etc. The interface definition is shown below:

 public interface IHandleResources<TRequest, TResponse> where TRequest : class, new() where TResponse : class, new()
{
      ResourceType Type { get; }
      IHandleResources ForType(ResourceType type);
      IHandleResources UseUrl(string url);
      IHandleResources UseUrlForGet(string getUrl);
      IHandleResources UseUrlForPost(string postUrl);
      IHandleResources UseUrlForPut(string putUrl);
      IHandleResources UseUrlForDelete(string deleteUrl);
      IHandleResources WithNamespace(string prefix, string @namespace);
      IHandleResources WithBasicAuthentication(string username, string password);
      IObservable<TResponse> Get<TRequest>();
      IObservable<TResponse> Get<TRequest>(params object[] @params);
      IObservable<TResponse> Put<TRequest, TResponse>(TRequest resource);
      IObservable<TResponse> Put<TRequest, TResponse>(TRequest resource, params object[] @params);
      IObservable<TResponse> Post<TRequest, TResponse>(TRequest resource);
      IObservable<TResponse> Post<TRequest, TResponse>(TRequest resource, params object[] @params);
      IObservable<TResponse> Delete<TRequest>();
      IObservable<TResponse> Delete<TRequest>(params object[] @params);
      IHandleResources WithHandlerDefinitions(JsonHandlerDefinitions definitions);
}

As you can see the request & response resources used in the examples are of type 'xml_api_reply' - I generated this automatically from an example XML response using XML Schema Definition Tool (xsd.exe). This was then included in the demo project and I removed manually the attributes which aren't supported by Silverlight in WP7.

If I was using a RESTful service which returned JSON I would have handcrafted the request & response resources as required - we use JSON.NET to handle the serialisation of JSON, so any request or response resources have to support serialization\deserialization by JSON.NET when communication with JSON based services.

That pretty much covers the basics of what is required to make a HTTP request using this pattern. You can find the demo application 'CommunicationDemo' in the Spikes directory of the WP7Contrib code base. Shown below is a screenshot from the demo application.


For completeness I've included a more detailed class on how to use this pattern - this is in the demo application. It shows how we don't use the 'ResourceClient' or the resources directly in a view model - we map the resources into a model and encapsulate this and the 'ResourceClient' class inside a 'Service' class. The service class then uses it's own IObservable<T> via the Subject<T>class. If you're not come across the idea of 'services' before check out Eric Evans Domain Driven Design book.

    public class WeatherService : IProviderWeather
    {
       private readonly IHandleResources<xml_api_reply, xml_api_reply> weatherResource;

       public WeatherService()
       {
            weatherResource = new ResourceClient()
                .ForType(ResourceType.Xml)
                .UseUrlForGet("http://www.google.com/ig/api?weather={0}");
       }

       public IObservable<WeatherSummary> Get(string location)
       {
            try
            {

                // TODO service related stuff before call...
               
                var observable = new Subject<WeatherSummary>();
                this.weatherResource.Get<xml_api_reply, xml_api_reply>(location)
                                        .Subscribe(response =>
                                                       {
                                                          var weather = ProcessResponse(response);
                                                          // TODO other service related stuff like caching
         
                                                          observable.OnNext(weather);
                                                       },
                                                   observable.OnError,
                                                   observable.OnCompleted);

                return observable;
            }
            catch (Exception exn)
            {
                throw new Exception("Failed to get Weather!", exn);
            }
       }

       private WeatherSummary ProcessResponse(xml_api_reply response)
       {
            var summary = new WeatherSummary();
            summary.Current = new Weather();
            summary.Current.Temperature = Convert.ToInt32(response.weather[0].current_conditions[0].temp_c[0].data);

            return summary;
       }
    }

So that pretty much covers it, keep your eyes open for a post on applying this principle to the MS Bing Maps API by Rich Griffin.



Read More
Posted in CodePlex, REST HTTP, WP7, WP7Contrib | No comments

Sunday, 6 March 2011

WP7Contrib: Why we use SilverlightSerializer instead of DataContractSerializer

Posted on 07:04 by Unknown
Like all applications developed for WP7 devices we (WP7Contrib) want to get the best performance possible from any libraries or patterns we use and this applies to how we serialize and deserialize data inside the WP7Contrib. In several of the libraries which make up the WP7Contrib we require binary serialization support, specifically we use binary serialization for the isolated storage cache provider and the storage service in the services project.

Simply after testing we found SilverightSerializer gave better performance, shown below the results of serializing a collection of 1000 items compared to the DataContractSerializer.


It shows the tick count, the equivalent time in milliseconds and the size of the generated byte array . So you can see the SilverlightSerializer gives better performance from both a time and size perspective. These results were generated using the StopWatch class.

The only downside I can see from using the SilverlightSerializer is the support for generic types used with custom collection types - you have to explicitly implement a serialization helper class for each type, you'll see this in the test application I created I had to create a class ProductCollectionSerializer to support serialization of the type ObservableCollection.

The test application 'SerializationPerformance' is available in the Spikes directory of the WP7Contrib code base.

That's it for now, I'll be back with the post about RESTful communication in WP7Contrib.
Read More
Posted in CodePlex, Serialization, WP7, WP7Contrib | No comments

Saturday, 5 March 2011

WP7Contrib: Trickling data to a bound collection

Posted on 13:04 by Unknown
Recently Rich & I've had problems with adding items to list control where the data template is chocked full of XAML goodies - triggers, opacity masks, images, overlay, loads of things I know little about... ;) The culmination of all this UI goodness when used with a bound list control is the blowing of the '90 mb limit' for WP7 devices. As I posted before, we knew the problem wasn't with the data model so we knew it was the data template, now there is plenty of coverage of issues with data templates in Silverlight and this post it not adding to this list, its about a technique to reduce the memory footprint once you've done as much as you can with the data template.

So we're developing an app which exhibits high memory usage, now obviously we want to reduce the memory consumption for the app so we trimmed down the data template for the list control, but we're still seeing the 90 mb limit exceeded for relative few items. Our data set could in theory contain several hundred items but it was failing for less than 40 items and this is an issue.

So Rich can up with the idea of adding a delay between each add to the bound collection - trickle the items, so after some experimentation we discovered the use of a call to the garbage collector when all the items have been added along with a delayed between each item reduced the memory usage to an acceptable level.

The initial implementation Rich came up with used a DispatcherTimer and I thought I could improve on this with Rx (reactive extensions) - this didn't work out (Rich - I won't try and be smart again). Simply the Rx added to much overhead and this caused  the rendering to be less smooth than the DispatcherTimer implementation. So we went back to the DispatcherTimer.

We've provider the implementation in the WP7Contrib, there are currently 2 implementations:

  • TrickleUniqueToCollection<T> - Only adds items not already in the collection,
  • TrickleAllToCollection<T> - adds all items irrespective if they already exist in the collection.

Both classes implement the interface ITrickleToCollection<T> via the base class BaseTrickleToCollection<T>. It defines a set of methods that allow the starting, pausing, resuming and stopping of trickling as required. The start method defined the time delay between each add as well the source collection and the destination collection.

public interface ITrickleToCollection<T>
{
   bool Pending { get; }
   bool IsTrickling { get; }
   void Start(int trickleDelay, IEnumerable<T> sourceCollection, IList<T> destinationCollection);
   void Stop();
   void Suspend();
   void Resume();
}

Both classes use a functional style via the Action method to notify the caller when an action occurs, e.g. when the trickling has started, stopped, item added etc. Shown below is the constructor signatures for both implementations:

public sealed class TrickleUniqueToCollection<T> : BaseTrickleToCollection<T>
{
   public TrickleUniqueToCollection(Action addedAction, Action completedAction)
      : this (addedAction, () => {}, () => {}, () => {}, () => {}, completedAction)

   public TrickleUniqueToCollection(Action addedAction, Action startedAction, Action stoppedAction,
                                    Action suspendedAction, Action resumedAction, Action completedAction)
   : base (addedAction, startedAction, stoppedAction, suspendedAction, resumedAction, completedAction)
}

public sealed class TrickleAllToCollection<T> : BaseTrickleToCollection<T>
{
   public TrickleAllToCollection(Action addedAction, Action completedAction)
      : this (addedAction, () => {}, () => {}, () => {}, () => {}, completedAction)

   public TrickleUniqueToCollection(Action addedAction, Action startedAction, Action stoppedAction,
                                    Action suspendedAction, Action resumedAction, Action completedAction)
   : base (addedAction, startedAction, stoppedAction, suspendedAction, resumedAction, completedAction)
}

Each class has a specific implementation for the DispatcherTimer, shown below is the implementation for the TrickleAllToCollection<T>, the interesting detail is the timer being shutdown once trickling all of the items has completed - no point leaving it running consuming device resources (memory & CPU).

public TrickleAllToCollection(Action addedAction, Action startedAction, Action stoppedAction,
                              Action suspendedAction, Action resumedAction, Action completedAction)
   : base (addedAction, startedAction, stoppedAction, suspendedAction, resumedAction, completedAction)
{
      this.DispatcherTimer = new DispatcherTimer();
      this.DispatcherTimer.Interval = this.StartupDelay;
      this.DispatcherTimer.Tick += delegate
         {
            if (this.DispatcherTimer.IsEnabled)
            {
               if (this.Source.Count != 0)
               {
                  var item = this.Source.Dequeue();
                  this.Destination.Add(item);
                  this.AddedAction();

                  if (this.Count == 0)
                     this.DispatcherTimer.Interval = this.Delay;

               this.Count++;
               }
               else
               {
                  this.DispatcherTimer.Stop();
                     this.CompletedAction();
               }
            }
         };
   }

Using these classes is simply, just instantiate an instance with the required Action methods:

 this.trickler = new TrickleUniqueToCollection<Property>(() => this.UpdateTrickleStatus(TrickleStatus.Added),
                                                        () => this.UpdateTrickleStatus(TrickleStatus.Started),
                                                        () => this.UpdateTrickleStatus(TrickleStatus.Stopped),
                                                        () => this.UpdateTrickleStatus(TrickleStatus.Suspended),
                                                        () => this.UpdateTrickleStatus(TrickleStatus.Resumed),
                                                        () => this.UpdateTrickleStatus(TrickleStatus.Completed));

And then start trickling to the bound destination collection:


   this.trickler.Start(432, result.Properties, this.aggregatedPropertiesView);

That's pretty much it, as I said these are in the WP7Contrib and can be found in the Collections project. I've also created a demo application 'TrickleDemo' in the Spikes directory of the code base. This demo doesn't show any memory problems with data templates, it only demonstrates how to use this trickle to collection pattern.

Next time a post about how we do RESTful communication in WP7 using the HttpWebRequest  & Reactive Extensions...
Read More
Posted in CodePlex, WP7, WP7Contrib | No comments

Saturday, 19 February 2011

WP7Contrib: Isolated Storage Cache Provider

Posted on 09:00 by Unknown
15/04/2001 - The code for this example has been updated - new WP7 build of SilverlightSerializer, this has removed the explicit implementation of ISerializeObject interface from the example model classes.

WP7Contrib received it's first question on the discussions forum, it was about how to use the IsolatedStorageCacheProvider.

Rich & I have been using this for a while in development and the question highlighted the lack of examples on how to use some of the stuff we've pushed out. So I thought I would share some insight into the demo I produced to answer the question.

You'll find the demo in the 'CacheProviderDemo' in the 'Spikes' directory in the code-base. It demostrates how to add both value & reference types to the cache, how these gets persisted to isolated storage and how values are purged from the cache. Before I show some code snippets I'll give some background to our thinking about caching.

As wikipedia states 'a cache is a component that transparently stores data so that future requests for that data can be served faster...'.

This is basis for the caching mechanisms in the WP7Contrib along with the principle that any implementation should be fault tolerant, i.e. if the cache fails to add or remove items this should not cause the host application to crash, the only exhibited behaviour would be a slight degradation in application performance.

The isolated cache provider has 3 requirements for any items you want to store:
  • Value types - These can not be used directly with the cache provider, the wrapper class CacheValue has to be used with these or cast to the type of Object. The cache provider only supports storing reference types,
  • Serialization - Any item you want to add to the cache (key or value) must support serialization via the SilverlightSerializer, Mike Talbot's blog has detailed information about to mark reference types for serialization and providing custom implementation through the ISerializeObject interface,
  • Hash code - Items are stored using a key-value pair hash-table in memory (as well as being persisted to isolated storage), and the key is expected to have a predictable hash code. Therefore we recommend using the properties of the reference type to calculate the value. We provide a mechanism in the BaseModel class for this purpose, CombineHashCodes, obviously you can use what ever alogrthim best fits your requirement.

That's enough background lets get to the code, as with all my demos the code is in the 'code behind'.

The snippet below shows the setup of the cache provider. There are 3 requirements for the constructor:

  • Application name - string identifing the cache, typically we use the application name, e.g. 'CacheProviderDemo',
  • Serialization assemblies - a list of any extra assemblies required for serialization by the SilverlightSerializer, these will be the assemblies containing your references types you've marked for serialization,
  • Log - captures diagnostic info about the provider.
We also initialise a variable for cache timeout - this is how long items remain in the cache before they are purged, we set the value to 20 seconds, obviously you can set this on a per item basis as required.
private const string ApplicationName = "CacheProviderDemo";
private ICacheProvider cacheProvider;
private TimeSpan cacheTimeout;
private ILog log;

public MainPage()
{
    InitializeComponent();

    var extraSerialisationAssemblies = new List<Assembly>();
    extraSerialisationAssemblies.Add(this.GetType().Assembly);

    log = new DebugLog();
    cacheProvider = new IsolatedStorageCacheProvider(ApplicationName, extraSerialisationAssemblies, log);
    cacheTimeout = TimeSpan.FromSeconds(20);
}
The final snippet below shows adding a value type to the cache and then reading the value back, both the key & value are value types in this example.
private void addValueType_Click(object sender, RoutedEventArgs e)
{
    var key = Guid.NewGuid().ToString();
    var value = new CacheValue(42);

    cacheProvider.Add(key, value, cacheTimeout);

    log.Write("Added value type to the cache...");

    var cacheValue = cacheProvider.Get<string, CacheValue>(key);
    var actualValue = (int)cacheValue.Value;

    log.Write("Value type read back from cache, value - '{0}'", actualValue);
}
The snippet below shows adding a reference type to the cache and then reading the value back, both the key & value are reference types in this example. The key is an instance of the 'ExampleReferenceTypeKey' class and supports serialization (see bottom of post for full class listing).
private void addReferenceType_Click(object sender, RoutedEventArgs e)
{
    var key = new ExampleReferenceTypeKey
        {
        FirstName = "Dirk",
        LastName = "Gently",
        Url = new Uri("http://wp7contrib.codeplex.com/"),
        Random = Guid.NewGuid()
        };

    var value = new List<Guid>();
    for (var i = 0; i < 100; i++)
       value.Add(Guid.NewGuid());

    cacheProvider.Add(key, value, cacheTimeout);

    log.Write("Added reference type to the cache...");

    var cacheValue = cacheProvider.Get<ExampleReferenceTypeKey, List<Guid>>(key);

    log.Write("Value type read back from cache, list count = {0}", cacheValue.Count);
}
The screenshot below shows the automatic persistence and purging working for the demo, it's a screenshot of the output window from visual studio. The timeline for this is as follows:

1. An item is added to the cache,
2. A maximum wait of 15 seconds happens before the cache is persisted(to isolated storage),
3. 20 seconds after the item is added to the cache it is purged from the cache,
4. A maximum wait of 15 seconds happens before the cache is persisted again.



That pretty much rounds up how the IsolatedStorageCacheProvider and as i said earlier the implementation and demo can be downloaded from the WP7Contrib project on CodePlex.


Full list for class ExampleReferenceTypeKey;

[Serializer(typeof(ExampleReferenceTypeKey))]
public class ExampleReferenceTypeKey : BaseModel, IEquatable<ExampleReferenceTypeKey>, ISerializeObject
{
    private string firstName;
    private string lastName;
    private Uri url;
    private Guid random;

    public ExampleReferenceTypeKey()
    {
    }

    public object[] Serialize(object target)
    {
        var key = (ExampleReferenceTypeKey)target;
        return new object[] { key.FirstName,
            key.LastName,
            key.Url,
            key.Random };
    }

    public object Deserialize(object[] data)
    {
        var key = new ExampleReferenceTypeKey
        {
            FirstName = (string)data[0],
            LastName = (string)data[1],
            Url = (Uri)data[2],
            Random = (Guid)data[3]
        };

        return key;
    }

    public string FirstName
    {
        get { return this.firstName; }
        set { this.SetPropertyAndNotify(ref this.firstName, value, () => this.FirstName); }
    }

    public string LastName
    {
        get { return this.lastName; }
        set { this.SetPropertyAndNotify(ref this.lastName, value, () => this.LastName); }
    }

    public Uri Url
    {
        get { return this.url; }
        set { this.SetPropertyAndNotify(ref this.url, value, () => this.Url); }
    }

    public Guid Random
    {
        get { return this.random; }
        set { this.SetPropertyAndNotify(ref this.random, value, () => this.Random); }
    }
        
    public override int GetHashCode()
    {
        return this.CombineHashCodes(FirstName, LastName, Url, Random);
    }

    public static bool operator ==(ExampleReferenceTypeKey k1, ExampleReferenceTypeKey k2)
    {
        return Equals(k1, k2);
    }

    public static bool operator !=(ExampleReferenceTypeKey k1, ExampleReferenceTypeKey k2)
    {
        return !Equals(k1, k2);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj))
        {
            return false;
        }

        return obj is ExampleReferenceTypeKey && this.Equals((ExampleReferenceTypeKey)obj);
    }

    public bool Equals(ExampleReferenceTypeKey key)
    {
        if (ReferenceEquals(null, key))
        {
            return false;
        }

        if (this.FirstName != key.FirstName)
        {
            return false;
        }

        if (this.LastName != key.LastName)
        {
            return false;
        }

        if (this.Url != key.Url)
        {
            return false;
        }

        if (this.Random != key.Random)
        {
            return false;
        }

        return true;
    }
}
Read More
Posted in Caching, CodePlex, WP7, WP7Contrib | No comments

Monday, 14 February 2011

WP7: Thinking about performance implicitly

Posted on 05:59 by Unknown
It's inevitable as the moon going around the earth - the performance of your Windows Phone 7 app will become an issue during your application development life cycle, hopefully you're using agile practices and therefore this won't happen to late in the process. There is one technique I believe you should always apply to the process and that is 'thinking about performance implicitly'.

So I have 3 tips which help me achieve thinking about performance implicitly.

The emulator is not your friend - You should as others have pointed out always be testing on a device and not the emulator - the emulator is great for spiking and unit testing but not as environment for building an application, it runs at the speed of the host and I haven't yet managed to find a WP7 phone to match the perf of my 4 * Quad Core machine :)

Get the worst device possible - Okay any device running WP7 will have been certified by MS as acceptable, but there are still great differences between them. We all want the latest with the best memory, processor etc but in the long run it's better to test against the lowest common denominator - it will save you time & money in the long term (if you can get hold of 2 devices then even better).
I'm currently using an LG GW910 and to say I don't like the device is an under statement, the responsiveness of the touch screen, the quality of the display and the number of 'white screens' compared to newer devices is noticeable, so if I can get good perf from this device then I know it will be better on newer devices, unless something less inspiring comes to the market that is.

Turn off WIFI support - When testing communication to back end services turn off WIFI, test using 2G\2.5G\3G or GSM EDGE it will give you a more real world experience. If your application works great over these it will fly on WIFI.
Read More
Posted in Development, WP7, WP7Dev | No comments

Tuesday, 8 February 2011

WP7Contrib: Location Push Model

Posted on 14:22 by Unknown
Anyone who's tried to get your current location of a WP7 device will know this is not as simple as it first appears, the problems really revolve around the frequency at which the location information can be generated by the device (GeoCoordinateWatcher class) and the fact it is generated on the UI thread. Jaime Rodriguez has a very insightful post on the issues, you should read this first if you're not familiar with the issues. For the WP7Contrib we wanted to abstract away the issues and simplify the interface for any developer wanting to get location information.

Following the pattern we used for Network Connectivity we use a push model using the MS Reactive Extensions for .Net. We use an observable sequence which returns the current location (latitude & longitude) in one of three ways - the current location, the location by time threshold (seconds or TimeSpan) and the location by distance threshold (metre).

The interface for the location service is shown below:

public interface ILocationService
{
    IObservable<GeoCoordinate> Location();
    IObservable<GeoCoordinate> LocationByTimeThreshold(int frequency);
    IObservable<GeoCoordinate> LocationByTimeThreshold(TimeSpan frequency);
    IObservable<GeoCoordinate> LocationByDistanceThreshold(int distance);
}

As you can see we have abstracted away the GeoCoordinateWatcher class and provide a clean push model using the IObservable as the return types for all variants.

The implementation of this interface can be found in the LocationService class, in the WP7Contrib.Services assembly.

We decided the implementation would not return a value when the location is unknown (latitude = NaN, longitude = NaN) - if a time out is required for trying to obtain a value then 'Timeout' observable extension should be used, and if the previous value is the same as the current value a value would not be returned - this only applies to the threshold based variants.

Examples of how easy it can be to get location information are shown below, as usual I've implemented this in the 'code behind' for simplicity.

The first example is how to get the current location:

private void currentLocation_Click(object sender, RoutedEventArgs e)
{
    currentSubscriber = locationService.Location()
       .ObserveOnDispatcher()
       .Subscribe(location =>
       {
          this.results.Insert(0, string.Format("'{0}', '{1}'", location.Latitude, location.Longitude));
       });
}

The second example is how to get the location using a distance threshold:

private void startDistance_Click(object sender, RoutedEventArgs e)
{
    if (locationSubscriber != null)
       return;

    var val = Convert.ToInt32(this.threshold.Text);
    locationSubscriber = locationService.LocationByDistanceThreshold(val)
       .ObserveOnDispatcher()
       .Subscribe(location =>
       {
          this.results.Insert(0, string.Format("'{0}', '{1}'", location.Latitude, location.Longitude));
       });
}

And the final example is how to get the location using a time threshold:

private void startTime_Click(object sender, RoutedEventArgs e)
{
    if (locationSubscriber != null)
       return;

    var val = (int)(Convert.ToDouble(this.threshold.Text) * 1000);
    locationSubscriber = locationService.LocationByTimeThreshold(val)
       .ObserveOnDispatcher()
       .Subscribe(location =>
       {
          this.results.Insert(0, string.Format("'{0}', '{1}'", location.Latitude, location.Longitude));
       });
}

These examples are from a quick application called 'RxLocationService' (the code can be found in WP7Contrib on CodePlex in the Spikes directory), screenshot shown below.


As you can see from these examples we've greatly simplifies using the location based information on a WP7 device. The complexity is hidden away in the LocationService class, and below I've included code snippets for each difference variation.

Getting the current location is straight forward - create an instance of a Subject<GeoCoordinate> class, this is returned via the IObservable<GeoCoordinate> interface then create an instance of GeoCoordinateWatcher and hook up an event handler for the PositionChanged event, when the event is fired we update the Subject<GeoCoordinate> with the new value and also importantly signal any observers that the observable sequence has finished by calling 'OnCompleted', this is important because it will shutdown the GeoCoordinateWatcher correctly. Next we start the watcher (which will start asynchronously under the covers) and return the Subject<GeoCoordinate> as an observable sequence where we fitler out an unknown location values.

public IObservable<GeoCoordinate> Location()
{
    var subject = new Subject<GeoCoordinate>();
    var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default)
       { MovementThreshold = FixedLocationDistance };

    watcher.PositionChanged += (o, args) =>
       {
          subject.OnNext(args.Position.Location);
          subject.OnCompleted();
       };
    watcher.Start();

    return subject.AsObservable()
       .Where(c => !c.IsUnknown)
       .Finally(() =>
       {
          watcher.Stop();
          watcher.Dispose();
       });
}

Next is the code getting the location by a distance threshold - this is very similar to the current location, but the differences are we use a BehaviorSubject<GeoCoordinate> and importantly we don't signal the observable sequence has finished in the event handler. We also use the 'DistinctUntilChanged' extension method to filter out the results so that only distinct values are returned to any observers.

public IObservable<GeoCoordinate> LocationByDistanceThreshold(int distance)
{
    var subject = new BehaviorSubject<GeoCoordinate>(GeoCoordinate.Unknown);
    var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default)
       { MovementThreshold = distance };
    watcher.PositionChanged += (o, args) =>
       {
          var newLocation = args.Position.Location;
          subject.OnNext(args.Position.Location);
       };
    watcher.Start();

    return subject.Where(c => !c.IsUnknown)
       .DistinctUntilChanged()
       .Finally(() =>
       {
          watcher.Stop();
          watcher.Dispose();
       })
       .AsObservable();
}

And finally the location by a time threshold - this uses the Interval method on the Observable class to trigger getting the location at the required time interval. The CurrentLocationByTime method actual returns the value from the GeoCoordinateWatcher class using the TryStart method.

private IObservable<GeoCoordinate> LocationByTimeImpl(TimeSpan timeSpan)
{
    return Observable.Interval(timeSpan)
       .ObserveOn(Scheduler.ThreadPool)
       .SubscribeOn(Scheduler.ThreadPool)
       .Select(t => this.CurrentLocationByTime(timeSpan))
       .Where(c => !c.IsUnknown)
       .DistinctUntilChanged();
}

private GeoCoordinate CurrentLocationByTime(TimeSpan timeSpan)
{
    var currentLocation = GeoCoordinate.Unknown;
    using (var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default))
    {
       if (watcher.TryStart(true, timeSpan))
       {
          currentLocation = watcher.Position.Location;
       }

       watcher.Stop();
    }

    return currentLocation;
}

So that pretty much rounds it up, as I said the code can be found in the WP7Contrib CodePlex project in the WP7Contrib.Services project.
Read More
Posted in CodePlex, WP7, WP7Contrib, WP7Dev | No comments
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • MVVM anti-pattern: View code behind with no implementation
    I've seen rather a lot of this anti-pattern recently, to be explicit about what I mean, lets define this in terms of a WPF user control....
  • Showing a message box from a ViewModel in MVVM
    I was doing a code review with a client last week for a WPF app using MVVM and they asked ' How can I show a message from the ViewModel?...
  • Exception handling for an async method
    I've been unit testing a method which has a return type of Task<T> and I need to handle cases where  exceptions will be thrown. Sh...
  • MVVM anti-pattern: Injecting the IoC container into a View Model
    This is another anti-pattern I've seen a lot recently, the dynamic use of the IoC container inside a view model to resolve child view mo...
  • WP7Contrib: Transient caching with In Memory Cache Provider
    Rich  and I are currently working on a WP7 application based around local content stored on the device.   This content consists of a databas...
  • Removing the 'Invalid Credentials... ' message from Bing Maps on WP7
    I got asked a question by @mrlacey today about how to remove the overlay message you can get when using the Bing Maps control on WP7. Now I...
  • Using IoC nested lifetime scopes with View Models in MVVM
    A common pattern you see when developing web services is the use of the Unit of Work applied to the HTTP request - anything that happens dur...
  • Azure - RoleEnvironmentException in OnStart
    My previous post was a bit of rant at the developer experience in Azure when trying to set-up diagnostics. I managed to work out what was c...
  • Be careful of the culture when using Bing Maps REST API
    When developing the Bing Maps Wrapper service for the WP7Contrib we weren't aware of the importance of the instance of the CultureInfo ...
  • Manipulating web browser scroll position on Windows Phone 7
    Manipulating the browser control position on WP7 is relatively straight forward, all you need to is a couple of calls out to javascript usin...

Categories

  • .Net
  • .Net 4.5
  • Abstractions
  • Advertising
  • Agile
  • Agile Courage
  • AOP
  • Async
  • automated testing
  • Azure
  • Azure IIS RESTful development
  • BDD
  • Bing Maps
  • Bounded Context
  • C#
  • C# 5.0
  • Caching
  • Chocolatey
  • CLoud
  • CodePlex
  • Coding
  • Coding Building CI Testing
  • Coding C#
  • coding C# IoC StructureMap
  • Coding Functional-Programming
  • Coding REST Knowledge
  • Coding Services
  • Coding TDD Refactoring Agile
  • Command
  • continuous testing
  • coupling
  • CultureInfo
  • DAL
  • databases
  • DDD
  • DDD Coaching
  • DDD Domain Events Auditing nHibernate
  • DDD Entities Value Objects
  • Debugging
  • Design Patterns
  • Design Patterns Databases Auditing
  • Developement
  • Development
  • Development Coding
  • Development Process
  • Development unit testing
  • Development VS 2011
  • Diagnostics
  • Disposable
  • Exceptions
  • FINDaPAD
  • FindaPad Property Rental Windows Phone 7 Mobile Devices
  • Fun Coding Duct-Tape
  • Hotfixes
  • integration testing
  • IoC
  • jasmine
  • javascript
  • Jobs Development
  • LINQ
  • marketplace
  • Mobile Devices
  • Mocking
  • MSDN Coding
  • MSpec
  • Multilingual
  • MVC
  • MVVM
  • nCrunch
  • nHbiernate Repository Pattern Criteria
  • nHibernate Auditing Design Fluent
  • nHibnerate Entities Events Listeners
  • node.js
  • nodes.js
  • Nokia
  • NoSQL RavenDB Azure Development
  • Observations
  • OO
  • ORM
  • Performance
  • Portable Class Library
  • Portable Library
  • PostSharp
  • Process
  • Rants
  • RavenDB IIS 7.5 Development
  • Reactive
  • Reactive Extension
  • Reactive Extensions
  • ReadOnlyCollections
  • Resharper
  • REST Distributed-Systems
  • REST HTTP
  • rest web
  • RESTful
  • Rx
  • Serialization
  • Silverlight
  • Silverlight Installation
  • Task
  • TDD
  • TDD IoC DI
  • TDD Mocking
  • TDD Team Observation
  • Telerik
  • testing
  • threading
  • TPL
  • UI
  • Undo-Redo
  • unit testing
  • ViewModels
  • VS 2012
  • wcf
  • web api
  • Web Services
  • web services mobile devices data
  • WebAPI
  • Windows
  • Windows 8
  • windows phone
  • Windows Phone 7
  • WP7
  • WP7 Bing Maps Development Network HTTP
  • WP7 Bing Maps Development UK Crime
  • WP7 Bing Maps Development UK Crime Clustering
  • WP7 Bing Maps Development UK Polygons Clustering Performance
  • WP7 cryptography bouncy castle
  • WP7 Cultures C#
  • WP7 feedback development app store
  • WP7 Javascript web browser
  • WP7 MSBuild
  • WP7 ORM Databases performance
  • WP7 Serialisation
  • WP7 SilverlightSerializer C#
  • WP7 sqlite performance development
  • WP7 WP7Contrib Bing Maps Development
  • WP7 WP7Contrib Bing Maps Polygon Development
  • WP7 WP7Contrib CodePlex
  • WP7 WP7Contrib CodePlex Bing Maps Development
  • WP7 WP7Contrib CodePlex ObservableCollection
  • WP7 WP7Contrib ILMerge .Net
  • WP7 WP7Contrib Phone Maps
  • WP7 WP7Contrib SilverlightSerializer C#
  • WP7Contrib
  • WP7Contrib Bing Maps WP7
  • WP7Contrib WP7 Geo-Location development C#
  • WP7Contrib WP7 HTTP Compression
  • WP7Contrib WP7 Url Development Rx
  • WP7Dev
  • WPF
  • WPF Cultures
  • WuApi
  • XAML

Blog Archive

  • ▼  2013 (16)
    • ▼  November (5)
      • MVVM anti-pattern: Injecting the IoC container int...
      • MVVM anti-pattern: View code behind with no implem...
      • MVVM anti-pattern: explicitly using data context i...
      • Implementing a message box using a visual overlay ...
      • Using IoC nested lifetime scopes with View Models ...
    • ►  September (3)
    • ►  August (1)
    • ►  July (1)
    • ►  June (3)
    • ►  May (2)
    • ►  January (1)
  • ►  2012 (44)
    • ►  November (2)
    • ►  October (8)
    • ►  September (5)
    • ►  August (2)
    • ►  July (4)
    • ►  June (3)
    • ►  May (1)
    • ►  April (2)
    • ►  March (13)
    • ►  February (4)
  • ►  2011 (52)
    • ►  December (3)
    • ►  November (5)
    • ►  October (7)
    • ►  September (7)
    • ►  August (11)
    • ►  July (4)
    • ►  May (2)
    • ►  April (1)
    • ►  March (5)
    • ►  February (3)
    • ►  January (4)
  • ►  2010 (1)
    • ►  August (1)
  • ►  2009 (32)
    • ►  December (3)
    • ►  November (7)
    • ►  October (6)
    • ►  September (11)
    • ►  April (1)
    • ►  March (4)
Powered by Blogger.

About Me

Unknown
View my complete profile