Feeds:
Posts
Comments

It is actually quite obvious, but figuring out the implications still took me a few minutes today.

Suppose you have a simple list of objects:

   1: List<Object> list = new List<Object> { new Object(), new Object() };

And for some reasons you’d like to create a projection from this list using a wrapper class. One reason why you would do this is wrapping business objects into ViewModels.

   1: var enumerable = from o in list

   2:                  select new Wrapper(o);

The Wrapper class only adds the capability of being flagged to the whole story:

   1: public class Wrapper

   2: {

   3:     public bool IsFlagged { get; set; }

   4:  

   5:     private Object Obj;

   6:     public Wrapper(Object o)

   7:     {

   8:         Obj = o;

   9:     }

  10: }

So what you now have in enumerable is an IEnumerable<Wrapper>. Next, you’d like to use the wrapper functionality and flag the two elements in enumerable:

   1: foreach (var e in enumerable)

   2: {

   3:     e.IsFlagged = true;

   4: }

And then you go forth using your enumerable, only to discover that none of the contained elements are flagged.

What!? Why?

It’s because an IEnumerable is not a List. One needs to understand that prior to calling .ToList() or using foreach() to enumerate over it, no constructor of wrapper has been invoked. Put another way, only because we used this nifty LINQ projection, no Wrapper instances exist yet.

They came into life when we foreach’ed them and disappeared right after that. Whenever we try to use enumerable again, we are enumerating this LINQ expression again. Which means we call the constructors again and we get totally different instances of Wrapper.

For example, suppose we’d use this expression in order to check how many elements are actually selected as an effort to find out why the program doesn’t work as expected:

   1: int numberFlagged = enumerable.Count(e => e.IsFlagged);

This will return 0, as we already know. The best way to find out is to step through the provided code and put a breakpoint into the Wrapper constructor. Please find the whole source code ready for copy & paste at the end of this article.

Although i knew how an IEnumerable behaves, it took me 10 minutes today to find my error in a slightly more complicated example. I guess it’s the special case of using a linq projection together with an IEnumerable that got me.

class Program

{

    static void Main(string[] args)

    {

        List<Object> list = new List<Object> { new Object(), new Object() };

 

        var enumerable = from o in list

                            select new Wrapper(o);

 

        foreach (var e in enumerable)

        {

            e.IsFlagged = true;

        }

 

        int numberFlagged = enumerable.Count(e => e.IsFlagged);

    }

 

    public class Wrapper

    {

        public bool IsFlagged { get; set; }

 

        private Object Obj;

        public Wrapper(Object o)

        {

            Obj = o;

        }

    }

}

I’d like to give a brief overview of the project for starters. The first important thing to notice here is that in this first step, there are no Mango tools involved. We are still working with the first version of the windows phone tools (7.0) and will switch to Mango later in the project. Fairly soon, though.

So the first thing I have done was reusing the parser logic. Clearly by far not the finest piece of code I’ve ever written, but we don’t even need to cover it here. The only thing worth mentioning is that it is responsible for issuing a HTTP GET to the HeavensAbove website with the coordinates your phone detected. All this scraping and parsing lives in the projects FlareParser and HeavensAboveParser. MobileFlares.Core is responsible for defining the interfaces and BusinessObjects the parsed, raw data gets transformed into.

I nearly forgot to mention the use of Async CTP features in the code, which greatly simplify working with asynchronous calls. Visual Studio Async CTP SP1 Refresh ships with assemblies for Windows Phone 7, which are included in the solution. Although the solution is self contained, you will still need to install the CTP should you want to build it yourself.

I’ve used the databound template for this project. This sets up your project with one page for master data and one page for detail data. For this step, we don’t even need the details page, we will only bind the data to a list on the master page (called MainPage.xaml)

MobileFlares/SampleData contains MainViewModelSampleData.xaml to throw design time data at the list on the master page. This is wired up in MainPage.xaml using this line:

d:DataContext="{d:DesignData SampleData/MainViewModelSampleData.xaml}"

The DataTemplate for visualizing flare data is called FlareOverviewTemplate and resides in App.xaml.

That’s it for the project layout. A bit more interesting is how the GeoCoordinateWatcher is set up. There is an initalization method in the code behind for MainPage.xaml:

private void InitGeoWatcher()
{
  geoWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
  geoWatcher.MovementThreshold = 1000; // Notify about new position every 1km travelled
  geoWatcher.PositionChanged += geoWatcher_PositionChanged;
  geoWatcher.Start();
}

By specifying GeoPositionAccuracy.Default we tell the watcher that we don’t need GPS accuracy and are happy to use coordinates that have been determined through cell tower triangulation. This cuts down power consumption because the GPS sensor does not need to get activated.

Movement threshold is another option for reducing both power consumption and the number of calls to the website. As long as the app is running, the PositionChanged event will only fire if the position has changed more than 1km. This is still good enough for accurate flare predictions.

There is also a LogPage implementation that can be hooked up to attach itself to the ApplicationBar. Up to this point, it has only been used to check when the GeoCoordinateWatcher fires its PositionChanged event.

So this is what happened up to revision 3: The app will get the location from your device, use the coordinates to fire a request to the website, parse the response into business objects and bind it through MainViewModel to a list on the screen.

image

The next step will already contain the upgrade to Mango tools and using the Compass API to implement what I called guidance.

  1. Introduction
  2. Setup and project overview

Some ideas are more or less useless, but also just as timeless. Some time ago, I started to implement a project called Mobile Flares for Windows Mobile 6.5. It was a small app for getting flare predictions for Iridium Flares.

After I got myself a brand new Windows Phone I thought about revisiting the project to make it work on the new platform. But it was only when the new Windows Phone Mango features were announced that I eventually got into it. Mango has interesting new APIs this small application can benefit from, which is why I’d like to shine some light on implementation details in order to turn the project into a Mango tutorial.

In the following posts, I will describe the implementation progress in steps and also point to the corresponding code revision. All the code is available on Codeplex, I am using Mercurial as version control software. I have to apologize for my random switching between german and english commit comments, I will restrict it to english from now on.

Even though the main use case of Mobile Flares is extremely simple (get predictions for the current location) there are a lot of sub-usecases revolving around this, which is why the application uses, among other APIs:

  • Location API
  • Compass API
  • Background Agents
  • Live Tiles
  • Local Database
  • Reminders

It also uses Visual Studio Async CTP (SP1 Refresh) and MVVM Light.

What I like about Windows Phone development is that it’s only a special flavor of Silverlight development, and Silverlight will look familiar to anyone who has done some WPF, which is, as it happens, exactly what I have done. I will not cover the basics of XAML, data binding etc for this is not a Silverlight tutorial.

Instead, I will show how to achieve this with LiveTiles:

image

and this using reminders

image

and this using compass data

image

So now you are the owner of a shiny WP7 device and even got a marketplace signup so you can code applications for this thing. And after a while you realize that Microsoft released a firmware update that contains some functionality you would like to incorporate into your apps, like copy & paste for example.

But your phone just never tells you about the update, and there is nothing to be installed, and some friends of yours already got the update while you are still unable to thoroughly test your app. Then you realize the difference: You bought the phone from a different carrier.

Some carriers hold back new updates for WP7 for quite some time, which – from a developer’s point of view – might be unacceptable.

And then someone tells you that flashing your phone with an original (unbranded) ROM might do the trick, but this means that you are losing all your messages and settings and so on – almost everything in fact, since the device will be completely reset, just like after doing a fresh reinstall of you favorite OS on your PC. But at least for a PC there are a lot of backup solutions available that will bring all your data back.

At the time of writing, this is not true for WP7 devices – the only backup solution worth mentioning I know of will do a complete backup of the phone – including the device’s current ROM which means that this is only applicable if you do NOT want do upgrade the ROM. But this is precisely what debranding is about.

If your only goal is to unlock the updates for your phone so that it uses MS updates directly instead of waiting for your carrier to release them, then there is another solution. Essentially, it will only flick a switch telling your phone not to receive the updates from your carrier but directly from MS. It will not alter your branded boot screen nor any other settings on your phone. Most importantly, it will not do anything to your precious data.

This is a short outline of what I did for my Samsung Omnia 7:

  1. (Optional) Create a complete backup of your phone so you could roll back in case of failure. This might be a good idea anyway.
    1. Install the support tool for WP7
    2. Install this wrapper for the support tool (this is the backup solution I mentioned previously)
    3. Perform a backup of the phone. For me, it was ok to remove the USB cable when the app told me to even though the phone was displaying an image at that time strongly advising me not to do so
  2. Follow the instructions on this site. For me this meant:
    1. Installing the registry editor for Samsung devices. This editor comes as an XAP file which must be deployed to the phone via the Windows Phone SDK Application Deployment tool
    2. After that I had to edit one registry value and
    3. Reboot the phone
  3. This should be it. My phone announced available updates and I installed them after Zune was finished updating itself to a new version.

Some forum members claimed that this took more than one attempt for them. While it worked for me at once, some had to try 20 times.

HTH

Looking for a way to expose data from Windows Azure Table Storage via an OData webservice I quickly discovered that in its current form, WCF Data Services are primarily meant to expose relational data when using the Entity Framework. Since working with Azure Storage – such as TableStorage – typically does not involve a relational data model, OData seemed to be a difficult path. Not using Entity Framework means you will have to implement your own LINQ provider to get the job done. This is not a trivial task as it involves juggling – or rather messing – around with expression trees.

At this point I discovered the WCF Data Services Toolkit on Codeplex which circumvents the need to write your own LINQ provider by using a repository pattern architecture for you to hook into. I also found documentation to get me started, however I discovered later that the documentation does not match the current (beta) release of the toolkit.

As a prerequisite, please read the author’s blog post about updating resources with the toolkit. Here he describes the IWriteableRepository interface. Please note that this documentation is partly out of date as with the april update:

 

IWriteableRepository interface is gone

But fear not. It is a breaking change, but simply removing it from the class declaration will do the trick. This is because methods on your repository will be called by convention (hence by reflection). This has multiple advantages which the author mentions at the end of the updating resources post.

CreateDefaultEntity has been renamed to CreateResource

While the previous change might have been obvious, this one is not. But again, this is easy to solve, just rename the method.

 

This is it for the changes. Some random things I discovered while using the Toolkit:

Make sure to implement CreateResource. In there, simply new up a new instance of your entity (or do more advanced stuff if necessary). Otherwise, the toolkit will try to use Activator.CreateInstance() to create an entity instance, which did not work for me because the type to create an instance from was in a different assembly. This is a known issue (#12 on Codeplex) and I sent a patch for this to the author.

 

Just for reference: The list of methods one can implement in the repository:

  1. public void Save(<YourType> entity)
  2. public void Remove(<YourType> entity)
  3. public void CreateRelation(<YourType> entity, <YourOtherType> relatedEntity)
  4. public object CreateResource()

So far, I really like the toolkit and how it helped me to work with Azure Storage. Keep up the good work!

Using Silverlight in conjunction with Windows Identity Foundation prevents you from calling REST web services, at least out of the box. Here is why:

  1. Using WIF to authenticate the Silverlight client against a server relies on security tokens being sent from client to server. These tokens are sent as cookies
  2. Sending cookies from a Silverlight application means you have to use the BrowserHTTP network stack since the other option for silverlight (ClientHTTP stack) is incapable of sending cookies
  3. BrowserHTTP in turn is limited to sending GET and POST requests. But REST web service methods often use other HTTP verbs as well, such as PUT and DELETE
  4. So this means we can’t use WIF with Silverlight AND call web service methods by HTTP verbs other than GET and POST, right?

Right, not as it is. But in certain circumstances, one is able to get over this limitation.

These are the moving parts:

So what is needed for our workaround? The web service has to understand and handle a request header that you can set in your Silverlight App and that is being used to tunnel the actual verb.

I chose to use X-HTTP-Method-Override as header. If you are responsible for the implementation of the web service, you could of course use every spare header you’d like, but I think X-HTTP-Method-Override pretty much sticks to the standards.

The solution can be outlined as follows:

  1. You still use the BrowserHTTP stack, which lets WIF do its magic.
  2. Whenever you want to send, lets say a PUT request, you set a header in the Silverlight app on this request which contains the actual verb you want to use (in this example, PUT) and let the stack issue a POST request to the resource.
  3. The web service recognizes the header and uses the contained verb to handle the requests as opposed to the verb the stack reported.

Here is some code to tunnel the verb by setting a header:

var request = (HttpWebRequest)System.Net.Browser.WebRequestCreator.BrowserHttp.Create(new Uri(fullUri));
request.Headers["X-HTTP-Method-Override"] = "PUT";
request.Method = "POST";

 
Next, here is what is necessary to make the web service understand this header.
ASP.NET MVC offers the [Authorize] attribute to make sure incoming calls to a method are authenticated. 

This attribute uses the actual verb and does not recognize our custom header, so we will need to provide another implementation for that. Luckily, that one is easy. Below is the full sample implementation of an attribute that uses the custom header if present, otherwise it will use the real verb. This implementation is mostly based on the ASP.NET MVC version of the Authorize attribute.

[AspNetHostingPermission(System.Security.Permissions.SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class AcceptTunneledVerbsAttribute : ActionMethodSelectorAttribute
{
   public AcceptTunneledVerbsAttribute(HttpVerbs verbs)
       : this(EnumToArray(verbs))
   {
   }

   public AcceptTunneledVerbsAttribute(params string[] verbs)
   {
       if (verbs == null || verbs.Length == 0)
       {
           throw new ArgumentException("Argument was null or empty", "verbs");
       }

       Verbs = new ReadOnlyCollection<string>(verbs);
   }

   public ICollection<string> Verbs
   {
       get;
       private set;
   }

   private static void AddEntryToList(HttpVerbs verbs, HttpVerbs match, List<string> verbList, string entryText)
   {
       if ((verbs & match) != 0)
       {
           verbList.Add(entryText);
       }
   }

   internal static string[] EnumToArray(HttpVerbs verbs)
   {
       List<string> verbList = new List<string>();

       AddEntryToList(verbs, HttpVerbs.Get, verbList, "GET");
       AddEntryToList(verbs, HttpVerbs.Post, verbList, "POST");
       AddEntryToList(verbs, HttpVerbs.Put, verbList, "PUT");
       AddEntryToList(verbs, HttpVerbs.Delete, verbList, "DELETE");
       AddEntryToList(verbs, HttpVerbs.Head, verbList, "HEAD");

       return verbList.ToArray();
   }

   public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
   {
       if (controllerContext == null)
       {
           throw new ArgumentNullException("controllerContext");
       }

       string incomingVerb = controllerContext.HttpContext.Request.Headers["X-HTTP-Method-Override"] ?? controllerContext.HttpContext.Request.HttpMethod;
       return Verbs.Contains(incomingVerb, StringComparer.OrdinalIgnoreCase);
   }
}

 
Credit to whom credit is due: These have been my sources

Golo Roden: Hint for tunneling the verb (german) http://www.des-eisbaeren-blog.de/post/2009/07/13/ClientHttpStack-in-Silverlight-3.aspx

Jeff Prosise: Differences between Silverlight network stacks http://www.wintellect.com/CS/blogs/jprosise/archive/2009/10/14/silverlight-3-s-new-client-networking-stack.aspx

stackoverflow user Levi pointed into the right direction for handling the header in ASP.NET MVC. Make sure to read the comments, subclassing the Attribute does not work. http://stackoverflow.com/questions/467535/is-it-possible-to-implement-x-http-method-override-in-asp-net-mvc


 

This morning, I received a newsletter from the Windows Azure Platform Team. Besides the fact that it’s formatting is horrible as usual since all German umlauts are displayed as some weird unreadable symbol, it contained a lot of new and exciting features for Windows Azure. Also be sure to check out this video which provides a fast overview of new features for Windows Azure.

Extra Small Instances

This is one of the features I was really waiting for. Before this announcement, the smallest instance size was Small, having a price tag of $0.12 per hour. Now there is an Extra Small instance size with $0.05 / hour.

I went ahead and replicated the table from this Microsoft web site to have the most current overview on my blog. This should come in handy, at least for me because I will keep forgetting this stuff.

Compute Instance Size CPU Memory Instance Storage I/O Performance Cost per hour
Extra Small 1.0 GHz 768 MB 20 GB Low $0.05
Small 1.6 GHz 1.75 GB 225 GB Moderate $0.12
Medium 2 x 1.6 GHz 3.5 GB 490 GB High $0.24
Large 4 x 1.6 GHz 7 GB 1,000 GB High $0.24
Extra large 8 x 1.6 GHz 14 GB 2,040 GB High $0.96

As explained in this video, Extra Small Instances share resources (CPU, memory) with other VMs on the same node. Furthermore, the network bandwidth is capped at around 5 Mbps. This is not the case with larger instance sizes, where CPU and memory are not shared and your service can leverage unused bandwidth.

I believe this is a very good idea. Amazon’s smallest Windows instance (Micro Instance) is available at a cut-price $0.03 per hour, but we can’t compare these offerings 1:1 because Azure offers more functionality. We don’t have to pay extra for load balancing services and we don’t have to worry about OS updates etc. Besides, Azure’s Extra Small instance has 155MB more RAM, which could make a lot of difference.

This is why I like this new instance size so much: It means that it just got easier to get a small service running without downtime. By that I mean that I can now pay 2 extra small instances for a small service which gives me the ability to enable rolling upgrades without downtime. This includes automatic OS updates as well as my own updates to my service when delivering new features. This is still cheaper than having one small instance without all these benefits. I would expect this to activate the SLAs also, but I’m not sure about that. This won’t be the case while this feature is still in beta.

Follow

Get every new post delivered to your Inbox.