Quick Number Formatting in C#

IMG_2184

I’ve been playing with the Windows Phone accelerometer, and displaying results. Thing is, it gives me values which have lots of decimal places that I don’t really want. They make the numbers flicker in a way that hurts my head. What I want is a way to just display them to two decimal places.

I must admit that previously I’ve resorted to very dodgy behaviour at this point, such as multiplying by 100, converting to an integer and then dividing by 100 again. Must be my old assembler ways coming back to haunt me. Turns out that there is a much easier way of doing this in C# which is to use the string formatter:

message = "Accelerometer" +
    "\nX: " + string.Format( "{0:0.00}",accelState.X) +
    "\nY: " + string.Format( "{0:0.00}", accelState.Y) +
    "\nZ: " + string.Format( "{0:0.00}", accelState.Z) ;

This little block of magic gets the X, Y and Z values out of a vector and then displays them to two decimal places in a string I can display in my XNA program.

The key is the {0:0.00} bit in the format, which gives a pattern for the display of the first (and only) value to be converted. This pattern says a single leading digit and two decimal places.

If you want to do interesting things like put commas into numbers (so that you can print 1,234,567 type values) then you can do that too. You can find out more about how the format strings work in my C# Yellow book (subtle plug) starting on page 50.

Delegates, Events and Confusion

IMG_2283

Delegates and Events are really powerful parts of C#. They are also powerful confusing.  We can start off by making a new delegate type:

delegate void SimpleEvent () ;

This is a new type, called SimpleEvent. If we ever need to create a delegate that refers to a method that returns void and has no parameters, we can use SimpleEvent to do this. So, let’s do that. Here is our method:

void testMethod()
{
    Console.WriteLine("Test Called");
}

This method doesn’t do much, but it does tell us it has been called, which is a start. Now, to create something that refers to this method we can create a SimpleEvent instance:

SimpleEvent x = new SimpleEvent(testMethod);

This has created a delegate that refers to testMethod. We’ve given it the rather enigmatic name of x. We can make a call on this delegate if we want:

x();

Note that we have to treat x as if it was a void method that accepts no parameters (since that is the type of method that the delegate refers to). When x runs it will print out “Test Called”, since that is what testMethod does, and x presently refers to that method.

The name x is actually quite appropriate, in that when we call x we don’t really know what is going to happen, since it could be made to refer to any method. If it doesn’t refer anywhere we’ll get a null reference exception of course, and serve us right.

So, delegates let us create objects that can refer to methods we want to run. Great if you want to bind behaviours to events. (and this is where it starts to get confusing)

We can declare a delegate variable:

SimpleEvent eventList;

At the moment this refers nowhere (try to call eventList and we get an exception). But we can add methods that we want to be called when the event is fired:

eventList += new SimpleEvent(testMethod);

Now, when we do:

eventList();

- the testMethod is called. Wonderful. So let’s make this more confusing:

eventList += x;

This adds another item on to the list of delegates managed by eventList. The item added is the x that we created earlier, which refers to testMethod. Now, when we do:

eventList();

- the testMethod gets called twice (because when you call a delegate it works through all the methods that are presently bound to it).

If we want to unhook methods from a delegate then we can use –= to do this:

eventList –= x;

This would remove one of the calls of testMethod from the delegate, so that now if we call eventList it will only call testMethod once. And it works.

However, this works too:

eventList –= new SimpleEvent(testMethod);

I hate this. It confuses me so much. It looks like we’ve made a new delegate and minused (!) it from the list of events. There is some strong magic going on here which I really don’t like. What must happen is that the –= operator must go “Aha!, here is a delegate that references this method, I must remove one from the list of delegates”.

If x is the delegate that I originally created, it seems reasonable to remove that from the list, what confuses me is that you can also remove delegates by appearing to create new ones. I guess that this is because otherwise programmers would have to keep track of event references that they might like to remove later, but I still don’t like it.

Clothes Shopping with Jetlag

gum

We got back to the UK first thing this morning, had a quick nap and immediately decided to go clothes shopping. As you do.

There was actually method in this madness, in that we were in Bristol, which is home to one of the few shops that sells clothes in my size. And they have a sale just right now. So it was off to purchase a whole bunch of outfits. Took number one wife with me to stop me buying anything purple or orange.

Windows Phone Jump Start Ends

making your mind up
We used seat colours to get answers from delegates. Purple for true, yellow for false. Here is the audience making its mind up.

Final day of the course today. Great turnout, great interaction and some really good questions.

Rob Miles with the Jetliner

“Win your own private jet” – more pictures from pinksugarface here.

At the end we gave away the big prize along with two smaller, passenger ones. Thanks to everyone who turned up, I hope you enjoyed it, Andy and I certainly did.

the audience
Audience pictures are not the same though…..

Then it was out for a meal to celebrate.

Jump Start Crew

This course was brought to you by (left to right) Sharon, Jeff, Bob, Andy, Rob and Elese. Thanks to Ben for taking the picture.

Remember, you can keep track of the course and find links to the videos and other cool stuff at:

http://borntolearn.mslearn.net/wp7/default.aspx

Windows Phone 7 Jump Start

You're on camera!

Nerves of steel in the studio.. Thanks to pinksugarface for the picture.

Andy and I did our first day of Windows Phone 7 training today. Fantastic fun with an incredible turnout.  We did these silly quizzes where delegates had to answer true/false questions by changing their seat colours and it was amazing to see all the flags switching over to the right answer before our eyes. Folks, you were great.

I gave out the phone number of my Windows Phone 7 device and asked for some jokes via SMS  (my “emergency” supply of humour ran out around 45 minutes in….). Got loads of texts in response, I’ve not got time to type them all in, but here is a choice selection:

  • What did the blind man say when handed a cheese grater? “That’s the most violent book I’ve ever read”
  • Where do you find a no-legged dog? Right where you left him.
  • On which side does a tiger have the most stripes? The outside.
  • Why do the French only have one egg for breakfast? Because one egg is an oeuf”
  • A man is smoking a cigarette and blowing smoke rings in the air. His girlfriend becomes irritated with the smoke and says “Can’t you see the warning label on the box? Smoking is hazardous to your health.” The man replies “I’m a programmer, we don’t worry about warnings, we only worry about errors”.

Great stuff. Normally I have to buy a whole bunch of Christmas crackers to get material of this quality.

Tomorrow (Wednesday) we are open “office hours” (1:00pm to 4:00 PST) on the course web site. If you are having a play with Windows Phone 7 drop by and say hello.

http://borntolearn.mslearn.net/wp7/default.aspx

And remember, you can still sign up for the Thursday sessions here:

July 22 – 8am (PST): Session Three:  Advanced Windows Phone Development

July 22 – 1pm (PST): Session Four:  Selling Your Windows Phone Solutions & Wrap Up

Windows Phone 7 Jump Start Studio Prep

WP7 Course Presenter View

Bob sets up the webcam while we sort out the introductions.

Today we went over to the room where we are doing our mammoth Windows Phone 7 Jump Start. It starts Tuesday morning and you can sign up here if you like. I was expecting a room with a desk and a webcam. They were there alright, in a studio with two proper cameras, a backdrop and all the trappings of a professional broadcast.

Oh gosh.

WP7 Course Camera View

Andy settling in.

We did some dry runs where we found out a couple of things:

  1. Both of us speaking at the same time– bad.
  2. Neither of us speaking at all – bad.

However, I think we should be OK on the day.

Got Phone

Windows 7 Phone

Mine

Got my Windows 7 phone working today (I’m calling it mine in case anyone tries to take it away). Works a treat. Once I got it to talk to the hotel WiFi it started to show just how nice Windows Phone 7 actually is. I really like it, but this week my focus is on writing programs, not phone user interface design.

So it was on with the fun and games getting my programs deployed to the device from Visual Studio. Which I had not done before. For this I had to lean on the expertise of fellow MVPs who came to my assistance with advice and software in equal measure.

Thanks to Ginny, Joel and Nick for sterling support which paid off in the end. It really was nice to see my program running on a device, and I love the feeling that I can get any of my silly ideas deployed to a real phone (and maybe even sell them)

Then we went out for a walk and I bought a Pay as You Go sim for my phone.  I’ll let you all know the number later, so you can ring me and talk to a real Windows Phone if you want.

Hello Seattle (again)

Mountain View

Nice view from the plane

The lady at US Immigration looked at the stamps in my passport and said “You come here a lot, don’t you”. I suppose I do, wouldn’t have it any other way.

Anyhoo, we had a very smooth couple of flights thanks to Continental airlines (although the airline food version of a cheeseburger is something I only want to experience once in my life) and finally arrived in Bellevue in time for a walk around. During which I broke my shoes in half. Fortunately they had a huge mall just around the corner which had loads of shoe shops and so I was able to get something I’ve always wanted, a pair of Converse All Stars. Excellent.

Downtown Seattle

Downtown Bellevue looking good.

Then Sharon arrived at the hotel with a Windows Phone each for Andy and me. Truly, the day could have got any perfecter.

Windows Phone 7 Training Mayhem

Meerkat

Who? Me?

I got an email a couple of weeks ago asking if I would like to do some Windows Phone 7 training. Thinking that this might be a useful stepping stone to getting my hands on a device, and it might be fun to do I said why not? Actually, it was a bit more complicated than that

I fly out to Seattle on Saturday. I started off thinking that I would be doing this using Live Meeting in a little room in our house, it turns out that I will be using Live Meeting out of a studio in Bellevue, Washington State, USA. 

At the moment I’m working on the content. We have 12 hours to fill…

Windows Phone 7 Jump Start

Windows Phone Jump Start

As announced earlier today in The Guardian among other places Microsoft is running a Windows Phone 7 Jump Start course next week to get developers started writing applications and games for Windows Phone 7. Andy and I are doing it, live from Bellevue Seattle on Tuesday and Thursday.  Using the magic of Live Meeting anyone can take part and it is free to sign up.

Should be fun.