Changing the default class template in Visual Studio 2012

I moved to Visual Studio 2012 last year and have not had to go back to the 2010 version for some time now. That is a sign of how good the new version is. It does however mean this article now needs an update.

To recap:

How many times have you hit SHIFT+CTRL+A to get a new class in a Visual Studio 2012 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 11.0\Common7\IDE\ItemTemplates\CSharp\Code\1033

The file you want is in an appropriately named folder (no more ZIP files!). If you open the Class folder you will find the following 2 files:

  • Class.cs
  • Class.vstemplate

2. Backup the original files!

Very important step as things do go wrong. Backup the original files e.g. by copying it to Class.cs. Orig so that it is not recognised by Visual Studio.

3. 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. Save your changes
Simply save your edited files (again, there is no longer a ZIP file to recompress with VS 2012).

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

Silverlight MVCVM – Long Live Controllers!

I have been asked to write about a subject I feel very strongly about: Adding Controllers to the MVVM pattern.

To that end I am adding information pages, about our suggested implementation of Controllers in MVVM, which I like to call MVCVM (for “Model, View, Controller, ViewModel”).

The first posting, providing some background information and general concepts, is “Silverlight MVCVM – MVVM With Controllers“.

This has been a debated suggestion on StackOverflow.com, so I welcome your thoughts and suggestions on MVCVM as I provide more and more information about practical uses for it.

Crunch: Online accounting made easy

Crunch, save time, save tax, save money

HiTech Magic Ltd are proud to be an affiliate for Crunch accounting

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.

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.

WordPress Themes