Posts in category .net - page 21

LINQ in C# Web Applications

I’m a big fan of the Web Application type that was previously available as an add-on to Visual Studio 2005 but thankfully got promoted to a standard citizen with Service Pack 1.

So with a little more time on my hands lately I’ve been delving into the wonder that is LINQ – part of the forthcoming Orcas release of technologies.

For those who’ve been living under a rock LINQ is a set of extensions to .NET that let you perform queries on objects in much the same way you would do on a database with SQL (except the syntax is backwards by comparison).

Now while the LINQ Preview CTP installs LINQ projects for C# Class Libraries, Windows Applications and Console Applications it inconveniently misses-out Web Applications!

You can drop this ZIP file in your %UserProfile%\My Documents\Visual Studio 2005\Templates\ProjectTemplates\Visual C# to gain a new ASP.NET LINQ Web Application project type for you to start with as often as you like as shown:

Window of the LINQ To SQL templates available

Or if you want to modify an existing Web Application simply:

  1. Open up the .csproj file in Notepad and replace <Import Project=”$(MSBuildBinPath)\Microsoft.CSharp.targets” /> with <Import Project=”$(ProgramFiles)\LINQ Preview\Misc\Linq.targets” />
  2. Add project references to: System.Data.DLinq System.Query System.Xml.XLinq

Hopefully more LINQ related posts as I get to grips with it.


My 2006 development tools

Christopher Bennage wrote about his development tool set-up and encouraged others to do the same so here’s my current set-up.

Daily tools

  • Visual Studio 2005 – IDE of preference despite it’s sluggish behavior
  • SQL Server 2005 Management Studio – Took getting used to but it’s an improvement on 2000’s Enterprise Manager
  • AnkhSVN – Subversion support inside Visual Studio 2005
  • .NET Reflector – Searching .NET API or to find out what it’s doing
  • Web Application Projects – Stop using VS’s web sites and start using web applications!
  • Web Deployment Projects – Deploy to dev, test or live servers as easily as building a project

Not quite daily

  • CodeSmith – Need to get to grips with v4 to build our whole database layer in one hit
  • Trac – Bug tracking, milestones & wiki with integrated support for Subversion
  • TortoiseSVN – Check-in/out of non-project items (e.g. art assets)
  • Web Developer Extension – Trying CSS changes on-the-fly, validating pages etc. from Firefox
  • Firebug – Examining pages, the page DOM etc. from Firefox
  • KDiff – Excellent 3-way diff tool that works great with AnkhSVN
  • Subtext – Blogging system running here

On occasion

  • Visual C# Express and XNA – Messing with 3D graphics, controllers and pixel shaders
  • Ogre – Steve’s object-oriented 3D engine
  • Xcode and Cocoa – Still quite alien with it’s message-based calling mechanism but obviously powerful

Keeping an eye on

  • Eclipse – IDE for developing Java (C++ and C# support in various stages too)
  • Ruby on Rails – Interesting RAD approach to web development – Apple also supporting on Mac OS X 10.5
  • Sandcastle – Microsoft’s documentation tool that already seems to have had an impact on NDoc
  • SubSonic – Build-provider that generates an ORM on the fly and provides automatic developer-only db editing pages

Not used lately, still installed

  • Delphi 5/6 – Borland’s great RAD tool for non-.NET development, later versions support .NET too
  • JBuilder – Java development although I’d probably move to Eclipse
  • Visual Studio 2003 – Still required for the odd .NET 1.1 application/testing


Adding depth to my programming ability

Elite on the BBC MicroI remember gazing at the screen of Acornsoft’s Elite in my childhood wondering what the code behind those 3D images looked like.

How did they rotate like that? How did it know which lines to hide? And more importantly where I can get a good price for this cargo hold of radio-actives and platinum?

Scouring through magazines, books and the library revealed nothing. Where on Lave was this elusive magic formula?

My attempts at reverse engineering Vu-3D shed no light and the web was still being conceived in Mr Berners-Lee’s brain so Google wouldn’t be able to exist for some time yet.

My programming continued on a more serious tract writing first silly hacks and demo’s, then utilities and into business software as an actual paid job. In my spare time I knocked out some other developer tools, utilities, drivers and even a Flash game of pool for a National Lottery.

3D remained the elusive beast long after the information became available to me. Matrices were not something my mind wanted to grasp a second time.

Then along came OGRE, written by a long-time friend of mine – Steve Streeting.

We’d actually hoped to write a game a long time ago when we were younger and less informed about how much work that would involve. The only thing that survived was the company name I still use for my consulting work – Envy Technologies.

Ogre looked promising. Object-oriented design meant it could hide most of the complexity and let me get on with high-level concepts and setting properties.

If only my degree wasn’t in the way!

Still I had a play and then the lure of Microsoft’s XNA came along.

Based on .NET Framework 2 and C# – the very two technologies I use day-in day-out to write those aforementioned serious apps. Write a game once and deploy it to the PC and Xbox 360 and from C# – a more enjoyable experience than the last C++ stuff I did (under DOS!)

XNA has been interesting to mess with at least on the 3D front. I’ve managed with not too much effort to plot a pyramid on the screen using co-ordinates I figured out, get it bobbing about a bit and changing the color via vertex and pixel shaders respectively and even get it and the viewpoint spinning round from the 360 controller.


From there on you find yourself soon needing features that aren’t there and you have to build yourself or acquire an engine to do it. The managed nature of XNA means that any engine you want to use will have to be specifically written for XNA itself – I guess Garage Games is hoping to cash in once XNA 1.0 gets out with their XNA engine Torque X.

Steve popped round this weekend for a chat about the usual geek topics we discuss I was very grateful that he lent me one of his complementary copies of Pro Ogre 3D Programming (he was technical reviewer and wrote the foreword).

I’m only at the end of Chapter 3 so far and with the exception of wondering what Scene Graphs were I’m still following everything.

Maybe I’ll be able to escape my 2D prison soon.


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]);


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!