Posts in category .net - page 22

Localizing .NET web applications

It seems that globalization often makes the wish list of many a web site until the client realizes professional quality translations require a significant investment of time and money.

On occasion however smaller web applications with their limited vocabulary are prime targets for localization globalization and it can be quite feasible to translate the couple of hundred strings involved.

Here’s a very brief whirlwind overview of what’s involved.

Create the default language resource file

Create a new folder inside your App_GlobalResources folder to contain your language resource files. Then create a new resource file (e.g. Localization\Language.resx) to use when no translation exists for the user’s preferred language.

Detect the user’s browser settings and switch

In .NET 1.1 this required a couple of lines of code in your global.asa.cs:

public void Application_BeginRequest(object sender, EventArgs e) {
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]);
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(Request.UserLanguages[0]);
}

Update

Sander Rijken points out that .NET 2.0 lets you do this with a line in your web.config <system.web> section instead:

<globalization culture="auto" uiCulture="auto" />

or indeed at individual page level with:

<@ Page ... Culture="auto" UICulture="auto">

Localize the classes

For every bit of code that sets a string that will end up on the user’s display you now have to move that into the language resource file and replace the code with a reference to it. So if for example you had;

if (name.Length == 0) error.Text = "Please enter a name";

Then you move “Please enter a name” into the resource file and give it a sensible key such as NameBlankError and modify the above line to read;

if (name.Length == 0) error.Text = Resources.Language.NameBlankError;

There is a Resource Refactoring Tool to do this for you now! Just right-click the string, choose Extract to resource and fill in the blanks.

Localize the pages

Unlike the WinForms designer the WebForms one doesn’t support multi-language so you’re instead forced to do it by hand. One way is to remove all the text from the page and place it into the resource language file.

Then create a private void Localize() method in each page that simply looks something like;

public void Localize() {
    Title = Resources.Language.LoginPageTitle;
    loginButton.Text = Resources.Language.LoginPageLoginButton;
    reminderButton.Text = Resources.Language.LoginPageReminderButton;
}

Obviously you need to call this from the page, I find that calling it from Page_PreRender works a treat.

One disadvantage to this technique is your page itself ends up looking very blank in the designer or duplicates text that soon gets out of date. You could avoid this by leaving the default-language text in the page and not calling localize if you are running in that language. Be sure to put “\***” or something in the default language resource file for it though so that if it’s missing for other languages you immediately spot the missing text during testing.

Don’t treat types as strings

If you have a number, treat it as a number and pass it around as a number. The same applies to dates etc.

If you need to pass over to SQL etc. then use a parameterized query, they’re fast and will take care of all the regionalization stuff for you!

To get those pesky strings in and out of the correct types see the following extra steps!

Always use .ToString() to format output

Almost all basic .NET types include locale-aware formatting and so keep an eye on the ToString methods. Remember even numbers are formatted differently across the globe. 1,234.00 in England and the US becomes 1.234,00 in various parts of Europe.

Be very careful of outputting currencies. .NET won’t convert the amount for you but you could easily find yourself with the wrong currency symbol and therefore a totally different price!

Always use .TryParse to read input

When accepting information from users hand over that string to TryParse for it to try and work out what’s going on. It will helpfully return a boolean indicating if it did the job okay – if not time to use that localized error-message.

Auf wiedersehen!

[)amien

XNA Game Studio Beta 2 has Xbox 360 support

Screenshot of the XNA Game Studio 360 registration windowYesterday I predicted the ability to run XNA code on our Xbox 360’s today.

We’re not quite there yet but we are a lot closer than most people believed this time yesterday.

Contrary to preliminary info on beta 2 of XNA Game Studio before it release it DOES in fact contains the necessary pieces for 360 development.

Specifically the registration window inside XNA Game Studio, shown here, the XnaTrans.exe tool for transferring builds over to the 360 and a surprise XNA Remote Performance Monitor for Xbox 360 tool.

I believe we have all the software we need right now. All we need Microsoft to do is to enable the Xbox 360 side – most likely a menu option alongside the Connect to media PC that’ll throw the connection key up on the screen that the PC side needs.

If anyone from the XNA team wants to turn mine on for testing my gamertag is DamienG ;-)

Update

It would seem the XNA team are prohibited from allowing beta code to run on retail Xbox 360’s :( Let’s hope they get to a 1.0 release sooner rather than later. A comprehensive look at the other beta 2 changes can be found at the XNA Team Blog.

[)amien

WinForms tricks & tips

TreeView right-mouse button select the node

I’m not sure why it doesn’t do this as standard but a simple event handler should do the trick:

private void treeView_MouseDown(object sender, MouseEventArgs e) {
    if (e.Button == MouseButtons.Right) {
    TreeNode node = treeView.GetNodeAt(e.X, e.Y);
    if (node != null)
        treeView.SelectedNode = node;
    }
}

Adding text to a text box

People have asked (in the IRC #CSharp) why adding text to a TextBox is so slow and flickery. Normally they are trying:

textBox1.Text += myNewText;

The problem with this is that it copies all the Text from the text box then adds myNewText to it and copies the whole result back. This is because strings in .NET are immutable, i.e. can’t be changed, and so adding one string to another always results in this overhead (and hence the existence of the StringBuilder class).

The solution is to abandon the slow, inefficient string concatenation and use the method AppendText thusly:

textBox1.AppendText(myNewText);

Which is fast and efficient whilst also being available to TextBox, RichTextBox and MaskedTextBox (by virtue of being a method of BaseTextBox).

They usually also ask how to make the text box scroll to the end. Just use the following line:

textBox1.ScrollToCaret();

Don’t forget keyboard input

Check those tab orders and accelerator keys!

Creating dynamic controls

If you’re ever unsure how to work with a dynamic control just create it in Visual Studio’s Designer and then head into the .designer.cs file and examine the code it generates.

Windows Forms FAQ

There are many other hints, tips and solutions in the Windows Forms FAQ.

[)amien

Compile XNA for your Xbox 360 tomorrow?

There’s a possibility that tomorrow will see the announcement of XNA Game Studio Beta 2 with support for compiling and running applications on your Xbox 360.

Originally this was scheduled for the final 1.0 release and would involve a $99 annual fee for the privilege but what better way to get hype and excitement than to offer it free for a month or two while it’s being polished and tested during the beta phase?

Before you think I’m dreaming consider that Microsoft released the Xbox 360 Halloween firmware update this morning complete with XNA support, admittedly overshadowed by the announcement of 1080p support – another thorn in Sony’s leaky side.

The official release notes made it clear that the XNA support was tied into future availability and subject to subscriptions. The page on Xbox.com just comes out and plain says “now”.

Dave over at LetsKillDave says they’ll be an announcement about XNA Game Studio Beta 2 in the next 24 hours although he has previously stated that the demonstrated technique for deploying games to the 360 won’t be available until 1.0.

Guess we’ll have to wait and see.

[)amien