Lightswitch: custom ribbon button

Two weeks ago, on July 26th, Visual Studio Lightswitch 2011 was released. I ‘d seen a couple of videos what you can do with Lightswitch so I though I’d put it to the test by developing a replacement for a tool I use at one of my clients. Lightswitch is really easy to use and I believe I can actually teach my wife to create data-centric application using it. Until you reach the limits though, because than it becomes more difficult really fast. The main reason for this is that there’s not much documentation available on the inner workings of Lightswitch and how to hook into some of it. One of the things I ran into was how to add my own button to the ribbon that is available on every screen, like the default Save and Refresh buttons are (unless you explicitly set them not to be visible on a screen).

Extending Lightswitch applications

Like with many things, if you know how to do it, it’s not that hard. Lightswitch makes heavy use of the Managed Extensibility Framework, MEF. To extend the default behavior of Lightswitch you need to implement certain interfaces and export your implementation using the MEF Export attribute. There are multiple places your extension could live:

  • A Lightswitch Extensibility solution
  • A Silverlight class library
  • In the Lightswitch application itself

The Microsoft preferred place if the Lightswitch Extensibility solution, but I believe that’s overkill if you just want a button specific to the application you’re building. The Lightswitch Extensibility solution is a perfect way to build extensions for Lightswitch that you want to reuse for multiple applications, e.g. a certain shell style of theme for the company you work for. To create a Lightswitch Extensibility solution, you need to have the Lightswitch Extensibility Toolkit, available here. Note that you also need Visual Studio 2010 Pro and the Visual Studio 2010 SP1 SDK in order to use the toolkit.

The Silverlight class library is a good option if you have extensions specific to your application. It works the same way as extensions in the Lightswitch application itself, but makes for a better separation of generated and custom code.

The last option is good if you want a quick extension to your application. In this example I use this method because it’s the easiest to demonstrate how it works and allows to focus on the task at hand: adding a button to the ribbon that is available on all screens.

Adding a class file to the Lighswitch application

It may sound easy to add a class file to the Lightswitch application, but if you don’t know how to do it, it can be quite a challenge. The thing is that a Lightswitch application behaves differently in Visual Studio. It isn’t a normal project with class files, folders and custom controls. It’s a logical view of your application that hides all the generated code from you. But there’s a way to switch to the view which does show the various projects and files that make up your application. In the button strip on the top of your solution explorer, there’s a button on the far right that allows you to toggle between the logical and the file views.

image

Once you switched to the file view, you see your application is made up by a Client, Common and Server project, where the Client project contains your Silverlight app, the Server project contains all server related stuff like data access and the Common project contains the things shared between the Client and Server project. You can go one step further by choosing to show all files. This is also a button on the button strip on top of your solution explorer. If you toggle to show all files, you also get to see the ClientGenerated and ServerGenerated projects. This is used for example if you need to change a connection string in the web.config, which is located in the ServerGenerated project.

image

Since the button needs to be added to the Silverlight client, this is where we add the class file. Right click the Client project and choose to add a class. Name it MyGroupProvider.cs. I’ll explain later why we call it a provider.

Steps to add a custom button

Adding a custom button to the ribbon that is available on all screens involves the following steps:

  • Create a class that implements IExecutable for executing code when the button is clicked
  • Create a class that implements IShellCommand which is our button
  • Create a class that implements IShellCommandGroup which is the group for the button
  • Create a class that implements IShellCommandGroupProvider that acts as the provider for MEF so Lightswitch can find our button.

Implement IExecutable

The class that implements IExecutable is responsible for executing code when the button is clicked. This interface could be compare to the Silverlight ICommand interface but with some editions. The interface provides properties through which Lightswitch determines if the executable can be executed and methods for executing the code. In addition to the ICommand interface, the IExecutable interface allows for synchronous and asynchronous execution, allows cancellation of an asynchronous execution and provides a way to handle errors with the execution.

Create a class named MyExecutableObject and implement IExecutable. For the executable to work in the ribbon, you need to change the CanExecuteAsync to return true and implement ExecuteAsync to execute the code you want, e.g. showing a screen. The synchronous CanExecute property and Execute method are not used in this case, although I don’t know where they would be used. Make sure to return null in the ExecutionError property and return Microsoft.LightSwitch.ExecutionState.NotExecuted for the ExecutionState. Of course you can add your own logic to determine whether the executable can be executed or handle the errors the way you like.

public class MyExecutableObject : Microsoft.LightSwitch.IExecutable
{
    public bool CanExecute
    {
        get { return false; }
    }

    public bool CanExecuteAsync
    {
        get { return true; }
    }

    public bool CanExecuteAsyncCancel
    {
        get { return false; }
    }

    public void Execute()
    {
        throw new NotImplementedException();
    }

    public void ExecuteAsync()
    {
        // You code here
    }

    public void ExecuteAsyncCancel()
    {
        throw new NotImplementedException();
    }

    public event EventHandler<microsoft.lightswitch.executecompletedeventargs> ExecuteCompleted;

    public Exception ExecutionError
    {
        get { throw new NotImplementedException(); }
    }

    public Microsoft.LightSwitch.ExecutionState ExecutionState
    {
        get { return Microsoft.LightSwitch.ExecutionState.NotExecuted; }
    }
}

Implement IShellCommand

Now we have a class that implements IExecutable, we need to create a button through which the user can execute it. A button is a class that implements the IShellCommand interface. It allows you to specify a description for the button as well as a name. The ExecutableObject needs to return a new instance of the MyExecutableObject we just created. Furthermore, to be able to use the button, we need to make sure it’s enabled and visible. To create the button, create a new class named ‘MyCommand’ and implement the IShellCommand interface. Make sure to change all property and method bodies to do something and not throw an NotImplementedException.

public class MyCommand : IShellCommand
{
    public string Description
    {
        get { return "This is My Command"; }
    }

    public string DisplayName
    {
        get { return "My Command"; }
    }

    public Microsoft.LightSwitch.IExecutable ExecutableObject
    {
        get { return new MyExecutableObject(); }
    }

    public string Group
    {
        get { return "MyGroup"; }
    }

    public ImageSource Image
    {
        get { return null; }
    }

    public bool IsEnabled
    {
        get { return true; }
    }

    public bool IsVisible
    {
        get { return true; }
    }

    public bool ShowSmallImage
    {
        get { return false; }
    }
}

You can specify an image for the button by returning a BitmapImage using an image resource. For this you add an image to the Resources folder of the Client project. Then you use the following piece of code to return the image.

return new System.Windows.Media.Imaging.BitmapImage(
    new Uri("/DeploymentSettingsManager.Client;component/Resources/import1.png", UriKind.Relative));

Implement IShellCommandGroup

As of the time of writing I don’t know how to add a custom button to the built-in Data button group, so we’ll create our own group to host our button. We create a new button group by creating a new class that implements the IShellCommandGroup interface. This interface lives in the Microsoft.LightSwitch.Runtime.Shell.ViewModels.Commands namespace, so make sure to add a using for it.

Implement the interface by right clicking the interface and choosing ‘Implement Interface’. It will generate three properties for you: Commands, DisplayName and Name. Replace the getters of the DisplayName and Name to return the names you’d like to use for your command. The commands property returns a collection of the commands available in the group. In this case we only return our MyCommand. You can construct a collection or use the ‘yield’ keyword as in the example below.

public class MyGroup : IShellCommandGroup
{
    public System.Collections.Generic.IEnumerable<IShellCommand> Commands
    {
        get { yield return new MyCommand(); }
    }

    public string DisplayName
    {
        get { return "My Group"; }
    }

    public string Name
    {
        get { return "MyGroup"; }
    }
}

Implement IShellCommandGroupProvider

You now created you executable, the button and the group. The last thing to do is make sure Lightswitch know about it, so it can add it to the ribbon. To do this, we use a class that implements the IShellCommandGroupProvider class. Create a new class named MyGroupProvider and imlement the IShellCommandGroupProvider interface. Make sure the GetShellCommandGroups method returns the MyGroup class, since that is the group we want to make available to the Lightswitch application.

To allow the Lightswitch application to discover the group provider, add an Export attribute to MyGroupProvider class with parameter ‘typeof(IShellCommandGroupProvider)’. The Export attribute is a way for MEF to export definitions in your class library or application, which can be imported elsewhere using an Import attribute. MEF scans the application for all Export attributes and makes them available. The parameter for the Export attribute allows MEF to create filters on the import, so that only particular types are imported. The Lightswitch application imports types that implement the IShellCommandGroupProvider and knows what to do with it. This way Lightswitch can discover our command groups and add them to the ribbon.

[Export(typeof(IShellCommandGroupProvider))]
public class MyGroupProvider : IShellCommandGroupProvider
{
    public IEnumerable<IShellCommandGroup> GetShellCommandGroups(Microsoft.LightSwitch.Client.IScreenObject currentScreen)
    {
        yield return new MyGroup();
    }
}

Now if you run your application you’ll see your button added to the ribbon. Once this is working, you can continue to modify the properties of your button, group and executable to do what you want.

image

Windows Phone 7 Mango features

A lot has been said and written about Windows Phone 7 Mango. The eagerly awaited update to Microsoft’s new Windows Phone platform is said to sport 500 new features, bringing it up to par with its competition. While 500 features sound a lot, it may well be achieved if you count every little detail. Many of the bigger features can be found all over the web, especially in the much detailed Engadget in-depth preview. However, a comprehensive list showing all new features hasn’t been published yet. The table below is my attempt to sum up all the features I have found using my own phone with the Windows Phone 7 Mango beta for developers and browsing the Internet. I focused on the consumer features and left out the features available to developers, like e.g. raw camera access or the calendar API. If you think I missed some, please let me know and I’ll add them. Click on the image for a larger view.

image

MIX11: Day 3

It’s a wrap, MIX11 is over. Yesterday was the last day of MIX and many people have already returned to their homes. There was not much news to be shared, but here are my findings anyway.

Designer and Developer: A Case for the Hybrid (Jeff Croft)

In this talk Jeff Croft talks about what makes good designers and developers. His statement is that designers should know how to program and developers should know how to design. He doesn’t mean a designer actually needs to know how to program, but the way of thinking as a programmer is what’s important. I think he has an interesting view here and I do actually agree.

NuGet in Depth: Empowering Open Source on the .NET Platform (Scott Hanselman, Phil Haack)

This was by far the most entertaining session all week. And what else do you expect of the HaaHa show? Except of all the fun stuff going on, NuGet also seems like a really great addition to Visual Studio, even for enterprises. NuGet is a package manager that integrates with Visual Studio (but also works outside of it from command line) that enables you to find and include open source project very easily. Without NuGet you would Google the open source project with Bing, go to the website, look for the download, pick the right version, download it and finally install it. With NuGet you search for the package from within Visual Studio by typing a few keywords and then just click install. The package manager automatically adds references to the DLLs, imports dependencies if necessary and can do al kinds of additional stuff, like modifying the web.config. For enterprises this could be interesting too, where if you needs to reference assemblies of other teams within the organization, it makes it easier to discover them and keep them up to date.

Some fun stuff from the session, that Scott showed right before the start:

Enhanced Push Notifications and Tiles for Windows Phone (Thomas Fennel)

Thomas talked about the enhancements Microsoft did to the push notifications and tiles for Windows Phone. The push notification have been enhanced regarding reliability and performance, so that updates can come quicker on non-persistent friendly networks. About 15 minutes it would take at max. For persistent friendly networks the push notifications are instant.

The tiles are enhanced so they now also support background info. If you provide this background info, the tile will animate a flip on the home screen. The flip is asynchronous with other tiles, so it creates a dynamic feel. It’s now also possible to update the tiles directly from the application or using a background agent, making it easier to have dynamic tiles. Last thing is that you can create multiple tiles per application, so you can pin information from your app and allow deep linking into your app.

Advanced Features in Silverlight 5 (Nick Kramer)

Many of the features from this talk we already seen really quick in the keynote, but I want to highlight a few that were not so clear.

  • Silverlught 5 supports trusted applications in the browser. To use this feature you still need to enabled trusted app in the out-of-browser settings (awkward, as Nick mentioned himself), sign the XAP with a certificate and have the certificate installed on the client machine. When you do testing on localhost, it’s not required to sign the XAP.
  • Silverlight 5 comes with P/Invoke, allowing you to call directly into Win32 APIs. The advantage of P/Invoke over COM+ for Win32 APIs is that it’s strongly types and doesn’t required COM registration. This feature is not available in the beta and obviously not available on Mac either.
  • Silverlight 5 supports the WebBrowser control now also in the browser
  • Silverlight 5 can run in a 64 bit process. This is important because you have no control over the browser a user uses or if you need a lot of address space.
  • The PivotViewer control ship as part of the Silverlight 5 SDK, but is not available in the beta. They made it easier to use your data with the PivotViewer since you don’t need to create specific cxml files anymore. The visuals are also XAML-based now, where they were bitmaps before.

Last announcement is that Silverlight 5 ships second half of 2011.

Just one day left in Las Vegas to enjoy myself. Maybe we go down town or hang out in the shark reef pool, we don’t know yet.

MIX11: Day 2

Today was a really interesting day, with lots of new stuff being announced and sessions packed with interesting information. These are my findings of this day.

Keynote (Joe Belfiore, Scott Guthrie)

The keynote started off with an inspiring viral video. It appears a fan of Windows Phone created it by request of Microsoft after he created his own viral out of love of the phone. If the viral gets over 200k of views on YouTube, it is turned into a real commercial. Support this by watching the video here.

Joe went on talking about the next version of Windows Phone, codenamed Mango. It will be on new phones fall this year and includes 16 more languages, more countries for app creation (38 instead of 30) and more countries for app commerce (30 instead of 16). This includes the Netherlands.

Mango has a lot of new features and Joe showed a lot of them. The new features include:

  • App jump list, just as you’re used to with contacts, to quickly find the installed app you’re looking for
  • App list search to find an installed app, which can also directly search the marketplace
  • The marketplace was redesigned to have separate pivots for reviews and related apps, making it easier to navigate
  • Once you install an app from the marketplace, you’re taken to the app list directly and there you can see the app being installed
  • Added extras pivot on music and video hub showing apps that integrate with the hub
  • Full IE9 engine built-in to the OS
  • The address bar of the browser is moved to the bottom to free up more screen real estate. It is also available it landscape mode now.
  • Because it uses IE9, it supports HTML5
  • The HTML5 audio tag allows playing audio in the background, even if you leave the browser
  • Live tiles now allow animation, multiple live tiles per app and can be updated without the push notification service
  • Live tiles support deep linking into an app, allowing you to directly jump to a specific part of the app
  • Sockets are now available allowing apps to be built like the demoed mIRC app
  • There’s a built-in SQL CE database available to your apps, making it easy to store data locally, e.g. for caching
  • There are more launchers and choosers available for choosing things like contacts, images. You can also now jump directly into locations (Bing maps)
  • Additional sesnor access available, like raw camera, compass and gyro access
  • Custom ringtones can be created by applications
  • A motion sensor API, making it easy for developers to leverage the compass and gyroscope to write motion oriented apps without caring too much about the tedious math involved
  • Multi-tasking for audio, downloads, alarms and custom tasks
  • Fast app switching, which makes returning to apps lightning fast and allows you to see what apps are kept in the background in a dormant state (this could be compared to ALT+TAB on Windows)

A couple of announcements were made while demonstrating the new features, like:

  • Skype to come to WP7 this fall, when Mango is released
  • Spotify to come to WP7 in the near future
  • Angry Birds coming to WP7 on May 25th
  • Kik messenger available the coming weeks, finally providing a good cross platform messenger
  • The updated developer tools for Mango are available next month

Joe hands over to Scott Guthrie, who talked about developer enhancements for Windows Phone 7.

Scott kicks off with showing enhancements to the emulator that enable you to emulate the accelerometer and locations. The accelerometer emulation works by showing a 3d model of the phone and a pivot point you can grab with your mouse that allows you to mouse the model of the phone. The locations allows you to place points on a map that are directly forwarded to the phone as geo locations. Both emulations also allow recorded actions to be repeated, like shaking the device of moving along a certain path.

Next up Scott demoed the out-of-the-box performance analysis tools, that allow you to get very detailed information on the performance of you app over time. Once the new SDK comes out it should even work on current WP7 apps.

The team also made additional performance optimizations to the platform that don’t require you to write any additional code. As I understood it, the only thing you need to do is recompile the app. The performance optimizations include:

  • Scrolling and input is much smoother and doesn’t block the UI
  • Image decoding is done off the UI thread, which makes sure the UI isn’t blocked when you need to load a list of images
  • Garbace collection is improved so that it occurs more times, so that it does need to do less work and is scheduled to occur when your app is idle
  • Memory usage is improved so your app consumes about 30% less memory, again without writing a single line of code

Mango includes 1500+ new APIs. It uses the full Silverlight 4 feature set, so it leverages those features too, like sockets. It now also allows you to combine Silverlight with XNA, so you can use all the 3D glory in your Silverlight app.

Up next: Silverlight 5. Also on the field of Silverlight 5 news is available. To start of with, Silverlight 5 gets hardware based video decoding, bringing 1080p video to netbooks. They also added something they call ‘Trickplay’ that allows you to speed up or slow down a video, but with pitch correction, so voices don’t sound like Alvin & the Chipmunks. Lastly, on the media part, they also added remote control support. All these additions make Silverlight the premier platform for streaming media.

John Papa continued to show off some new 3D features of Silverlight 5. Het showed a Silverlight application that uses the XNA APIs to show a 3D model of a house. He demoed 2D to 3D projection, which allows you to take 2D Silverlight controls and project them against a 3D model, so that the 2D control aligns with the model. The source code of all this is available next month.

Some additional new features include:

  • Binding in Style setters, so that you can alter styles at runtime
  • Implicit data templates, allowing you to specify a data template for e.g. a list box based on the type of the bound object. When you do this, the template is applied everywhere in your app where that type of object is bound
  • Data binding debugging, allowing you to set a breakpoint in XAML and see detailed information about the binding

The Silverlight 5 beta is now available here.

Finally Jeff Sandquist came on stage talking about Kinect and how many they sold (over 10 million). His announcement was something I was looking forward too since yesterday when I noticed a lot of Kinects on stage: the Kinect SDK will be released later this spring.

His talk continued to show all the cool things you can do with Kinect and the SDK, like a sofa on wheels! Check them here.

Building In Browser Experiences With Silverlight 5 (Steve Lasker)

In this session, Steve dove a little deeper into many of the new Silverlight 5 features. Not all features are available in the Silverlight 5 beta yet. One of them is vector based printing, something that wasn’t announced at the keynote yet. In Silverlight 4, printing is done by converting the control to be printed to a bitmap which is then sent to the printer. This is not so efficient since these bitmaps can become very large and printing becomes really slow. It also defeats the possibility to print to PDF since all you get is a bitmap inside a PDF. With vector based printing the vectors are sent to the printer, so no more bitmaps when not necessary.

Get Ready For Fast App Switching In Windows Phone (Adina Trufinescu)

In this session Adina talked about how fast application switching works and what you need to do to leverage it. In the current version of WP7, when the user presses the back or Windows button when in your app, the app is deactivated and then tombstoned. The the deactivated phase you can store the state of the application before it gets killed. When the user returns to your app, it is activated and then running. In the activated phase, you can restore the state you saved earlier during the deactived phase.

In Mango, the app doesn’t get tombstoned directly after the deactivated phase. Instead it enters a new state called ‘Dormant’. In this state, the app is kept in memory as is. As long as there’s memory available it stays there, but as soon as the OS needs more memory, e.g. another app is started, the app can be tombstoned anyway. The difference with the previous method is actually in the activated phase. In this phase you now need to check whether the app was dormant or tombstoned. Only in the latest case you need to reload the state. You can see if the app was dormant if the new property IsAppInstancePreserved equals true.

It might be you need to do additional work in the activated phase. Because of resource usage, the phone OS terminates things like timers, access to camera, audio etc when the app enters the deactivated phase. In most of the cases, the OS resumes these things, but not in all. For e.g. if you have a MediaElement on your page, you need to write some code to resume it, since the OS doesn’t do it for you.

What’s New In The Windows Phone Developer Tools (Vibhor Agarwal)

This session was a total let down, since it was exactly the same as what Scott Guthrie already talked about during the keynote.

Crafty UX (Sara Summers, Nathan Moody, Robert Tuttle and Guido Rosso)

This was again a UX Lightning series, where there were four speakers and each had exactly ten minutes to do their talk. Although not as inspiring as yesterdays UX Lightning series, it was still fun. One thing that I noticed was the difference in ideas of the speakers. Where one said you should stay away from the computer at all when you’re prototyping, another said you should create experiences that are really close to the final result by doing videos etc. One thing I got from this session was: It doesn’t matter how you prototype, but please, do something. Don’t start building right away.

Multitasking In The Next Version Of Windows Phone, Part I (Darin Miller)

Another really interesting session where Darin explained the multitasking model and the choices Microsoft made and why. Microsoft wants to support multitasking, but on the other hand be careful with the resources of the phone, like battery and network usage. It is always a balance between user experience and health.

There are a couple of system services for doing multitasking, or background work rather. These are:

  • Alarm and Reminder, allowing you to pop up an alarm or reminder just like the rest of the phone does. They are persisted across reboots and can be turned off by the user. To add an alarm or reminder, you instantiate one in your app and call ScheduledActionService.Add() with the instance.
  • Background transfer service, allowing you to download or upload data in the background. Even if you’re just doing downloading or uploading in the foreground, this API is really useful. It has a download maximum of 20MB over the cell network, but allows more when connected to Wifi. If no Wifi is available, the download is scheduled and will automatically begin once connected to Wifi. Uploads are limited to approx. 3MB, but this needs validation by Microsoft. To schedule a background transfer, you instantiate a BackgroundTransferRequest and call ScheduledActionService.Add() with the instance.
  • Background audio, allowing you to play audio in the background just as Zune does. The simplest method is using the audio tag on a HTML5 webpage. The OnEnded trigger specified in the tag still fires, even if the browser is not open, allowing you to advance to the next track. The more advanced method is by using the BackgroundAudioPlayer class. This enables previous and next track functionality in the menu when you press the volume rocker on the phone. There are two methods: URL and Streaming where the latter allows you to decrypt / decompress the audio.

When you want to do more, you can write your own agent. An agent can do a lot of stuff, but not everything is allowed.

  • Allowed: Tile updates, Toast notifications, Location access, Network access, Read/Write isolated storage, sockets and most framework APIs.
  • Restricted: Displaying UI, access XNA libraries, access microphone, access camera, access sensors, play audio (except for background audio APIs)

There are two types of background agents: PeriodicTask and OnIdleTask. They are all persisted across reboots. There’s a limit of 18 agents in total, but this number might change as Microsoft is validating this number. An agent can be scheduled for 14 days. You could try to set it longer, but it will still run for just 14 days. After the 14 days the agent is stopped. Your app can renew this schedule. This method prevents agents to be running when the user is actually not interested in the app anymore. Again this is an example of caring about the resources of the phone.

Periodic agents are executed every 30 minutes and may take 15 seconds max to execute their work. Periodic agents are scheduled to run sequentially to reduce the total CPU load. They are also executed as close as possible next after each other to limit the network usage, since network connection needs to be made and released by the OS.

On idle agents are only executed on external power or with non-cell network. They are allowed to run for up to 10 minutes and can be user for heavier tasks, like initial data sync.

Today is already the last day of MIX11. I don’t expect a lot of new stuff today, but love to hear more about yesterdays announcements.

MIX11: Day 1

Today was the first conference day and my second day at MIX11. The day began with a keynote and after that a couple of sessions. These are my findings of today.

Keynote (Dean Hachamovitch, Scott Guthrie)

Dean started off with looking back at the development of IE9 and how successful is has been so far. Then he announced that they’re already three weeks into development of IE10, which didn’t come as a surprise looking at the shirt he was wearing with a bit TEN on it with the ‘E’ being the IE logo. The rest of his talk goes on showing the performance compared to ‘other’ browsers (it was Chrome) and how much the standards have conformed. I’m no big HTML fan and got the creeps when he showed al kinds of variations on riadial gradients for CSS3 (-ms-radial for IE, -moz-radial for Firefox, –o-radial for Opera, etc)

A great part of the demo was that in the end it appeared that the IE10 demos were actually running on an ARM 1.0Ghz machine and the performance was great. Dean’s talk concluded with the announcement that the first preview of IE10 is available immediately on IETestDrive.com

Next up was Scott Guthrie who talked about the web stack. As per today they release the ASP.NET MVC 3 Toolds Update which includes

  • JQuery 1.5 + Modernizr (a tool that automatically provides downward support of HTML5 constructs for HTML4 browsers)
  • HTML5 support
  • Entity Framework 4.1 support
  • Scaffolding

Also announced is that Entity Framework 4.1 (Magic Unicorn edition) is release final today.

The rest of Scott’s talk was about Orchard (yet another CMS), NUGet (a package manager for open source projects; this one is cool, but not completely new) and WebMatrix (kind of like Visual Studio for dummies).

The last bit of the keynote Scott talked about Windows Azure. There will be several new things coming soon, like a new access control service, a new caching service, added content delivery network support and traffic manager support. Umbraco (another CMS being around a little while) demoed an extension for Windows Azure that allows web admins to configure their site to automatically scale upon traffic during certain periods. This looks like a unique selling point for Umbraco and fairly easy to configure.

HTML5 for Silverlight Developers (Giorgio Sardo)

In this session I was expecting to get explained when to use what technology so a Silverlight developer like myself knows when HTML5 is a better option compared to Silverlight. Unfortunately, Giorgio pointed out all the similarities between HTML5 for most of the session. For example, he took a duck crafted in XAML with Expression Design and showed how ‘easy’ it was to convert that to AVG (the vector format for HTML5). These conversions involved a lot of copy paste and custom built tools which showed again that tool support for HTML5 is lacking and should be priority one if they want Silverlight developers to be interested.

Deep Dive MVVM (Laurent Bugnion)

I doubted a lot if I would go to this session since I didn’t know exactly what deeper one could go with MVVM. Much deeper as it turned out. Laurent’s session overall was too much code and jumping back and forth between screens, files and tools to be able to follow it well. He assumed a little too much that attendees used MVVM Light before and also are comfortable with terms like IoC (Inversion of Control). His basic message was one of interest though, which is if you want to improve MVVM in your application and want to get rid of some tight coupling like e.g. you have with dialogs, you should use dependency injection and/or behaviors. He showed how these technologies can help you removing any of the tight coupling and keep you ViewModels testable.

Inspiring UX (Thomas Lewis, August de los Reyes, Corey Schuman and Chris Bernard)

This was by far the most inspiring session so far. The idea behind the session is that every speaker has just ten minutes for their talk and their slides are timed and transition automatically. It was a great joy to see how well all speakers were able to time their words just right, where August’s talk topped everything by keeping in sync with every word on his slides. Besides the format, the contents of the talks was also interesting. When we walked out of the room we were inspired to do more with UX and felt that event the most boring battleship grey forms we work with on a daily basis could be improved to make it a pleasant experience for the user.

Today is day 2 of MIX11 and we expect some serious announcements regarding Kinect and Windows Phone 7. Why Kinect? Well, we noticed about six of them were lined op on stage yesterday during the keynote. Will the Kinect SDK be released today?

MIX11: Boot Camps

Today was the preconference day at MIX11, which means boot camps for everyone that applied for them. There were options for the morning and afternoon boot camps and I chose the Silverlight and SharePoint & Silverlight boot camps. This is a brief summary of what I think were things of interest.

Silverlight boot camp

I didn’t came to this boot camp to improve my knowledge on Silverlight, but more because of the speakers: John Papa and Mike Taulty. I think they might be considered heroes in the field of Silverlight. As expected, the boot camp was planned well and packed with the basics for building line of business apps with Silverlight. Even for an experienced Silverlight developer there were interesting things as well.

Silverlight comes with two HTTP stacks: the browser HTTP stack and the client HTTP stack. The difference is that the browser HTTP stack is easier to use, but is limited in its functionality. E.g. the browser stack automatically marshals the callback to the UI thread so you don’t need to. The browser stack on the other hand only supports 200 and 400 status codes and all other codes are converted to any of these. The client HTTP stack supports the full HTTP protocol, but requires more complex code. Always go for the browser HTTP stack, unless you need specific features e.g. in the case of SOAP, WCF, put or delete operations etc. To choose for a specific HTTP stack you can either do it on a per call basis or use the WebClient.RegisterPrecix static method to define the HTTP stack to use for certain URLs.

This week SP2 of WCF RIA Services for Silverlight 5 will be released. New features in this release are:

  • DateTimeOffset, which allows the developer to explicitly specify a date time offset to use instead of the default one (by popular demand)
  • MVVM support, by generating client side classes that are more suitable for databinding than the current ones

In the near future we can expect Entity Framework Code First to be supported by WCF RIA Services, but it will be in the release after the SP2.

Alongside all the demos and information a few new small added features of Silverlight 5 were disclosed today:

  • DataContextChanged event is added, which allows you to respond to DataContext changes
  • Ancestor binding, which is derived from WPF and allows you to move up the control hierarchy and break out of the context of the (inherited) DataContext

SharePoint & Silverlight boot camp

This boot camp was particularly interesting because it explained what to keep in mind when combining SharePoint and Silverlight to achieve an improved user experience.

The announcement was made that the SharePoint and Silverlight training is available on MSDN here.

Things to keep in mind when building Silverlight for SharePoint are:

  • Use a consistent theme in both SharePoint and Silverlight so they both blend
  • Expose a JavaScript API, so SharePoint developers can interact with the Silverlight control
  • Provide down level support, so the site still works even if someone doesn’t have Silverlight installed
  • Tightly integrate with SharePoint, e.g. use the ribbon in combination with the Silverlight webpart

There are four ways to add Silverlight to SharePoint:

  • Upload a XAP file
  • Use the built-in Silverlight webpart
  • Use the Silverlight SharePoint webparts extension
  • Do it all by hand

The Silverlight SharePoint webparts (found here) is a great extension to the SharePoint solution project for Visual Studio, allowing you to easily add an Silverlight webpart. The steps to do this are:

  • Add a Silverlight application to the solution
  • Add a SharePoint solution to the solution
  • Add a Silverlight webpart project item to the SharePoint solution
  • Modify the config of the webpart to point to the XAP file

The SharePoint and Silverlight training contains code for a custom Silverlight webpart. One of the main reasons for using this webpart is because the default webpart has a timeout limit of 5 seconds, which means the Silverlight app needs to be running within 5 seconds or SharePoint kills it.

SharePoint 2010 exposes an OData service when using WCF Data Services. This allows for full CRUD operations from within Silverlight. The pros for this method are: the code is type-safe and intellisense is provides.

An other option to get to the SharePoint data is to use the SharePoint client object model. This client object model provides access to a subset of types and members contained in the Microsoft.SharePoint namespace from .NET, JavaScript and Silverlight. This means you can access lists and pages from within Silverlight just as you would when using the server object model. Pros for this method: flexible, code re-use.

That’s it for now, more tomorrow on the first conference day at MIX11. I think we can expect a few announcements / releases during the keynote. My thoughts are: Silverlight 5 beta and new Windows Phone 7 SDK with new APIs.

Advanced MVVM: Doing visual states properly

An important plus of rich internet applications is the potential user experience you can achieve by applying UX patterns. A part of this is the visual states and their transitions. A visual state determines what the user interface looks like at a certain point in time and the transitions describe how the application moves from one visual state to the other, many times using animations to enhance the experience.

image

The most obvious way when you’re unfamiliar with XAML is to change the visual state of an application by writing code to show or hide controls when events occur, like e.g. a button click. Besides that on many occasions it requires a considerable amount of code, it doesn’t fit properly with the Model-View-ViewModel pattern. Although the pattern doesn’t prevent you from writing code in the codebehind as long as it related to the View, the pattern encourages to do it as little as possible.

The next commonly seen approach from people that want to stick to the MVVM-believes is to show/hide controls by binding properties like Visibility and Opacity to the ViewModel. This works fine for simple visual states, but has a couple of downsides, such as hard to maintain when a lot of controls are part of the visual state change, no support for animations and lack of seperation between View and ViewModel.

The only real proper way of doing visual states with WPF or Silverlight (phone / desktop) is through the VisualState-property of controls and pages. Each visual state in the VisualStates-property has a set of deltas to the base visual state, like the change of opacity of a button to 100%. Each visual state can furthermore contain transitions to and from the state if required. You can write the XAML for the visual states and transitions by hand, but it’s more convenient to use Expression Blend for this. In Expression Blend there’s the States-tab on which you can create or edit the visual states of any control, even the default controls when using a custom template.

The process of creating visual states and transitions can be found on many places on the web. The difficulty, however, lies in triggering a visual state transition, which is done using the VisualStateHelper class from code in many of the examples you’ll find. If you’re doing MVVM this becomes cumbersome since you need to track the properties of the View and trigger the appropriate state changes from code.

imageThis is where behaviors come into the picture. Expression Blend 4 comes packed with a couple of behaviors that make it easy to do visual state changes without writing a single line of code. These are:

  • GoToStateAction
  • DataStateBehavior

GoToStateAction calls the VisualStateHelper.GoToState() when an event occurs. To what state to transition and on what event can be configured. DataStateBehavior acts as an if-else statement. In your ViewModel you expose a boolean property determining the state of your application. You configure through data binding to inspect this property and what visual states the application should go to when the value is either true or false. E.g. you can use this behavior for hiding / showing controls depending on user rights. On your ViewModel you define for example a CanEdit property of type boolean and using the DataStateBehavior you switch between the ReadOnlyState and EditableState visual states.

When you want more functionality, there’s also the Expression Blend Samples. Although the name suggests differently, the Expression Blend Samples contains some very mature additions to the default Blend behaviors and triggers. The package included the DataStateBehavior since Blend 3, which is now packed with Blend 4. The package also contains the DataStateSwitchBehavior, which, as its name suggests, acts like a switch statement. It’s basically the same as the DataStateBehavior, but with multiple possible values besides just true or false. To use this behavior you expose an enumeration property on your ViewModel and use the DataStateSwitchBehavior to switch to particular visual states for each of the enumeration values. You can use this for example with the application roles of your application, e.g. Guest, Contributor and Administrator.

<DataTemplate x:Key='User'>
      <Grid>
            <VisualStateManager.VisualStateGroups>
                  ...
            </VisualStateManager.VisualStateGroups>
            <i:Interaction.Behaviors>
                  <si:DataStateBehavior
                      Binding='{Binding IsLoggedIn}'
                      Value='True'
                      TrueState='LoggedInState'
                      FalseState='LoggedOutState'/>
            </i:Interaction.Behaviors>
      </Grid>
</DataTemplate>

Using the Sync Framework on Windows Phone 7

For a mobile platform, like Windows Phone 7, you may be required to allow an application to work even when there’s no data connection available. Doing so is not that easy. You need to manage state locally, synchronize changed data (one-way or duplex) and maybe even handle conflicts. Luckily Microsoft offers the Sync Framework which makes it easier for you to accomplish this by taking much of the required plumbing out of your hands completely. Currently there’s a community technology preview available of Sync Framework 4 (they skipped version 3 to be in line with other releases), Sync Framework 4 makes it even easier for clients to support synchronization because all synchronization logic has moved to the server.

The figure below shows the Sync Framework 4 architecture where the blue components are the ones provided by Microsoft and the orange components the ones you need to develop yourself. The Sync Logic block is the part that you can extend to allow for more granular control over de synchronization.

syncfx002

For synchronizing data, the Sync Framework makes use of the OData protocol. Since OData is an open standard all kinds of platforms are able to sync data with the Sync Framework. Out of the box the Sync Framework comes with a provider for SQL Server and SQL Azure. On the client the Sync Framework provides components for Isolated Storage so you can use sync without writing a line of code on both Silverlight for the desktop as Silverlight for Windows Phone 7.

In this article I’m going to demonstrate how to use the Sync Framework in your application for Windows Phone 7 by creating an application to manage a shopping list. As I was using the Sync Framework myself I ran into a couple of problems, so I will add my learnings as well.

1. Prerequisites

Before you can use the Microsoft Sync Framework, you need to install the framework itself. To obtain the framework please visit this page and download the file ‘Download Instructions.mht’. Once you open the file you are prompted with two steps. By following the first step you need to answer a few basic feedback questions before you are redirected to the Microsoft Connect site. Once you are transferred to the Microsoft Connect website, click on ‘Downloads’ menu option on the left. You’re now at the download page. Please read the description carefully. It tells you that you need to install the Microsoft Sync Framework 2.1 first before installing the 4.0 CTP. Choose the operating system version that is most appropriate to you. Note that when you’re running the 64-bit version of Windows you need to install the 32-bit redistributables of the Sync Framework 2.1 in order to test in Visual Studio.

Now you have installed the Microsoft Sync Framework, the next step in this sample is setting up the sample database. To do this, download the following SQL file and open and run it in SQL Server Management Studio. This will create a new database named ‘ShoppingList’ and polulate some sample data.

2. Generate Sync Configuration

The sync configuration describes what data you want synchronized. The configuration contains the name and location of the data store, what entities to synchronize and what filters to apply to the entities so you can limit what data is exchanged over the wire. The configuration is used in the next steps to provision the database and generate client and server code.

Since the sync configuration is an XML-file it’s off course possible to craft it by hand, but in this case we’re using the ‘SyncSvcUtilHelper’ tool to do it for us. This tool is limited in what it can do, so if you need more control over the configuration file you can always tweak it afterwards.

The ‘SyncSvcUtilHelper’ tool is a graphical user interface build on top of ‘SyncSvcUtil’ command line tool, which is meant to provision the database and generate code. Generating a sync config isn’t actually a functionality of the ‘SyncSvcUtil’ tool, but for easy of use it’s incorporated in the ‘SyncSvcUtilHelper’ anyway. You find both tools in the ‘bin’ directory of the Microsoft Sync Framework SDK installation directory, which is by default ‘C:\Program Files\Microsoft SDKs\Microsoft Sync Framework\4.0\bin’ on 32-bit and C:\Program Files (x86)\Microsoft SDKs\Microsoft Sync Framework\4.0\bin on 64 bit Windows.

Once you fire up ‘SyncSvcUtilHelper’ you’re presented with the main screen with 3 options:

  1. Generate or Edit Sync Configuration
  2. Provision or Deprovision
  3. Code Generation

syncfx003

By executing all these three steps in this order gives you all you need to be able to sync data between server and a Silverlight-based client. In this case you obviously use the first option to generate the sync configuration. On the first screen specify a file name for the sync configuration file. It’s best to save the configuration file in the same directory as the ‘SyncSvcUtilHelper’ since you’re going to need it in the subsequent steps and the tool defaults to this directory.

syncfx004

On the next screen you need to enter the details of the database that you’ll use to sync data with. Click on the Add button to add a new database. Enter the details of your database and click the Save button to add your database. Click the Next button to go to the next screen.

syncfx005

In this screen you define the synchronization scopes of our application. A synchronization scope defines what data to synchronize for that scope. You can have multiple scopes for different synchronization purposes. In this case you use just one scope and name it ‘DefaultScope’. To add a scope click the Add button and enter the scope name. For schema name, use ‘dbo’ and make sure you check the box in front of ‘Is Template Scope’ since a template scope allows us to apply filters. Click the Save button and then Next to continue.

syncfx006

Here is where you choose what entities (tables) you want to synchronize and on what columns you want to enable filtering. To choose the tables to synchronize, click the ‘Add/Edit’ button. In the new window select the database you’ve configured a few screens back and a list of tables is shown. Select all columns of both tables for syncing and enable filtering on the ‘Id’ column of the ‘User’ table and ‘UserId’ column of the ‘Item’ table. Click the ‘OK’ button to close the window and click the Next button to continue.

On the first screen you see when you chose step 2, you open the sync configuration file you created before. Since you only have one database and sync scope, they are selected by default, so you can just click the ‘Next’ button to continue.

syncfx007

The summary screen shows you the details of the sync configuration that’ll be saved to the file. Once you click the ‘Finish’ button, the file is created and the tool is closed.

3. Provision the database

Open the ‘SyncSvcUtilHelper’ tool again, but this time choose step 2, in which you’ll provision the database. By provisioning the database, additional tables are created for all the tables you configured in the sync configuration file. The additional tables store sync related information so the Sync Framework can calculate diffs and detect conflicts.

On the first screen you get once you chose step 2, you open the sync configuration file you created before. Since you only have a single sync scope and target database they’re selected by default. Click the ‘Next’ button to start provisioning the database.

syncfx008

If provisioning of the database was successful you can close the tool by clicking the ‘Finish’ button.

syncfx009

4. Create the Sync Service

A full Sync Framework solution consists of a Sync Service on the server that speaks OData and an offline context on the client for storing data offline and tracking changes. In this step you’ll create the Sync Service.

To do so you first need a web application to host the Sync Service. Fire up Visual Studio 2010 and create a blank solution (File > New Project > Blank Solution) and name it ‘ShoppingList’. Then add a new ASP.NET Empty Web Application to the ShoppingList solution, named ‘Web’. Add a reference to ‘Microsoft.Synchronization.Services.dll’ which can be found in the ‘Server’ directory of the Microsoft Sync Framework 4.0 installation directory.

Now you have an empty web application to host you need to create the sync service. To do this you use the ‘SyncSvcUtilHelper’ tool again, but this time choose step 3. On the screen you’re presented with open the sync configuration file and click the ‘Next’ button.

syncfx010

On the ‘Select code generation parameters’ screen, select ‘Server’ as the codegen target. Specify the ‘Web’ directory of your ShoppingList solution as the output directory. You can choose whatever language, namespace and output file prefix you like. I used the parameters as in the screenshot below. Click the ‘Next’ button to start the code generation.

syncfx011

If the code generation completed successfully you can close the tool and return to Visual Studio. In the solution explorer, click the button to show all files and include both DefaultScopeEntities.cs and DefaultScopeSyncService.svc.

Before you can use the Sync Service, you need to change a couple of lines of code. Right click DefaultScopeSyncService.svc and choose ‘View code’. Replace the body of the ‘InitializeService’ method with the following lines of code:

config.ServerConnectionString = @"Data Source=.\SQL2008;Initial Catalog=ShoppingList;Integrated Security=True;MultipleActiveResultSets=True";
config.SetEnableScope("DefaultScope");
config.AddFilterParameterConfiguration("userId", "User", "@Id", typeof(int));
config.AddFilterParameterConfiguration("userId", "Item", "@UserId", typeof(int));
config.SetSyncObjectSchema("dbo");
config.UseVerboseErrors = true;
config.EnableDiagnosticPage = true;

Lines 1 and 2 define the connection string to the database and which scope to use for synchronization.

Lines 3 and 4 are used to add a mapping for parameter ‘userId’ to the filters you defined when creating the sync configuration file. By using the same parameter name for both filters, the client only has to provide a single value to be able to filter both tables.

The lines 6 and 7 are only used for diagnostics and should be turned off in a production environment. UserVerboseErrors enables full errors to be send back to the client in case of an exception. This comes in handy when trying to find out why you’re service isn’t syncing properly. EnableDiagnosticsPage enables a page that shows you whether the basic server configuration is valid. This page is the first thing you check if you want to know if the Sync Service is working.

Now check if your Sync Service is working by right clicking ‘DefaultScopeSyncService.svc’ and choosing ‘View in browser’. The page should load correctly. Then change the ‘$syncscopes’ parameter in the url to ‘$diag’ and press enter. If all tests passed, except for the ClientAccessPolicy/CrossDomain files, you’re ready to continue to create the Windows Phone 7 client.

5. Create the Windows Phone 7 client

Add an empty Windows Phone 7 application to the solution. In this example I named it ‘ShoppingList’. Add a reference to ‘Microsoft.Synchronization.ClientServices.dll’ which can be found in the ‘Client\WP7′ directory of the Microsoft Sync Framework 4.0 installation directory. Also add a reference to the Silverlight 3 version of ‘System.ComponentModel.DataAnnotations.dll’. This assembly van be found in C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\ (32 bit) or C:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\ (64 bit).

In order to access the sync service and use the entities, you need to generate the client code. Start the ‘SyncSvcUtilHelper’ tool and follow the same steps as when generating code for the server. This time choose ‘IsolatedStore Client’ as the codegen target and specify the Windows Phone 7 application directory, ‘ShoppingList’. The ‘IsolatedStore Client’ generates code that uses IsolatedStorage for storing the synced entities and can be used for both Silverlight for the desktop as for Windows Phone 7. Click the ‘Next’ button to start the code generation.

syncfx012

If the code generation completed successfully you can close the tool and return to Visual Studio. Make sure the Windows Phone 7 project is selected and in the solution explorer, click the button to show all files and include both DefaultScopeEntities.cs and DefaultScopeOfflineContext.cs.

Now open up MainPage.xaml.cs and replace all the code with the following:

using System;
using Microsoft.Phone.Controls;
using Microsoft.Synchronization.ClientServices.IsolatedStorage;

namespace ShoppingList
{
    public partial class MainPage : PhoneApplicationPage
    {
        private DefaultScope.DefaultScopeOfflineContext context;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            context = new DefaultScope.DefaultScopeOfflineContext(
                    "ShoppingList",
                    new Uri("http://localhost/ShoppingList/DefaultScopeSyncService.svc")
                );
            context.CacheController.ControllerBehavior.AddScopeParameters("userId", "1");
            DataContext = context;

            context.LoadCompleted += context_LoadCompleted;
            context.LoadAsync();
        }

        void context_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            context.CacheController.RefreshAsync();
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            context.CacheController.RefreshAsync();
        }
    }
}

In lines 16 to 19 the DefaultScopeOfflineContext is initialized with the path in IsolatedStorage to store the offline data and the Uri to the sync service. In line 20 a parameter is added for the userId. For each client parameter name on the server you need to add a scope parameter on the client. In this case there’s just a single client parameter ‘userId’, which is mapped on the server to two table fields. In the sample data in the database there are two users you can try: IDs 1 and 2. In line 21 the DefaultScopeOfflineContext is set as DataContext so you can use it in the XAML bindings. In lines 23 and 24 an event handler for LoadComplete is assigned and the context is asked to load the offline stored data from IsolatedStorage. Once the offline data is loaded, the CacheController is asked to refresh, which calls the sync service to synchronize the offline data with the live data on the server. Once the sync completes, the data in the offline context is in sync with the server data, which is done in line 34.

Open up MainPage.xaml and add a ListBox to the ContentPanel Grid using the following piece of XAML. This creates a ListBox that binds to the ItemCollection propery of the DefaultScopeOfflineContext which contains the items in your shopping list. A CheckBox is used so you can mark the item as bought.

<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
        <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Sync" Click="ApplicationBarIconButton_Click"/>
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

Return to the MainPage.xaml.cs and add the event handler for the ApplicationBar button using the following piece of code. This makes sure any changes made by the user are persisted to the IsolatedStorage first and then start the synchronization.

private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
    context.SaveChanges();
    context.CacheController.RefreshAsync();
}

Now your application is ready to test! Make sure the Windows Phone 7 project is marked as startup project and then press ‘F5′ to start debugging. Once the application is started you should soon see a list of shopping list items. Try making changes on the client by marking an item as bought and click the sync button and notice that the IsBought value changed in the database. Also try adding additional items to the Item table in the database and notice the items appear in the list in the Windows Phone 7 client as soon as you click the sync button again.

syncfx013

Debugging a sync service

Having trouble with your sync service, but don’t have a clue what’s wrong? Debugging a sync service is a bit tricky. As you probably noticed during your own investigation, you can handle the RefreshCompleted event of the CacheController, but all you find when inspecting the Error property of the RefreshCompletedEventArgs is a ‘The remote server returned an error: NotFound.’. Before explaining how to do it, here are a few questions I compiled after stepping into a couple of common errors myself:

  • Open the Diagnostics page. Do all tests pass?
  • Did you provision the database? Re-provisioning doesn’t hurt, so just try it.
  • Did you add lines of code to the sync service code behind setting the connection string and sync scope name? When regenerating the server code, this file could be overwritten.
  • Did you add filter parameter configurations for all the filter parameters in your sync service config on the server?
  • Did you add parameters on the client for each parameter mapping on the server?
  • Are the names and types of the filter parameters on the server equal to the GlobalName values in your sync service configuration?
  • Does the account under which the sync service runs have access to the database in the connection string?
  • Did you specify the correct Uri on the client? Try the Uri in your browser to make sure it is correct.

If all of the above didn’t help it’s time to start debugging the sync service. For debugging you use a common HTTP-traffic monitor tool called Fiddler2. Download Fiddler2 and install it. Next start Fiddler2 and configure it to allow remote connections, as described in this blog post. You should be able to capture the internet traffic of the Windows Phone 7 emulator by now. Make sure you start the emulator after you started Fiddler2, so if it is running, restart it first. Open internet explorer on the emulator and browse to a particular website. Fiddler2 should show you the internet traffic.

Since the ASP.NET Development Service doesn’t allow remote connections and the emulator is regarded as a remote device, you need to configure the web application to run in IIS. Note: I assume you’re running Vista or Windows 7 and you already installed IIS 7. Open the properties of the web project and go to the ‘Web’ tab. Select to use the local IIS web server and specify a Url, see example below. Click ‘Create Virtual Directory’ to create the virtual directory if it doesn’t exist yet.

syncfx001

Fiddler2 doesn’t capture traffic going to localhost, so in order to capture your sync service traffic go to MainPage.xaml.cs in your Windows Phone 7 application and replace localhost with the computer name in the Uri to the sync service. Make sure the Uri points to the IIS hosted sync service.

In the DefaultScopeSyncService.svc.cs file in your web project, make sure you enabled UserVerbodeLogging by adding the following line of code:

config.UseVerboseErrors = true;

Now, if you encounter a synchonization error, go into Fiddler2 and lookup the faulted web session, which is indicated with status 500. Click the ‘TextView’ button of the response area (bottom right part of the screen) in order to see the plain error message that was transmitted over the wire.

syncfx014

Building a location aware Windows Phone 7 application

The Windows Phone 7 SDK contains a couple of APIs for interacting with different parts of the phone hardware, like accessing the camera or initiating a phone call. One of the cool APIs of Windows Phone 7 is the Location API. Just as in the desktop version of .NET Framework 4.0, the Location API enables you to get the approximate location of the user. To find the location of the user, the API uses GPS, WiFi or cell tower triangulation, where the first is the most and the latter least accurate. The API hides the method of determining the location for you as a developer and will attempt to use the most accurate available method. By default it uses cell tower triangulation, but if you tell it you need high accuracy it will try WiFi or GPS when available. For you as a developer you need to carefully determine the level of accuracy, since the more accurate method the slower and more power consuming it gets.

In this example I’ll show you how to use the Location API. First off I created a new Windows Phone application using the ‘Windows Phone Databound Application’ project template. You can use any of the project templates, but I chose this one because I like to use MVVM all the time. The next thing I do is changing the UI. Because I use the Bing maps control, make sure you reference the Microsoft.Phone.Controls.Maps.dll assembly. Also add a reference to the namespace to the MainPage.xaml, like this:

xmlns:maps="clr-namespace:Microsoft.Phone.Controls.Maps;assembly=Microsoft.Phone.Controls.Maps"

We will use a TextBlock to show the current estimated address and a Maps control to show your current estimated location on a map. Replace the complete contents of the ContentPanel Grid with the following XAML snippet. You may need to remove some code from the codebehind of MainPage.xaml because it references the ListBox we remove.

  <StackPanel>
    <TextBlock Text="{Binding Status}" />
    <TextBlock Text="{Binding Address}" />
    <maps:Map Center="{Binding Location, Mode=TwoWay}" ZoomLevel="13">
      <maps:Map.CredentialsProvider>
        <maps:ApplicationIdCredentialsProvider ApplicationId="&lt;YourKeyHere>"/>
      </maps:Map.CredentialsProvider>
      <maps:Pushpin Content="You are here" Location="{Binding Location}" />
    </maps:Map>
  </StackPanel>

In order to use the Bing maps control, you need your own key. Request a key on the Bing maps portal.

In the XAML I’ve used bindings to Status, Address and Location properties. These properties do not yet exist, so the next thing is to add these properties to the MainViewModel class in MainViewModel.cs. The Status property is of type GeoPositionStatus and contains the status of the GeoCoordinateWatcher, the Address property is a string containing the current estimated address and the Location property is of type GeoCoordinate, which is a type used to represent a lat/long position. The following code snippet shows you the three properties to be added to the view model:

private GeoPositionStatus _status;
/// <summary>
/// Contains the status of the GeoCoordinateWatcher to see if it is initializing, ready or not getting any data.
/// </summary>
/// <returns></returns>
public GeoPositionStatus Status
{
    get
    {
        return _status;
    }
    set
    {
        if (value != _status)
        {
            _status = value;
            NotifyPropertyChanged("Status");
        }
    }
}

private string _address;
/// <summary>
/// Contains the current estimated address as returned by the reverse geolocation web service.
/// </summary>
/// <returns></returns>
public string Address
{
    get
    {
        return _address;
    }
    set
    {
        if (value != _address)
        {
            _address = value;
            NotifyPropertyChanged("Address");
        }
    }
}

private GeoCoordinate _location;
/// <summary>
/// Contains the current estimated lat/long location as returned by the GeoCoordinateWatcher.
/// </summary>
/// <returns></returns>
public GeoCoordinate Location
{
    get
    {
        return _location;
    }
    set
    {
        if (value != _location)
        {
            _location = value;
            NotifyPropertyChanged("Location");
        }
    }
}

Now that we’ve set up our UI and bindings, it’s time to start using the Location API. The Location API consists of two classes: GeoCoordinateWatcher and CivicAddressResolver, just like in the desktop framework. The GeoCoordinateWatcher does the heavy lifting of calculating the approximate lat/long of the phone, while the CivicAddressResolver translates the lat/long to a human readable address using reverse geolocation. Unlike the desktop version of the .NET Framework, the CivicAddressResolver isn’t implemented on the phone. Instead of throwing an exeption it will always tell you the address is unknown. This means we can’t use this class yet to resolve the lat/long to an address. Instead we will use the Bing web service for that, but more on that later.

In order to get the lat/long of our current position, we need to create an instance of the GeoCoordinateWatcher, subscribe to the StatusChanged and PositionChanged event and start listening for position changes. The following lines of code will do just that:

GeoCoordinateWatcher gcw;

public MainViewModel()
{
    Items = new ObservableCollection<ItemViewModel>();
    gcw = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
    gcw.StatusChanged += gcw_StatusChanged;
    gcw.PositionChanged += gcw_PositionChanged;
    gcw.Start();
}

void gcw_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
    Status = e.Status;
}

void gcw_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
    Location = e.Position.Location;
    Address = String.Format("{0}, {1}", Location.Latitude, Location.Longitude);
}

In other examples on the web you’ll find that most of the time also the StatusChanged event of the GeoCoordinateWatcher is handled to see if it is ready before listening for position changes. Because you could get a PositionChanged event before you’ve even received a StatusChanged event, it’s not very useful to do so and may cause you to miss the PositionChanged event. So be sure just to listen for the PositionChanged event and only use the StatusChanged event to display the status, like done in this example.

In this case I used the default constructor of the GeoCoordinateWatcher, which uses the default accuracy (which only uses cell tower triangulation). If I wanted, I could pass in GeoPositionAccuracy.High as a parameter, which tells the GeoCoordinateWatcher to use WiFi triangulation or GPS when available. The PositionChangedEvent gives you a property ‘HorizontalAccuracy’ which tells you, in meters, how accurate the detection of the position was and allows you to filter for specific accuracy. Note that when done indoors and without a WiFi connection, it won’t provide a better accuracy then the default, since only cell tower triangulation is available.

The event handler for the StatusChanged event updates the Status property and the PositionChanged event handler updates the Location property and takes the latitude and longitude and concatenates them into the Address property.

Now if you run the application in the emulator by pressing F5 (which is the default), you’ll notice that nothing happens and the status is ‘NoData’. This is because the emulator doesn’t emulate location data. There are two things you can do:

1) Simulate location data using this technique described by Tim Heuer.

2) Test on your Windows Phone. This requires your phone being developer unlocked.
clip_image001
If you have the possibility to test on a physical Windows Phone, I’d highly recommend it. During my tests it appeared the location data on the phone wasn’t what I expected. For instance, the GeoLocationWatcher was unable to find my location using cell tower triangulation as soon as I have HSDPA connectivity. This probably has something to do with the way HSDPA works. It also shows you that the GeoCoordinateWatcher may jump between NoData and Ready every now and then when e.g. connection is lost or the phone switches to a different type of connection.

As soon as you run the application on an actual phone you’ll see something similar to this:
clip_image002
Now that we’re able to obtain the lat/long of our estimated position, I’d like to translate the lat/long into an address I can understand. As mentioned earlier, we can’t use the the CivicAddressResolver class since it’s not implemented for Windows Phone 7. Instead we’ll use the Bing web service. In order to do this, add a service reference to the following URL:

http://dev.virtualearth.net/webservices/v1/geocodeservice/geocodeservice.svc
clip_image003
Adding the service reference also creates a new file ‘ServiceReferences.ClientConfig’ to your project. This file contains the WCF bindings required for calling the web service. By default it will add two end points: a SOAP endpoint (the first) and a Binary endpoint (the second). Because WCF can’t decide by itself which of the two to use, we remove the SOAP binding from the file.

Now we want to modify our code to call the ReverseGeocode service method once we receive a position update. In order to do so we modify the MainViewModel class. First we add a field of type GeocodeServiceClient. In the constructor we initialize the field and handle the ReverseGeocodeCompleted event. In the event handler we check if any addresses are returned and display the first found address. In the PositionChanged event hander of the GeoCoordinateWatcher, instead of setting the Address property using the lat/long values, we construct a ReverseGeocodeRequest using the Bind key we used earlier and the lat/long values and call the ReverseGeocodeAsync method. The changes to the MainViewModel are shown in the following snippet (changes are in bold):

GeoCoordinateWatcher gcw;
GeocodeServiceClient gsc;

public MainViewModel()
{
    Items = new ObservableCollection<ItemViewModel>();
    gsc = new GeocodeServiceClient();
    gsc.ReverseGeocodeCompleted += gsc_ReverseGeocodeCompleted;
    gcw = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
    gcw.StatusChanged += gcw_StatusChanged;
    gcw.PositionChanged += gcw_PositionChanged;
    gcw.Start();
}

void gcw_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
    Status = e.Status;
}

void gcw_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
    Location = e.Position.Location;
    var request = new ReverseGeocodeRequest();
    request.Credentials = new Credentials { ApplicationId = @"MyApplicationId" };
    request.Location = new Location { Latitude = e.Position.Location.Latitude, Longitude = e.Position.Location.Longitude };
    gsc.ReverseGeocodeAsync(request);
}

void gsc_ReverseGeocodeCompleted(object sender, GeoCodeService.ReverseGeocodeCompletedEventArgs e)
{
    if (e.Result.Results.Count == 0)
        Address = "No address found";
    else
        Address = e.Result.Results[0].DisplayName;
}

Now if we run the application, we don’t see the lat/long values, but instead see a readable address of our estimated location.
clip_image004
There are a couple of things wrong with this implementation. First, each time the position is changed a new web request is done to get the address, even if the location didn’t change (much). Second, if a web request is underway, it’s not cancelled, but instead a new web request is done. This could lead to a racing condition where the second request would complete before the first, resulting in the address of the first location being displayed. Third, the PositionChanged event keeps firing, even if the position doesn’t change. This costs unnecessary resources on the phone.

The third flaw could be overcome by using a MovementThreshold. MovementThreshold is a property on the GeoCoordinateWatcher and specifies the amount of movement is necessary before a new PositionChanged event is fired. A common MovementThreshold is one of 20.0, e.g.:

gcw = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
gcw.MovementThreshold = 20.0;
gcw.StatusChanged += gcw_StatusChanged;
gcw.PositionChanged += gcw_PositionChanged;
gcw.Start();

The first two flaws can be overcome by writing more boilerplate code, like starting timers and cancelling web requests. This could easily lead to hard to read code since it is all scattered around. A way to simplify things is to use Reactive Extensions, but that’s food for another blog post.

WCF RIA Services OData endpoint does NOT support update or LINQ

After struggling with WCF RIA Services v1 (Silverlight 4 RTM) to enable insert/update for the OData endpoint for use with Windows Phone 7, I finally figured it out. The current version of WCF RIA Services does NOT support update or LINQ! I think I searched for a couple of hours until I found the single line of information on this in this following Silverlight TV post:

NOTE: The ODATA endpoint has very limited support in V1. There is no Update or LINQ query support in this release.