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

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.

Honk twice if you see us!

Today I witnessed the arrival of eight Avanade branded Fiat 500 cars. They arrived in a single line in front of our main office, where they stand now. The orange / black color combination draws a lot of attention and enthousiasm. Together with the branding and racing stripes they form the perfect car for our core services team. Secretly, in our hearts, the customer facing employees, driving our big luxurous lease cars, would die to drive one of these babies ourselves.

*Update* Added a few extra photo’s in better quality.

  

Day 0: arrived in LA

Yesterday afternoon we (my collegues and I) arrived in LA. Purpose of visit: the Microsoft Professional Developer Conference 2008 (PDC’08). It promises to be a very interesting week with a lot of new stuff from Microsoft, including Windows 7, ‘Oslo’ and ‘Dublin’. After arrival we checked into our rooms, grabbed a slice of pizza, had a drink and went to bed. We tried to join the party by Jeffrey Pallermo, but the waiting time was about 40 minutes and we heard there was no more beer (no problem for me as non-alcohol drinking person, but some of my collegues seemed to mind :) ). Today will be the first real day of the conference which is kicked off by the keynote of Ray Ozzie and others. After the keynote we have plenty of sessions to choose from. Although I’m not yet sure about my planning for the day, it’ll probably look something like:

  • 8:30 AM – 11:00 AM  Keynote
  • 11:00 AM – 12:15 PM  Under the Hood: Advances in the .NET Type System
  • 12:45 PM – 1:30 PM  Microsoft Expression Blend: Tips & Tricks or “Dublin” and .NET Services: Extending On-Premises Applications to the Cloud
  • 1:45 PM – 3:00 PM  Identity: “Geneva” Server and Framework Overview or Developing for Microsoft Surface or The Future of C#
  • 3:30 PM – 4:45 PM  A Lap around Cloud Services Part 2
  • 5:15 PM – 6:30 PM  Developing and Deploying Your First Cloud Service

For the evening we have planned to go to the LA Kings ice hockey match in the Staples Center, next to the conference center. This looks like it’s gonna be a day full of fun and information.

Consume WCF service using Sharepoint Designer

By default the SharePoint Designer is unable to consume WCF services because it fails to recognize the structure of the request messages. There is a workaround if you still need to consume WCF services using the Designer. However, this does not work via the datasource wizard but instead requires some manual intervention. There are two methods to do accomplish this:

  • Modify the datasource
  • Modify the code in the page

The first method is easier to implement and gives you more control over the output. The only downside is that the WCF service must use a wrapped request message contract. This means that you either need full control over the WCF service so you can enable the request message to be wrapped, or you have to be lucky that the WCF service you’re trying to consume uses wrapped message contracts. From the WSDL it’s difficult to see if wrapped message contracts are used. If you’re not sure you can try the first method. If the Designer crashes as soon as you want to use the modified data source, the WCF service probably doesn’t support it. If you have full control over your service, the first method will also describe how te enable wrapped message contracts.

Method 1: Modify the datasource

To consume a WCF service in the Designer by modifying the datasource you perform the following steps:

  • Enable wrapped message contracts
  • Create a datasource using the wizard
  • Obtain request message by calling the service with Webservice Studio
  • Modify the soap envelope of the datasource

1.1 Enable wrapped message contracts

In this step you’ll set the IsWrapped property of the request message contract to True.

If you used Web Service Software Factory for creating your WCF service you can set the request message contract to be wrapped in the service contract model. Open the service contract model and select the request message contract. In the properties window of the message contract you change Is Wrapped to True. Save the model and generate the code for the service contract.

If you didn’t use Web Service Software Factory you can have the request message contract set to wrapped by modifying the MessageContract atribute. Open the file containing the request message contract and locate the MessageContract attribute. Make sure that the attribute does not set IsWrapped to False. If it does you can simply remove the property assignment or you set it to True, which is the default value. You can also give the wrapper a name and namespace if you like, but this is not required. In the end your message contract should look a little similar to the code sample below:

[sourcecode language="csharp"]
///

/// Service Contract Class – HelloWorldRequestMessage
///

[WCF::MessageContract(
WrapperName = "HelloWorldRequestMessage",
WrapperNamespace = "urn:HelloWorldService.ServiceContracts")]
public partial class HelloWorldRequestMessage
{
private string name;

[WCF::MessageBodyMember(Name = "Name")]
public string Name
{
get { return name; }
set { name = value; }
}
}
[/sourcecode]

Whether you changed the wrapped value using WSSF or directly in the code, you should make sure to rebuild your project.

1.2 Create a datasource using the wizard

In this step you’ll create a new datasource using the Sharepoint Designer wizard. Open Sharepoint Designer, connect to your site and go to the Datasource Library tab on the right side of your screen. Click on the Connect to a webservice link underneath the XML Web Services. In de dialog you enter the URL to your services endpoint and click the Connect Now button. The wizard will connect to your web service and present you a list of endpoints and methods. It doesn’t matter which endpoint or method you select here, because we’ll change that later. Click OK to exit the wizard and create the new datasource.

1.3 Obtain request message by calling the service with Webservice Studio

In this step you’ll obtain the appropriate request message for calling your webservice. Because the request message generated by the Sharepoint Designer wizard is incorrect you need to replace that with the correct one. For this purpose we’ll use Webservice Studio (http://www.codeplex.com/WebserviceStudio).

Before calling the web service you should make sure you have the URL to the service’s WSDL and that the service is running.

To call a web service you start Webservice Studio, type the URL to the service’s WSDL in the WSDL Endpoint drop down list and click on the Get button. Webservice Studio attempts to create a proxy for the WSDL it found at the specified URL.

Once the creation of the proxy is finished you are promted with the web service’s methods on the left. By clicking on a method the required input parameters are shown and you are able to specify their values.

Once you’ve specified the required parameters you can call the web service by clicking the Invoke button. The response of the web service is shown in the Output window if the call was successful. We then move to the Request/Response tab to be able to view the raw request message. Copy the soap:Envelope record of the request message and store it somewhere so we can use it in our next step.

1.4 Modify the soap envelope of the datasource

In this step you’ll modify the XML Webservice datasource of the Sharepoint Designer.

To access the datasources you need to be connected to your site using the Sharepoint Designer. In the site’s tree you navigate to _catalogs\fpdatasources. This directory contains xml files with the datasource configurations. Open the xml file that has the name of your service. The contents will look similar to this (reformatted for better reading):

[sourcecode language="xml"]


HelloWorldService












]]>



[/sourcecode]

The soap:Envelope part is what we’re interested in. Replace the complete soap:Envelope with the soap envelope you obtained using Webservice Studio. Now your datasource will look similar to this (reformatted for better reading):

[sourcecode language="xml"]


HelloWorldService








Sander





]]>




[/sourcecode]

Note that the soap:Body is completely different from what the Designer’s wizard gave you. After modifying the soap:Envelope you can save the changes to the datasource. Refresh the list of datasources in the Datasource Library and use the datasource like you would any other. Be careful not to reconnect the datasource using the wizard because that would render it unusable again.

Method 2: Modify the code in the page

To consume a WCF service in the Designer by modifying the code in the page you perform the following steps:

  1. Obtain request message by calling the service with Webservice Studio
  2. Complete DataFormWebPart XML
  3. Paste XML in WebPart

2.1 Obtain request message by calling the service with Webservice Studio

This step is the same as in the previous method.

2.2 Complete DataFormWebPart XML

After obtaining the request message of the web service we can complete the XML of a DataFormWebPart. Below is the basis of the DataFormWebPart. Have a look at the structure and then continue reading on how to complete it.

[sourcecode language="xml"]



WsdlPath="http://localhost:3391/MeteringPointService/MeteringPointService.svc?wsdl"
SelectUrl="http://localhost:3391/MeteringPointService/MeteringPointService.svc"
SelectAction="urn:ASBusinessServices.ServiceContracts.MeteringPointServiceContract.GetMeterDetails"
SelectPort="MeteringPointServiceEndpoint"
SelectServiceName="GetMeteringPointDetails">






{MeteringPointName}
{MeterName}

























'






[/sourcecode]

The SharePoint:SoapDataSource contains a couple of attributes that need to be set. The first is the WsdlPath, which is the same path as you used in Webservice Studio. Then there’s the select path, which in most cases is almost identical to the WsdlPath with ‘?wsdl’ removed from the end. The SelectAction is the soap action of the method you’d like to call. If you’re uncertain what this value should be, you can look it up in Webservice Studio, on the left side of the Request/Response tab. SelectPort is the name of the endpoint of the service. This is specified in the Wsdl as the name of the binding to which the operation belongs. The last attribute is the SelectServiceName attribute. It’s value is the name of the method. If you’re unsure of the values of the latter two attributes, you can use the add XML Webservice wizard to obtain them.

A little below the SharePoint:SoapDataSource you find the SelectCommand. The SelectCommand should contain the soap envelope you’ve obtained using Webservice Studio. You can substiture the values of the parameters by variable names enclosed by braces. This allows the value of the parameter to be set via Web Part connection. In you do this you should also make sure to add the parameter to the SelectParameters and ParameterBindings collections.

The last thing you probably want to do is to modify the XSL for the desired output. This is pretty straightforward if you’re familiar with XSL. If not, there’s a lot of content out on the web to help you get started.

2.3 Paste XML in WebPart

All the hard work is done in the previous steps. The only thing to do now is to copy the completed XML from the previous step and paste it inside a WebPart. The easiest way to do this is by selecting the split view in the SharePoint Designer and then clicking on a WebPart. This selects the code of the WebPart. Find the tags and paste the XML between them. Once you save the document it will update the design and call the WCF service.

Better WSSF solution structure

I’ve done my share of work with the Web Service Software Factory modelling edition, but never have I liked the solution structure it generates for me. Or either the namespaces of the projects are wrong, or the paths became too long because of the fully qualified names I’d use. This time I reserved some time to tackle this once and for all. The result is an easy to apply patch for WSSF: Modelling Edition.

What does it do:

  • Does not add the service name to each project but name them simply BusinessEntities, ServiceImplementation or DataContracts
  • Let the user choose his own namespace, which is then added to each project name. E.g. a user chooses the namespace MyCompany.MyProduct. The BusinessEntities project then gets the namespace MyCompany.MyProduct.BusinessEntities.
  • Names the host application after the service instead of just ‘Host’

What doesn’t it do:

  • It doesn’t change the assembly name. There seems to be a bug in the templating system of Visual Studio so the AssemblyName property of a template project is always set to the project name. I haven’t tested this with Visual Studio 2008 SP1, so I’m interested to know if that service pack solves this.
  • It currently doesn’t work for ASMX implementation project, only for WCF implementation projects. I don’t think ASMX is done with WSSF that much these days, so I didn’t bother to implement it for ASMX.

How to apply the patch:

  • Download the zip file containing the patched files from the bottom of this post.
  • Extract the contents of the zip file to the “C:\Program Files\Microsoft Service Factory Feb 2008\Guidance Package” directory (or other directory where you installed WSSF), replacing the existing files. Create a backup if you want to revert to the existing templates and recipes.

How to use the patch:

  • Choose to generate the WCF implementation projects like you normally do. This means right clicking on the solution and choosing Add > WCF Implementation Projects.
  • Enter the desired name for the service. A simple name will do, do not enter a fully qualified name here becuase you can choose a namespace in the next step. Screenshot
  • In the next screen you supply a desired namespace. Remember that the namespace you enter here will be added to every project that is generated. Screenshot

Download Web Service Software Factory Solution Structure Patch Version 1.0

Viddler.Net on Codeplex

Things are moving fast. Yesterday I released an early first version of Viddler.Net, a wrapper for the Viddle API. Today I was able to post an updated version to Codeplex, which seems more suitable for managing this project than my own blog. The updated version uses HTTP POST instead of GET and includes one extra implemented method to upload videos.

Find the Codeplex project at http://www.codeplex.com/ViddlerDotNet