Category: Silverlight

Stopping a user from leaving a Silverlight page

Like Flash, Silverlight applications only exist for the life of the page that hosts it.

A common complaint is that when you navigate away from your Silverlight page you get no chance to tidy up or warn the user…

Never fear, help is at hand! All browsers expose an event called window.onbeforeunload.

If you connect a method to that event handler, that returns a string, you will get a standard Message box that looks like this (Internet Explorer):

 

 

or like this (Chrome):

Your javascript  onbeforeclose method is expected to provide a string value to display in that Message box. It makes sense to return that from your Silverlight application, so we will actually kill two birds with one stone.

Here are the actual steps you need to hook into the onbeforeunload event…

1. Add a pluginloaded handler to your HTML page hosting the Silverlight application:

	var slCtl = null;
	function pluginLoaded(sender, args) {
		slCtl = sender.getHost();
	}

This basically stores your Silverlight control object in a global (page) variable called slCtrl.

2. Specify the pluginloaded in your Silverlight object definition:

     <param name="onLoad" value="pluginLoaded" />

This ensures the previous handler is actually called.

3. Define an onClose javascript method and assign it to the onbeforeunload event:

	function onClose() {
		return slCtl.Content.App.OnBeforeClose();
		}
	window.onbeforeunload = onClose

4. Register your Silverlight application object with Silverlight in your App.xaml.cs file Application_Startup event:

private void Application_Startup(object sender, StartupEventArgs e)
{
    this.RootVisual = new MainPage();
    HtmlPage.RegisterScriptableObject(“App”, this);
}

5. Expose a scriptable method in your application to do the cleanup and return the string to display:
[ScriptableMember]
public string OnBeforeClose()
{
    // Do some shutdown work here…
    return “This is where your custom message will be displayed”;
}

I am assuming you know how to put the Javascript into appropriate HTML script elements in your file.

This is guaranteed to run before the user gets the “Are you sure…” prompt. Just add your “shutdown” processing before you return from OnShutdown and voilà you now have a place to hook your code!

Unfortunately there is no way to stop the Message box, but it is better than your user leaving your Silverlight application before you want them to.

Rotating a Silverlight bitmap within its own bounds

This post results from another StackOverflow question we answered.

Install Microsoft Silverlight

This is an interactive version of the answer provided so users can try it out for real.

Localisation of Silverlight projects after completion (Part 2 of 3)

Sorry to leave you in suspense like that. It’s been a busy few weeks completing a large Silverlight Prism/MVVM application.

We have an original solution to all the localisation challenges outlined below:

  • You want the translated strings to be stored in a centralised location for easy of translation and maintenance.
  • You only need one language at a time to be visible.
  • You only want to download to the client the selected language.
  • You probably would not want to change the current language while in the middle of a critical operation (like form entry).
  • You want to make it easy for the developer to add new strings without worrying about maintaining a database.
  • You want to make it easy for localisation testers to edit and view changes inside the running application.

Your first impression may be that the solution is overly complex, but trust me when I say you get a lot of ongoing value in return (and the individual components were not that hard to build).

Attached Properties to the Rescue!

Attached properties are a marvellous invention. They allow any object (that derives from DependencyObject) to store values that they have no knowledge of. The most common examples given are the Grid.Column and Grid.Row properties. They are stored in the children of a Grid, but only the Grid knows of them and what to do with them. The child objects have no idea they are carrying parasitic values around.

A little known detail you may be able to make use of is: that AttachedProperty Setxxx methods are called as XAML files are parsed, even if you don’t actually store the attached values! This gives you somewhere to hook code to do special things as the XAML is loaded.

The components of our solution are:

  • Create a Loc class containing PageId and Key dependency properties (at a minimum). We also added MaxLength and Notes properties to optionally give translators more information (e.g. about restrictions on the translation length).
  • Key Property: The secret is to put your lookup code in the static SetKey method you had to create, as this is called whenever a loc:Loc.Key property is found as your XAML files are parsed.
  • Mark every page and user-control in your project with a PageId Attached Property. Give them all a unique meaningful name (probably the name of the assembly and XAML file).
  • Mark every control that contains any text to be localised with a Key Attached Property, identifying the translation key.
  • Create a server-side Localisation database with at least Phrase, Translation, Page and PagePhrases tables. For a more serious set-up you will probably want Cultures, Translators and TranslatorCultures tables as well.
  • Create a RIA services project (e.g. called CompanyName.Localisation.Web and CompanyName.Localisation)
  • Add an ADO.NET Entity Data Model and connect it to your localisation database tables.
  • Create a RIA Services “Domain Service Class” giving you access to the localisation Entity Data Model.
  • Create a LocalisationManager class to act as a single port of call for all your localisation needs.
  • If you are producing a Prism app, you will also create an ILocalisationProvider interface (with methods to change the language and fetch translations based on key values).
  • Optional: Create a XAML interface for viewing and editing translations from within your application (this is the only difficult step, as any good interface with lots of parts is hard work).

The reason for marking all pages and user-controls is that, normally, from inside a XAML page you have no idea of what page you are in. It is all just a visual tree of components. Having an attached PageId property means you can now do cool stuff like relate translation keys, to the controls they appear on, at runtime. This becomes especially useful when you add a user interface that allows language Translators to edit the language strings at runtime. This feature is worth the effort and will amaze your clients.

By using Attached Properties for the localisation of individual controls, you get the following benefits immediately:

  • The original “Programmer English” strings are unchanged so are visible and human-readable as normal.
  • The original string is available to use as the starting default value for your translations. You can even have the Key SetKey method send all keys and original text to the database (maybe in debug mode)! No need to add it manually.
  • These Attached Properties can be found, at runtime, by a recursive search of the visual tree allowing instant replacement when the language changes.

By providing a single point of entry for localisation you can also use the same system to access translated strings programmatically. This is a requirement as there are also strings somewhere that are not simply authored into the XAML pages.

You now know all the secrets of how we got it to work. In part  3 we will show specific examples of the various components. In the meantime we are always available for consultation and development tasks, so drop us a line via our contact page.

Localisation of Silverlight projects after completion (Part 1 of 3)

So, you’ve created a Silverlight app for you client… It was so well received they now want to take it global!

Before you start shouting hooray, the question you need to ask yourself is “did you take localisation into account when you created the application?”

If your project had a typical short time-frame and small budget, then the answer is “probably not”. At this point you might be starting to sweat a little as you just know they are going to ask you “how long will it take to add new languages?“.

Options:

  1. Create multiple version of the application (so many downsides how dare you even consider it?).
  2. Use language specific resource files for different assets (one per page, per locale).
  3. Fetch and replace the strings using code-behind (and lots of code).
  4. Some combination of 2 and 3, usually involving very (very) long binding expressions to fetch values.
  5. Using simpler bindings and using the application resource dictionaries for storage.
  6. Something new

After looking at the available options in Silverlight, against the requirements of localisation for our project (which I am betting are similar for most Silverlight projects), I came to the conclusion that most publicised methods for Silverlight localisation were too weighty.

Option 5 (simpler bindings) was initially the preferred option and it worked something like this:

  • Use a binding like Text={Binding L_MainMenuTitle}.
  • Insert a dictionary item, of type System.String, under the key L_MainMenuTitle.
  • Manage language changes by simply deleting and replacing name/key entries in the application resource dictionary.

I should point out that the above solution does work, and it works well, but it has some deficiencies:

  • The developer is required to insert [generally] unreadable keys into binding expressions.
  • The developer must manage the adding of new strings to the language database/files.
  • It is intrinsically difficult to track usage of any given key value throughout a large project.

Our final solution (something completely new)

The requirements for localisation of your Silverlight project may run something like this:

  • You want the translated strings to be stored in a centralised location for easy of translation and maintenance.
  • You only need one language at a time to be visible.
  • You only want to download to the client the selected language.
  • You probably would not want to change the current language while in the middle of a critical operation (like form entry).
  • You want to make it easy for the developer to add new strings without worrying about maintaining a database.
  • You want to make it easy for localisation testers to edit and view changes inside the running application.

- “Centralised” and selectable, in a Silverlight application, straight away says server database and RIA services to me.

- Not requiring an instantaneous update negates the huge overhead of every string being a bindable INotifyPropertyChange property.

- Making it easy for the developer implies some form of automation, or integration, with the pages and project is required.

So how does it work? What magic did we perform to meet all the requirements above (and then some)? Stay tuned for part 2 coming soon.

Deep Deep Zoom – Let’s take the red pill and see…

Below is a first experiment using DeepZoom with Silverlight 4 to see what setting are needed to host one in a WordPress Silverlight app.

Install Microsoft Silverlight

The key was to set the InitiParams to “path=DeepZoom/GeneratedImages/dzc_output.xml” so the full plugin setting for this one is (in square brackets):

silverlight: DeepZoom/DeepZoomProject.xap, 480, 300, path=DeepZoom/GeneratedImages/dzc_output.xml

If you follow the right eye of Koala (his right, your left), then the eye of the left Penguin (your left) you can see how deep the rabbit hole goes.

Easing into Silverlight animation – Announcing www.easing.co

After asking a specific question about easing functions on StackOverflow.com I received a comment from user AnthonyWJones. It occurred to me that a lot of people must have the same problem. That is: How to choose an appropriate Easing Function for a given visual effect.

The range of Easing Functions is currently only 33, but most have properties to allow variations on that theme resulting in a huge number of permutations.

The idea is that we build a Silverlight application that will show working examples of each easing type and common useful settings. Further, it would allow  users of the application (i.e. you, the public) to supply keywords for any given Easing configuration. This will allow a search, based on English descriptions of the desired effect, to show appropriate sample settings and active demo.

The end result of the idea is that a few hours ago, and only 20 minutes after the idea formed,we created www.Easing.co to contain the proposed Easing project.

The site will hold a place-holder blog initially, describing the Silverlight development, but later it will house the final application.

It should be an interesting project. If you would like to contribute, contact us through this form on Easing.co.

Thanks, Dave

Default Form Button Behaviours for Silverlight

Behaviours are a great way to encapsulate useful functionality in a self-contained object. These objects can be attached to XAML elements in a Silverlight page to enable features that the elements do not themselves contain or know about.

A feature present in Win Forms and missing from Silverlight is the concept of Default Submit and Cancel Buttons. That is: a button that is clicked automatically when Enter or Escape is pressed while entering  text in TextBox controls on a form.

Type text into any of the 3 TextBox controls below and press the Enter key to “submit” the form or the Escape key to “cancel” the form. For test purposes random numbers appear under the buttons to show that the button actions have been fired (you can just press the Go or Cancel buttons directly to see this).

Install Microsoft Silverlight

The example above uses our new DefaultButtonBehavior and CancelButtonBehaviour. The features are:

  • Can be attached to single text boxes, or to entire forms.
  • Can be enabled independently of the text boxes (this property is bindable).
  • Can ignore empty text boxes (this property is bindable). This is useful for single text box user controls, like a search box.
  • Automatically presses and releases the target button, based on the Enter or Escape key press and release, to give good visual feedback.

We have released this behaviour  to the Expression Gallery. Feel free to download and try it out. Feedback and suggestions welcomed!

Silverlight Control Inheritance Tree

Here is another trivial app. The interesting feature is that it is hosted in a ViewBox control, so resizes to fit the Silverlight control in this page:

Install Microsoft Silverlight

Using the ViewBox as a visualroot container

The same ViewBox based Silverlight control is reused here with a 100 by 100 size:

Install Microsoft Silverlight

The ViewBox control is a very cool addition to control top level scaling of Silverlight apps.

Silverlight plugins for WordPress – practical example

This is a test of the Silverlight Plugin for WordPress by Tim Heuer. Move your mouse over the Silverlight control to start additional animation.

Install Microsoft Silverlight

Documentation was a bit light on the ground but a Google cached copy of Heuer’s blog page revealed the required parameters. The trick is to place your Silverlight component’s XAP file into the root of your blog website (it was not specified, but we figured out this by watching the http requests with the Firefox Http Headers adding).

The widget injects all the require Javascript for you. The WordPress widget marker syntax (inside square brackets) is:

silverlight: <app>, <width>, <height>, <initParams>, <minVer>

The parameters are:

  • app is the XAP filename
  • width is the display width of the Silverlight component (optional)
  • height is the display height of the Silverlight component (optional)
  • initparams maps to the initiparams of the Silverlight component (optional)
  • minVer maps to the minRuntimeVersion required for your app (optional)

Cheers, Dave

WordPress Themes