Making Web Apps for Dining with Nerds

Engerland
Flying the flag for Engerland. I especially like the balcony the top right hand corner with the Scotland flag. I think they’ll be rooting for Slovenia tomorrow….

If you are a student with nothing better to do because you have finished your term then this is the perfect time to pick up some new skills. One such skill (posh prose don’t you think) is writing web applications. You can get a great start (including 196 pages of well worked example text about building a Nerd Diner system) here:

http://www.microsoft.com/web/jumpstart/develop.aspx

At the moment the focus is on VS 2008, but I’m sure the content will be updated in due course, and all the fundamentals are the same. In fact the microsoft.com/web stuff is very interesting, particularly if you are wanting to host things like WordPress on your Windows system.

Using RenderTarget2D in XNA on the Zune HD

Have you been lying awake at night wondering why your texture rendering doesn’t work on the Zune HD? No? Oh, well it must be just me then.

Anyhoo, I’ve found the problem, and the story goes like this.

RenderTarget2D is a way that you can draw things on a texture rather than on the game display. Normally I’d write things like:

spriteBatch.Begin();
spriteBatch.Draw (lots of pretty stuff….)
spriteBatch.End();

When the End method runs it takes all my drawing operations, batches them up and pushes them onto the graphics hardware, so the screen now contains the results of all my drawing operations.

However, sometimes you want to do things like rear view mirrors in driving games. You want to draw the view you would see behind the game onto a texture and then draw the texture on top of the rear view mirror.  In this case you need to create a thing called a RenderTarget2D which can accept the draw operations and put them onto a texture rather than the screen. Render targets are not that hard to use:

RenderTarget r = new RenderTarget2D(
   GraphicsDevice,  // my graphics device
   800,              // width of texture   
   600,              // height of texture
   1,               // no. of levels (1 works)
   SurfaceFormat.Color);  // format

GraphicsDevice.SetRenderTarget(0,r);

spriteBatch.Begin();
spriteBatch.Draw (lots of pretty stuff….)
spriteBatch.End();

GraphicsDevices.SetRenderTarget(0,null);

Texture2D result = r.GetTexture();

In the example above I send a bunch of drawing operations to a render target which is 800 pixels wide and 600 pixels high. I set the GraphicsDevice to render to this target, and then at the end I point it at null, which means go back to drawing on the screen again. The render target that I create is called r, and it ends up providing me with a texture which holds the results of all the drawing operations. You can use this to make your whole game display slide about, or bounce around the screen and it is very effective.

I’m using it so that my game can create some textures when it starts, rather than having to load them. I got the rendering working just right on the Windows PC and then transferred my code over the the Zune HD and it broke. I could clear the texture with different colours but I couldn’t draw anything on them. Wah.

After some twiddling I’ve found the problem. When you get a graphics device to render to a texture it is doing something it isn’t particularly used to. Graphics devices are designed to put stuff on the screen, not into memory.  This means that you have to be careful when you set up the target for the rendering, so that the graphics device is happy to write to it. You can find our more about this kind of thing here.

From the point of view of the Zune HD hardware, it is only happy to draw things if the target texture is either the size of the display or half the size of the display. Don’t ask me why, I don’t make the rules.  Any other sizes don’t produce an error, but they don’t work either, which is no fun.

This is not actually a huge problem (except perhaps for memory usage I guess) in that although you have to create textures that are larger than you really want you can use a version of Draw to only pull out the actual part that you want when you finally render them onto the screen. So, if you want to render to textures on a Zune you need to create your render target thus:

drawBuffer =
    new RenderTarget2D(
        GraphicsDevice, 
        GraphicsDevice.Viewport.Width / 2, 
        GraphicsDevice.Viewport.Height / 2,
        1,
        SurfaceFormat.Color);

This is the smallest texture you can use, if you want to draw on the full screen just don’t divide by 2.

Static Constructors

Summer Ball Star

One of the few nice things about marking all the programming exam papers over the last week was the number of people who seemed to understand what “static” means in a programming context. While one or two did make the mistake of putting ‘static means that you can’t change it’ and getting both a muffled oath and zero marks from me most answered “static means that it always there, like the continuous background hiss from a badly tuned FM radio”. Actually, not all of them were as poetic as that, but they all knew that the thing about static items is that you don’t have to make them, your program can use them without having to create any instances.

Pressed for uses of static their answers made sense too, constants that you want everyone in a class to make use of, validation values and methods, all the sensible stuff. I didn’t ask about static constructors though, which is the next step along the road.

If you want to set up an instance of a class you add a constructor method that runs when an object of that type is created. These can be given values so that you can pre-set your object with data at the beginning of its life. Bank accounts can be given account holder names and starting balance values, sprites can be given textures and positions.

Sometimes you might want to perform some code to set up values in your static class. For example a class providing some constants for your program might need to read some system settings first. Unfortunately you can’t use a normal constructor for this because (duh!) we never make an instance of a static class. Instead though you can use a static constructor. This is just like a normal constructor, but has the keyword static in front:

public static class Settings
{
   public static int Number;
   static Settings ()
   {
        // code in here is performed when
        // the class is loaded
        Number = 99;
   }
}

The thing to remember about this is that the static constructor is run when the class is loaded, not at the start of the program. The first time your program reaches a statement like:

int i = Settings.Number;

- that is when the Settings class is loaded and the static constructor runs. In order to reduce memory use and time spent processing unwanted code the .NET runtime system only loads classes when they are needed, so if we never use a value from the Settings class it is never brought into memory and the static constructor never runs. Don’t think of static constructors all running when your program starts, they only run when the classes that contain them are loaded.

In fact any class can contain a static constructor that runs when it is loaded, not just static ones. If you need to get something set up before anybody uses your object just use the construction above to get control when the class is brought in. One way to find out if a particular class is ever actually used in your program is to add a static constructor and then put a breakpoint in it.

XNA Cross Platform Compilation Symbols

Garden Flowers 02

I’m writing a single XNA game that should work on a whole bunch of platforms. Actually I’m going for Windows PC, Windows Phone, Xbox 360 and Zune. Which is a full house I reckon.

Anyhoo, this is a bit of a pain, as I have to make the code do different things for the different target devices. For example the Xbox and the Windows PC don’t have a touch screen so I have to simulate this in some way, or provide a different input mechanism for those platforms.

I can do this by using the symbols provided by XNA to let me select code which is passed to the compiler when the program is built. There are a bunch of them.

#if WINDOWS
// only compile this bit if we are targeting Windows PC
#endif

#if XBOX
// only compile this bit if we are targeting XBOX
#endif

#if ZUNE
// only compile this bit if we are targeting ZUNE
#endif

#if WINDOWS_PHONE
// only compile this bit if we are targeting Windows
//  Phone
#endif

It is important that you understand what is happening here. We are not selecting which code to run when the program is active, we are actually selecting which code gets compiled when the program is built.  I could do this to really confuse a programmer:

#if ZUNE
     Har Har
#endif

This is a very nasty thing to do. It means that the program will not compile if the programmer tries to build version for the Zune, it will produce an error when the compiler sees “Har Har” and ties to compile it. It will however work for every other XNA platform.

One other thing worth knowing is that the symbols that you see when editing with Visual Studio depend on the context in which the file was opened. If you have a multi-project solution (one project for Zune, another for Windows and so on) then the project that you open the file from determines which symbols are active when the file is edited and compiled. This is true even if all the entries in the project source are links to the same actual source file. In other words, the view you have of the code depends on where you opened the file from.

Using the Split method in C#

Abstract Wall

I’ve been playing with a little C# program to transfer marks into a spreadsheet. It is not a very clever program,  and probably took me longer to write than it would have taken me to actually type in the numbers, but it was much more fun, and next year I’ll be ahead of the game…

Anyhoo, one of the things I had to do was split up full name into set of strings to get the first name and surname. I used the Split method to do this, which is supplied free with the String class.

Split is wonderful. It does exactly what you want, plus a little bit more, and so I thought it would be worth a blog post. Split looks a bit scary, because it returns an array of strings, which is something you might not be used to.  The other thing that you might not like about Split is that you have to give it an array of separators, which looks a bit of a pain but actually gives you a lot of flexibility. My first string was a bunch of names separated by tab characters. Easy.

string sampleName = "Rob\tMiles";
char[] tabSep = new char[] { '\t' };
string [] allNames = sampleName.Split(tabSep);

The code above would make an array called allNames which holds two string elements, one with "Rob" in it and one with "Miles" in it. To handle the fact that some people have lots of first names I can get the surname (which is the last string in the sample name) by using the Length property of the allNames array:

string surname = allNames[allNames.Length-1];

Remember that this code will not end well if the starting string is empty, as this means that the allNames array will not contain any elements and your code will say a big hello to the ArrayBoundsException shortly afterwards running the above.  My perfect solution checks the Length of the allNames array and displays an error if this is zero.

The second problem I had was to do the same split action on a list of names which were separated by either comma or space (or both). First thing I had to do was create an array of delimiters:

char[] wordSep = new char[] { ',', ' ' };

Now words are split on these two separators. Bad news is that if I give the Split method a string that contains a bunch of both kinds:

string sampleName = "rob,    Miles";

- this means that I get a whole array of  strings (in this case 6) lots of which are empty. Just finding the surname (which should be the last string) would still be easy enough but finding all the proper names in the rest of the array would be a pain. Turns out that Split has got this covered though, you can add an option that controls the behaviour of the split so that it ignores the empty items:

string[] allNames = fullName.Split(wordSep, 
                      StringSplitOptions.RemoveEmptyEntries);

The option is a bit of a mouthful, but as you don’t need to say it this is not really a problem. The great thing though is that all those nasty extra empty strings are removed, leaving allNames just holding the two strings I really want. Split is actually very useful and it will work on really big strings. I used it to split a list of several thousand words and it worked a treat.

Windows Snipping Tool

image

The Windows Snipping Tool started life in the Tablet versions of Windows but has now made it into the big time and is part of the Accessories for Windows 7. It is great for capturing images off the screen that you want to incorporate into other documents. Say for example you wanted to steal a screenshot of a Plants vs Zombies game and drop it into a blog post….

It is great if you are writing a manual for a program and just want to drop parts of the screen into your text. One of my pet peeves is documents that have the whole Windows desktop in their screenshots. Everybody knows about pressing the PrtScrn to copy the screen to the clipboard. A few people know about ALT+PrtScrn which lets you just copy the active window. With the Snipping Tool you can just capture the bit that you want to write about. You can find it in All Programs->Accessories, but it is so useful you’ll probably pin it to your Taskbar or Start Menu.

Making Games close to the Edge

image

Calling a start to the event in noisy style..

Andy Sithers of Microsoft and a few Hull students got mention in an article in this month’s Edge magazine about some recent 48 hour game development competitions.  This is where a bunch of teams are given a theme, 48 hours and a lot of pizza to make a game. XNA is a brilliant tool to use for  this kind of thing, and Microsoft set up a couple of competitions this year.

Some students from Hull took part and while they didn’t win anything this year (having got a “Cheesiest Game” award last time) they did have a great time. I’d love to take part in one of these one day.

A Hot Day for writing Custom XNA Content Importers

Humber View Wide

In between gardening and feeling very warm I wrote a custom content importer for XNA 4.0 today. This is the way that you can bring in your own content into an XNA game. I’m playing around with some game ideas and I needed to get a bunch of data into my game engine so I can twiddle with it.

Turned out to be a lot easier to do than I thought it would be. Actually, the whole content setup is lovely to use in XNA. If you ever want to do this, you can find a really great start here:

http://msdn.microsoft.com/en-us/library/bb447754.aspx

The stuff seems to work fine in Windows Phone too. I really know how to enjoy myself in summer…..

C# Exceptions and Finally

London Tulips

I’m writing a new version of the C# Yellow Book and I’ve been going through the chapters to make sure they still make sense. Today I’ve been playing with Exceptions. These are things that programs do when really bad things happen. When things are going badly for me in a chess game I have this annoying habit of kicking the board over and storming of to do something else. Exceptions are just like that, but for programs.

If a program finds itself in a situation where it really can’t go any further it can throw an exception and make the issue somebody else’s problem. Really bad in this case means things like “I asked for a number and you’ve given me some text” or “You asked for a file and I can’t find it”.  This means that a proper programmer will put such potentially moody code into a try – catch construction so that they can deal with any tantrums that might be thrown:

try
{
    // Potentially moody code
}
catch
{
    // Code to recover the situation
}

If anything in the block under the try throws an exception the program runs the code in the catch block to try and put things right. When I was younger and more desperate to be liked I used to make sure that code I wrote didn’t ever throw exceptions, but tried to sort things out and carry on. Ask my object to load something from a file that doesn’t exist and it would return a null reference and keep going. Sure, the program that went on to use that null reference would explode some time afterwards, but at least my method hadn’t thrown a tantrum.

Now I’m more nasty. I let my programs throw exceptions if they are asked to do stupid things. That way the fault is generated much closer to the real reason why it happened. Problem is, that sometimes I don’t want to just pass an exception on, I want to do a bit of tidying up myself before I blow away the person that calls me. I can do this by catching the exception in my method and then throwing a new one.

try
{
    // Potentially moody code
    // Code to tidy things up
}
catch
{
    // Code to tidy things up
    throw new Exception ("Bad news message to caller");
}

Of course the problem here is that I have to write the code to tidy things up in more than one place. Once if everything works, and again if the exception is thrown. Which is where finally comes in:

try
{
    // Potentially moody code
}
catch
{
    throw new Exception ("Bad news message to caller");
}
finally
{
    // Code to tidy things up
}

You don’t have to add a finally part to your try – catch construction, but if you do it is where you should put all your tidy up code. This is the code that must run whether or not the exception is thrown, and irrespective of what happens in the blocks above. I use code in the finally part to do things like close files, release objects and say bye-bye to network connections. And it works well except in one situation, which is kind of why I’m writing this blog post.

The code in my finally clause will not run if there is nothing to catch any exceptions thrown by the code in my try – catch construction. In other words, if the exception my code throws will cause the program to end for lack of an exception handler the finally clause will not run. I did some experiments to prove this, and decided it was something worth noting.

The thinking, I suppose, is that if the program is going to stop anyway, what is the point of allowing it to run any more code. Most of the time the finally clause will be releasing resources that will be freed anyway when the program is terminated. However, it is not always as simple as that. Sometimes finally code might want to say a formal goodbye to a remote host, or log some information. 

Since you can’t rely on someone to always catch exceptions that you might throw (particularly if they are stupid enough to make bad calls of your methods in the first place) I think that this means you need to be a bit careful about using finally. If this means putting tidy up code into a method and then calling it both in the try and catch parts of your program, this might be a step worth taking.

Running Windows 7 64 Bit on a Macbook Pro I didn’t know was old..

York Railway Museum Engine Controls

I’ve had so much success with 64 bit Windows 7 on my new Dell Laptop I thought I’d put it on my MacBook Pro. I got this around 2 and a half years ago and it has been quite reliable, only needing a new power supply, battery and system board so far. Thank heavens for AppleCare.

But I digress. I bought a new hard disk and got number one son to fit it. Then we installed OS X and fired up BootCamp which is the Apple program to partition the drive and put Windows on it. At the appointed time I put my Windows 7 64 bit distribution disk in the machine to begin the install. And I got a very strange error message, as if the disk was stuck at a menu I hadn’t seen before.

Turns out that the Windows 7 64 bit DVD uses a format that doesn’t work on old (i.e. made more than 18 months ago) Macs. After a bit of searching I found my way to a web site that explained how to make a new DVD that worked OK.  The command I used (with my not-working DVD in drive d:) is this one:

oscdimg.exe -n -m -bd:\boot\etfsboot.com d:\ c:\windows7x64.iso

The oscdimg program is provided by Microsoft for making disk images. Once it had finished I then had an image on drive C:  which I could burn to make a working disk. I still have it. I’m going to put it somewhere safe.

Anyhoo, that got Windows 64 bit working on my machine and then I hit a second snag. The machine is so old that Apple don’t provide a version of BootCamp for it. This means that I couldn’t do the automated install of all the Apple and other drivers to make it work properly. The good news is that I’ve got all the important bits working without it and I’m sure I can live without the light up keyboard. From a performance point of view everything is fine, and I can now use all of the 4Gbytes of memory the machine has inside.  If you have an older Mac I’d definitely recommend the move to 64 bit.

TechDays 2010 Portugal Session Resources

TechDays Portugal 2010 My Office

ACA009 Creating Windows Phone Games

Here is the content from my session. Thanks for being a great audience.

The code works on the current version of the CTP for the Windows Phone system. You can download this from here. If you want to use demo 3B to serve out accelerometer information to your phone app make sure that the program is running with Administrator privileges, and that you have modified the URL in the Phone Starlight program to address this host (localhost should just work).

If you want to get started with Windows Phone you can find a list of useful lines (and some FAQ entries) here.

ACA004 Giving Robots Life with the .NET Micro Framework

I left Oscar the robot powered up overnight by mistake. I was very impressed to find that he still had plenty of battery power left this morning. Fortunately nobody had been sending movement commands to him via the secret URL otherwise he could have gone anywhere!

If you want to get hold of a robot and Fez controllers you can go to:

http://www.tinyclr.com/

If you want to get hold of the Web Server board you can go here:

http://devicesolutions.net/Products/Tahoe.aspx

If you want the most powerful Micro Framework board I’ve ever seen you can go here:

http://www.ghielectronics.com/product/125

The Micro framework at Microsoft can be found here. There are links to platform manufacturers and a very useful forum. You can even propose enhancements to the platform.

http://www.microsoft.com/netmf/default.mspx

Fun with Visual Studio 2010 Tech Days in London

Tech Days 2010 London Pick your Door
Which door would you choose?

Went down to London today to give a session as part of tech-days Visual Studio Developer Days. It was great fun, even though just about everything broke at some point during the talk. Richard from Black Marble was on before me and did a very impressive talk about the new testing features in Team Foundation Server.

Tech Days 2010 London Richard Fennell
Doesn’t Richard look like Bill Gates?

When my turn came my laptop had gone to sleep and forgotten to produce any video output. Then I had all kinds of finger trouble typing in programs and my microphone broke and fell off twice. But it was all good…

Tech Days 2010 London Blurry Rob Miles
A blurry version of me, which is how I felt at the time…

Tech Days 2010 London Audience
Some of the audience, all of whom were absolutely great.

The whole thing took place in a cinema, so I had the biggest screen I’ve ever used in my life.  You can find the presentation here and the demo code here.

As part of the day I was interviewed for Underbelly, a new Microsoft website for developers. you can find my interview here. If you really want to…

Orta talks iPhone Development

4440451019

Orta and title slide. Nice hat.

Orta (or Ben Maslen) is graduate from our department who is into iPhone development and other cool stuff. Our student computing society, Hull Com. Soc.  invited him up to Hull to give a talk about what he has been up to.

Very good presentation. Nice to hear some of the things that we go on about during the course coming back at us from an ex-student. Orta made the point that when you start doing something like this that you must actively engage with the developer community, asking questions and helping others. Just writing a game and putting it out there is one thing, but you also have to work at “being out there” to promote both yourself and the things that you have done. 

From what he showed us, he seems to be doing pretty well at it.

I’ve got a new Windows Phone

4435712539

Unfortunately it’s not real. Like many other facets of my life, it exists only within the mind of my computer. However, it does work, and I can write programs for it using the latest version of Visual Studio.

If you want your own Windows Phone 7 Series device you can head over to here to perform a one stop download that gives you all the tools you need, including Silverlight, XNA and the emulator.

If you are feeling rich (or are a student on Dreamspark) you can even signed up for the Developer experience here.

iPhone Game Development Lecture

4435022966

One of our ex students (I only know him as @orta!) is giving an iPhone development talk in the department on Wed, March 17, 3:15pm in Lecture Theatre A in the Robert Blackburn Building. He has had his iPhone apps published (and even featured in Apple commercials) and so it should be well worth turning up.

Platform 2010 Free Games Conference at Hull

image

I’m going to be doing quite a lot of speaking in the next month or so. Good thing I know lots of jokes.……

Anyhoo, in a couple of weeks or so, on March 25th, I’ll be treading the boards at Platform 2010, which is a digital gaming event in Hull. It is at the spiffy new Hull Truck theatre and they have some really good speakers lined up. And me.

It is free to attend, so if you are in the neighbourhood and want to take part you should head over to here and register your interest via the “Contact Us” link.

http://www.platform2010.co.uk/index.html

Processing Lots of Files in C#

4346439556

Elliot came to see me today with a need to process a whole bunch of files on a disk. I quite enjoy playing with code and so we spent a few minutes building a framework which would work through a directory tree and allow him to work on each file in turn. Then I thought it was worth blogging, and here we are.

Finding all the files in a directory

The first thing you want to do is find all the files in a directory. Suppose we put the path to the directory into a string:

string startPath = @"c:\users\Rob\Documents";

Note that I’ve used the special version of string literal with the @ in front. This is so my string can contain escape characters (in this case the backslash character) without them being interpreted as part of control sequences. I want to actually use backslash (\) without taking unwanted newlines (\n)

I can find all the files in that directory by using the Directory.GetFiles method, which is in the System.IO namespace. It returns an array of strings with all the filenames in it.

string [] filenames = Directory.GetFiles(startPath);
for (int i = 0; i < filenames.Length; i++)
{
   Console.WriteLine("File : " + filenames[i]);
}

This lump of C# will print out the names of all the files in the startPath directory. So now Elliot can work on each file in turn.

Finding all the Directories in a Directory

Unfortunately my lovely solution doesn’t actually do all that we want. It will pull out all the files in a directory, but we also want to work on the content of the directories in that directory too. It turns out that getting all the directories in a directory is actually very easy too. You use the Directory.GetDirectories method:

string [] directories =
          Directory.GetDirectories(startPath);
for (int i = 0; i < directories.Length; i++)
{
    Console.WriteLine("Directory : " + directories[i]);
}

This lump of C# will print out all the directories in the path that was supplied.

Processing a Whole Directory Tree

I can make a method which will process all the files in a directory tree. This could be version 1.0

static void ProcessFiles(string startPath)
{
   Console.WriteLine("Processing: " + startPath); 
   string [] filenames = Directory.GetFiles(startPath); 
   for (int i = 0; i < filenames.Length; i++)
   {
      // This is where we process the files themselves
      Console.WriteLine("Processing: " + filenames[i]); 
   }
}

I can use it by calling it with a path to work on:

ProcessFiles(@"c:\users\Rob\Documents");

This would work through all the files in my Documents directory. Now I need to improve the method to make it work through an entire directory tree. It turns out that this is really easy too. We can use recursion.

Recursive solutions appear when we define a solution in terms of itself. In this situation we say things like: “To process a directory we must process all the directories in it”.  From a programming perspective recursion is where a method calls itself.  We want to make ProcessFiles call itself for every directory in the start path.

static void ProcessFiles(string startPath)
{
  Console.WriteLine("Processing: " + startPath); 

  string [] directories = 
                  Directory.GetDirectories(startPath); 
  for (int i = 0; i < directories.Length; i++)
  {
    ProcessFiles(directories[i]);
  }

  string [] filenames = Directory.GetFiles(startPath); 
  for (int i = 0; i < filenames.Length; i++)
  { 
    Console.WriteLine("Processing : " + filenames[i]); 
  }
}

The clever, recursive, bit is in red. This uses the code we have already seen, gets a list of all the directory paths and then calls ProcessFiles (i.e. itself) to work on those. If you compile this method (remember to add using System.IO; to the top so that you can get hold of all these useful methods) you will find that it will print out all the files in all the directories.

Console Window Tip:  If you want to pause the listing as it whizzes past in the command window you can hold down CTRL and press S to stop the display, and CTRL+Q to resume it.