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.

Changing the default class template in Visual Studio 2010

How many times have you hit SHIFT+CTRL+A to get a new class in a Visual Studio 2010 project? 100s? 1000s?

And after, that how many times do you have to modify the class file it creates because it is not exactly what you wanted… For me: Every single time!

For starters I want the class public by default. I also want standard regions installed to save me adding them afterwards.

Here’s how to do it:

1. Find the files

The files have not moved around much so are currently in C:\<Program Files>\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Code\1033

The file you want for a class is strangely enough called Class.zip. If you unzip that file you will find it contains only 2 files:

  • Class.cs
  • Class.vstemplate

2. Extract the files

Open that zip file and place the 2 files somewhere to edit. You will need to zip them up again afterwards.

3. Backup the original Zip file!

Very important step as things do go wrong. Backup the original file e.g. by renaming it to Class.ZipOrig so that it is not recognised by Visual Studio.

4. Change the Class.cs template file

This is where you get to be creative. You will notice the original looks something like this:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
	class $safeitemrootname$
	{
	}
}

You might want something more like this:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
	public class $safeitemrootname$
	{
		#region Constants
		#endregion Constants

		#region Fields
		#endregion Fields

		#region Properties
		#endregion Properties

		#region Constructors
		#endregion Constructors

		#region Public methods
		#endregion Public methods

		#region Class override methods
		#endregion Class override methods

		#region Class extensions - virtual methods
		#endregion Class extensions - virtual methods

		#region Private helper methods
		#endregion Private helper methods
	}
}

You will notice a number of Macros $ commands in the template. The complete list is here.

4. Create a new Class.zip file
After editing and saving the template, select the 2 files and use the “Add to compressed folder” option to save them back to a file called Class.zip.

5. Tell Visual Studio about the changes
Your new changes will not be loaded unless you explicitly tell Visual Studio to reload all templates.

  • Close Visual Studio (or the change swill not show until next time you run it)
  • Open a command prompt (you should run this as Administrator if you are not an admin of the machine).
  • Change to the IDE folder a few levels above the template folder (e.g. to C:\<Program Files>\Microsoft Visual Studio 10.0\Common7\IDE)
  • Run the following command:
    devenv.exe /installvstemplates
Viola! There you have your own custom template for new classes.

6. Automate repetitive/fiddly  tasks

If you are going to do this a lot I would suggest creating a batch file, e.g. in your template folder, to run the update step for you. For example create a text file called UpdateTemplates.bat containing the following 3 lines:

cd ../../../..
devenv.exe /installvstemplates
pause

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.

Microsoft Prism 4 hits second Beta

Things are heating up… The second Beta (drop 10) of Prism was released today. We are just awaiting to final release of Prism V4 in the next month or so.

The basic premise of Prism is one of divide and conquer. The divide is cleverly performed by using loose coupling of modules (in English that means that modules know little if anything about each other).

Prism includes a practice referred to as Unity. The Unity container is responsible for providing interfaces to modules and objects on request and acts as the central port of call that modules use to communicate with other modules.

There is a very good set of videos giving examples of Prism on the Channel 9 site here.

The latest version combines a second practice known as MEF (Managed Extensibility Framework). This is another Microsoft produced open source project. MEF uses clever techniques to identify requirements in projects, at runtime, by analysing “import” and “export” directives that exist only in the Metadata of the project. MEF is designed to allow for a plug-in style environment, like the Visual Studio IDE.

We are now using Prism and MEF on a medium to large scale project that is expected to have a lifespan of many years.

We will post updates on techniques as we progress on the project. I must say it’s good to be back on hard-core Silverlight development after a spell of APS.Net development.

Thanks, Dave

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!

Stack Overflow: All quiet on the Silverlight front

We’ve been on StackOverflow.com for about 5 weeks now. One of the things we have noticed is a relative lack of traffic on the Silverlight tag/area when compared to other more common subjects like C#.

One positive result of the low traffic, is that today I was awarded a Gold “Unsung Hero” badge:
Unsung Hero!

Swells with pride… until you realise: that means at least 25% of 150 or so answers have been marked as “the answer”, but nobody has up-voted them as “useful”.

Luckily we are just there to learn and teach. The ranking system is a nice touch, but if anything seems to lead to a rush of poor answers. People compete to earn points and focus more on speed and less on good content.

Still a very worthwhile place to hang out (for computer geeks anyway) :)

Cheers, Dave

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

WordPress Themes