Mark's profileMark Dawson - Tips for C...BlogLists Tools Help

Mark Dawson - Tips for C# .Net

March 01

Auto-implemented properties

In the latest version of C# (3.0) you now have a language feature called Auto-Implemented properties: http://msdn2.microsoft.com/en-us/library/bb384054.aspx Basically you can define that you want a property and when the code is compile a backing field will be created to fill in the implementation of the property, for example:
 
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      Person p = new Person();
      p.Name =
"Frank";
    }
  }
 
  class Person
  {
    public string Name { get; set; }
  }
}
February 24

Funny email statement

At work the other day someone had connected a DHCP server to the network, tsk, tsk.  An email was sent around asking everyone to make sure there computer have not connected to the rogue DHCP server,  the funny bit was the statment of the email which said:
 
"Education has been applied"
 
Just made me laugh :-)
 
 
Mark.

Installing Visual Studio 2008 on Windows Vista with Virtual CDRom

I installed a trial version of Visual Studio 2008 today on my home laptop.  The download is actually a 3GB ISO file, there are two ways you can install it, either burning a DVD with the contents, or for people like me who don't have a DVD burner you can mount the ISO virtually using a handy little tool from Microsoft.  This post is about getting this tool to work on Windows Vista.
 
3. After installing Virtual CR-ROM Control Panel for Windows XP, right click on the desktop icon and choose properties, then go to the Compatibility tab and check the option to make this XP SP2 compatible.
4. Turn Off UAC, by clicking on the Start Perl and then clicking on your user image, you will then see the option to turn off uac.  If you don't do this step then when you mount the ISO the drive will not show up as a drive for you to be able to use, by disabling UAC the drive will show up and you can install Visual Studio.
5. Install Visual Studio
6.TURN ON UAC
 
Don't forget step six after you have finished installing.
January 21

Talking about xUnit.net - Unit Testing for .NET - Home

Most of you will probably have heard about NUnit for writing unit tests (you do write unit tests don't you :-)).  xUnit is a new unit testing framework that was developed by Brad Wilson and Jim Newkirk, most definitely worth checking out:

xUnit.net - Unit Testing for .NET - Home
December 09

C# string format cheat sheet

A nice page containing details of how to format strings in C#: http://blog.stevex.net/index.php/string-formatting-in-csharp/
October 07

New demo for Kit3d

I created a new demo using Kit3D (www.markdawson.org\kit3d) it is a 3d picture viewer, inspired by some demos created using papervision3d for flash, check it out: http://www.markdawson.org/kit3d/demos/photos/default.html
 
Mark.
September 30

Kit3D - a 3D graphics engine for Microsoft Silverlight

So a while ago I posted I would be working on a 3D graphics engine, well I didn't get chance to work on that until the last week or so, however...... instead of writing it in C# I wrote it in JavaScript.  Why you might ask, well I was playing around with Ajax.Net and then progressed into using Microsoft's new cool web plugin Silverlight http://www.microsoft.com/Silverlight/ which is a lightweight plugin that allows 2D graphics, video and sound, much like Adobe Flash player.  However currently there is no 3D support natively, so I thought I would write the engine in Javascript (which is supported in the 1.0 version - 1.1 supports C# and .Net so I might port it into C# in a bit if I get time).  Also another nice thing about having it in Javascript is that it should be pretty trivial for someone (maybe me) to port this to work with SVG as well as XAML in the silverlight plugin which is pretty cool.
 
Anyway, check out the demos, so far in version 0.1 I have:
 
- View Frustum clipping
- Scene Graphs
- Texture Mapping
- Animation
 
 
There is also a codeplex website where you can browse through all of the code: http://www.codeplex.com/kit3d
 
Check it out :-)
July 08

C#3.0 - Implicitly Typed Local Variables

Implicitly Typed Local Variables
 
Implicitly typed local variables are one of the fundamental pieces of C#3.0 that allow LINQ to be so expressive and simple to use.  An implicitly typed local variable is a variable in which the writer of the code does not explicitly have to define the type of the local variable.  These variables are declared using the “var” keyword.  Some examples are:
 
            var a = "hello";
            var b = 3.0f;
            var c = DateTime.Now;
 
An important point to make is that the var keyword is not the same as a variant data type which can be assigned any value and the type of the value assigned to the variant can change during the execution of the program.  With var, the code is strongly typed, once a value has been assigned the type of the values assigned to the var variable cannot be changed, so the following will produce a compiler error:
 
            var a = "hello";
            a = 123;
 
Implicitly typed locals are really useful for allowing more consice code, since we do not need to explicitly defined the type of the variables, but the big win is that there are many times, especially using LINQ, when we do not have an explicit name for a type that is returned.  In the cod we want to retrieve some information that is an amalgamation of the data from different types, if we had to create a new type for each of these scenarios then we would have to create many types just to hold this data.  With implicitly typed local variables a type is made behind the scenes by the compiler.
 
A couple more points:
-    ITLVs must be initialized with a value that allows the compiler to infer the type, so assigning to null is not allowed:
var a = null;
 
-    ITLVs can be used in multiple places like for/foreach statements and also in a “using” statement.  For a var to be used in the “using” statement the type it is linked to must implement the IDisposable interface otherwise a compile time error will occur.
 
List<int> numbers = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8 };
            foreach (var n in numbers)
            {
                Console.WriteLine(n);
            }
 
            using (var f = new Form())
            {
}
 
There are some limitiations to what you can do with implicitly local variables, they cannot be used as class members or as parameters to functions.  When looking at anonymous types we will see more examples of the var keyword being used.

C# 3.0 Lambda Expressions

Lambda Expressions
 
What is a lambda expression?
A lambda expression is really just a function, in functional programming a lambda function is a function that does not have a name.  This may sound a little bit weird at first but there are lots of scenarios (as we will look at later) where you want to be able to define a function which caring what it is called, for example if you wish to pass a function as an argument to another function.  The new language syntax allows us to define the body of a function and a delegate which calls that function with a single language construct.  Basically lambda functions are very similar to anonymous methods which were introduced back in C# 2.0.  The basic structure of a Lambda expression consists of three pieces, a parameter list, the => token (I don’t think it has an official name) and the body, which can be either an expression or a statement block:
 
lambda-expression:
(   lambda-parameter-listopt   )   =>
   lambda-expression-body
implicitly-typed-lambda-parameter  
=>   lambda-expression-body
 
Lets review quickly how an anonymous method can be used, in the example below we want to create a method that adds two to the value passed into the function:
 
     delegate int AddTwo(int value);
 
        static void Main(string[] args)
        {
            AddTwo f = delegate(int value)
            {
                return value + 2;
            };
 
            int newValue = f(10);
        }
 
That is pretty good, however having to define the delegate syntax does detract from the intention of the code.  In this contrived example it is not too bad, but in larger more complex examples this extra verboseness can make the code not as consise as it could be.  Now instead of using an anonymous method we can use a lambda expression, so the above code turns into:
 
        delegate int AddTwo(int value);
 
        static void Main(string[] args)
        {
            AddTwo f = value => value + 2;
            int newValue = f(10);
        }
 
Here you see that the delegate f is defined as being a function that takes in a value parameter and returns a value that is equal to value plus 2.  Notice that there is no extra coding, in this example we did not even have to specify the type of the parameter (value) that was used since this can easily be interred by the compiler from how the expression was used.  As you can see the code is much more concise.  One of the benefits of this functional style of coding is that you write a lot less code to do the same job and that helps to reduce mistakes.
 
In the above code, at the end of the day underneath the hood the code is the same as the anonymous method code we saw, if you open up the code in reflector you will see the following definition:
 
    private static void Main(string[] args)
   {
       AddTwo f = delegate (int value) {
           return value + 2;
       };
       int newValue = f(10);
   }
 
We can see how the C# language has been evolving, for example if we have a very simple scenario, where we want to add a listener to a forms MouseMove event that simply outputs the mouse co-ordinates to the output window, below shows how this can be written in the various releases of C#:
 
        private void Form1_Load(object sender, EventArgs e)
        {
            //C# 1.1, also need the Form1_MouseMove method to be defined
            this.MouseMove += new MouseEventHandler(Form1_MouseMove);
 
            //C# 2.0
            this.MouseMove += delegate(object s, MouseEventArgs evt)
            {
                Console.WriteLine("X={0}, Y={1}", evt.X, evt.Y);
            };
 
            //C# 3.0
            this.MouseMove += (s,evt) => Console.WriteLine("X={0}, Y={1}", evt.X, evt.Y);
        }
 
        //This is required for the C#1.1 language version of the example.
        void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            Console.WriteLine("X={0}, Y={1}", e.X, e.Y);
        }
 
As you can see in C#1.1, when defining the event handler the caller needs to create a new method which performs the desired action, this is not desirable because the intent of the handler now has been seperated from the place where it is used, leading to more code bloat and more difficult to read/maintain code.  In C#2.0 things were improved in that now we have anonymous methods that allow the action to be described inline where the handler is used, however this is still a little verbose, especially for more complex scenarios.  In the present day with C#3.0, we now have lambda expressions, here we are able to define very tersly the action we want to perform on the MouseMove event (a much more declarative style of programming), notice that we do not even have to declare explicitly what the types of the parameters being used by the lambda expression are, this can be inferred by the compiler (we still are strongly typed, but we do not need to explicitly declare the type since it can be inferred).
 
So the big benefits we get from Lamba expressions over anonymous methods are that they are more consice which leads to easier to read code and also they implement type inferencing which allows you to not have to specify the parameter types in most cases.  Also anonymous delegates can only have a block expression as their body, whereas Lambda expressions can have both block and expressions as their body.
 
Another nice example of how consise we can be with lamba expressions is in the code sample below, where we can use a lambda expression as a parameter to a DrawGraph function (the lambda expression evaluates to a delegate of type Func<P,R> which is defined as:
 
 “delegate R Func(P p)”
 
The intent of the code is very clear:
 
      static void Main(string[] args)
        {
            //y = x + 1
            DrawGraph(x => x + 1);
 
            //y = x2
            DrawGraph(x => x * x);
 
            //y = x
            DrawGraph(x => x);
        }
 
        static void DrawGraph(Func<int, double> f)
        {
            List<int> domain = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            domain.ForEach(x => Console.WriteLine("X={0}, Y={1}", x, f(x)));
        }
 
Examples of permitted lambda expression syntax:
Note: Action<T> is a delegate with the following signature “delegate void Action<T>(T t)”, namely a method that takes a single parameter and does not return a value. MethodInvoker is a delegate with the following definition “delegate void MethodInvoker()”
 
When not passing any parameters the () parentheses must be used i.e.
MethodInvoker f = () => Console.WriteLine("This does nothing");
 
When passing a single value the parentheses are optional i.e.
Action<int> printValue = x => Console.WriteLine(x);
Action<int> printValue = (x) => Console.WriteLine(x);
 
When specifying more than one parameter you are required to write the parameter list parentheses around all of the parameters. When specifying parameters for the lambda expression you can explicitly or implicitly type the parameters, all of the parameters provided must be either explicitly typed or implicitly typed, this cannot be mixed:
Func<int, double> f = (int x) => x * Math.PI;
Func<int, double> f = x => x * Math.PI;
Func<int, double, string> g = (int x, double y) => (x * y).ToString();
Func<int, double, string> g = (x, y) => (x * y).ToString();
 
The contents of the lambda expressions body are defined as:
 
    lambda-expression-body:
        expression
        block
 
    expression:
        assignment
        non-assignment-expression
 
    non-assignment-expression:
        conditional-expression
        lambda-expression
        query-expression
 
So the body can either be another expression, or a block. A block is a set of statements or expressions inside {}.  The expressions can either be a conditional expression (such as the tertiary operator ()?:, not note an if/then/else because that is a statement, not an expression), a lambda expression so the definition is recursive or a query expression (more on that another time).Therefore valid examples of the body of a lambda expression are:
 
        Func<int, double> f = x =>
                                             {
                                                 Console.WriteLine(x);
                                                 return x * 2;
                                             };
 
        Func<int, int> g = x => (x % 2 == 0) ? 0 : 1;
        Func<int, int> g = x => { return (x % 2 == 0) ? 0 : 1; };
 
 
July 07

C# 3.0 - Overview of new features

C# 3.0 is the new version of the C# language, there are a number of improvements being made, some that might be quite unfamiliar or foreign to hardcore imperative programmers J.  A lot of the changes in the language are based on declarative style programming, such as F# (if you haven’t already bought yourself a copy of “Foundations of F#” I would really recommend it: http://www.amazon.com/Foundations-F-Robert-Pickering/dp/1590597575/ref=sr_1_13/002-2807637-8507208?ie=UTF8&s=books&qid=1182798120&sr=8-13), changes that allow the code that developers write to be more terse and clearer about the purpose of the code without having to write too much boilerplate code which distracts from the purpose of the code.
 
I want to write a series of entries, one for each of the new language features that are listed in the new C# 3.0 specification (see: http://download.microsoft.com/download/5/8/6/5868081c-68aa-40de-9a45-a3803d8134b8/csharp_3.0_specification.doc ), finally finishing off with an overview of LINQ (pronounced link).  LINQ uses all of the newly added language features, so it is important that you understand how to use them correctly.  The list of topics I will cover are:
 
As I write about these different topics I will update the links on this post. Enjoy J
July 06

Checked Exceptions

A nice article about why C# does not have checked exceptions like Java, from the main man himself Anders Hejlsberg: http://www.artima.com/intv/handcuffsP.html
July 04

Events and delegates - pattern of implementation:Part2

Please read part1 before reading this entry: (wish Live Spaces would allow more text per entry)
 
 
Finally there is the issue of future proofing this event.  For example, at some point in the future, as well as sending the message to each client, we may also want to send the time that the server received the message.  The problem we have is that now we have to update the MessageReceivedEventHandler signature to include this new parameter i.e.
 
public delegate void MessageReceivedEventHandler(DateTime timeReceived, string message);
 
Which means all of the clients that receive this message will have to update their method signatures.  A better way would have been to pass a data type to the delegate that could be modified without breaking the clients code.  In C# you can use the EventArgs class to handle this.  Event information should inherit from the EventArgs class, so our example would change to include the new type:
 
    class MessageReceivedEventArgs : EventArgs
    {
        private DateTime timeReceived;
        private string message;
 
        public MessageReceivedEventArgs(DateTime timeReceived, string message)
        {
            this.timeReceived = timeReceived;
            this.message = message;
        }
 
        public DateTime TimeReceived
        {
            get { return this.timeReceived; }
        }
 
        public string Message
        {
            get { return this.message; }
        }
    }
 
Now the MessageReceivedEventHandler delegate can be described as:
 
public delegate void MessageReceivedEventHandler(MessageReceivedEventArgs args);
 
Here we have future proofed ourselves if we event want to add more information to the event.  Finally in the normal pattern, it is customary to pass in the reference to the object that raised the event, so the listener can use this information if they wish, so our handler will look like:
 
public delegate void MessageReceivedEventHandler(object sender, MessageReceivedEventArgs args);
 
If you are using .Net 2.0 or above (which you should be J), then instead of having to create our own delegates for every event we want to raise, like the MessageReceivedEventHandler shown above, which can possibly end up with many delegate types if you have a lot of events in your class, we can take advantage of the generic EventHandler<T> type.  The non generic EventHandler class defines the following signature:
 
public delegate void EventHandler ( Object sender, EventArgs e )
 
For the generic version EventHandler<T>:
 
public delegate void EventHandler<TEventArgs> ( Object sender, TEventArgs e ) where TEventArgs : EventArgs
 
The e parameter can now be any type that inherits from EventArgs, this is really nice because now instead of having to define our own delegate and describe the event signature as:
 
public event MessageReceivedEventHandler MessageReceived;
 
We can now delete the MessageReceivedEventHandler and just define our event as:
 
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
 
Our final stab at this code is now going to look like the code below.  This code is extensible, will not throw exceptions at unexpected time and follows the normal Microsoft pattern for raising events:
 
 
using System;
using System.Collections.Generic;
 
namespace EventExample
{
    class Program
    {
        static void Main(string[] args)
        {
            EnterpriseChatServer server = new EnterpriseChatServer();
 
            //Customer paid their bill, so they can now receive messages
            server.SubscriptionPaid = true;
 
            //Add a listener who want to know of new message arrivals
            server.MessageReceived += server_MessageReceived;
 
            //Simulate receiving a message;
            server.AlertNewMessageArrival("This is a message from Frank");
        }
 
        static void server_MessageReceived(object sender, MessageReceivedEventArgs args)
        {
            Console.WriteLine("New message received at {0}=[{1}]", args.TimeReceived, args.Message);
        }
    }
 
    class MessageReceivedEventArgs : EventArgs
    {
        private DateTime timeReceived;
        private string message;
 
        public MessageReceivedEventArgs(DateTime timeReceived, string message)
        {
            this.timeReceived = timeReceived;
            this.message = message;
        }
 
        public DateTime TimeReceived
        {
            get { return this.timeReceived; }
        }
 
        public string Message
        {
            get { return this.message; }
        }
    }
 
    class ChatServer
    {
        public event EventHandler<MessageReceivedEventArgs> MessageReceived;
 
        public virtual void AlertNewMessageArrival(string message)
        {
            OnMessageReceived(new MessageReceivedEventArgs(DateTime.Now, message));
        }
 
        protected virtual void OnMessageReceived(MessageReceivedEventArgs args)
        {
            EventHandler<MessageReceivedEventArgs> handler = MessageReceived;
            if (handler != null)
            {
                handler(this, args);
            }
        }
    }
 
    class EnterpriseChatServer : ChatServer
    {
        private bool subscriptionPaid = false;
 
        protected override void OnMessageReceived(MessageReceivedEventArgs args)
        {
            if (SubscriptionPaid)
            {
                base.OnMessageReceived(args);
            }
        }
 
        public bool SubscriptionPaid
        {
            get { return this.subscriptionPaid; }
            set { this.subscriptionPaid = value; }
        }
    }
}

Events and Delegates - pattern of implementation:Part1

Events and Delegates – pattern of implementation.
 
Events and delegates are something that every C# programmer should be comfortable with.  Microsoft has a set of guidelines for how events should be implemented.  Below I will go through a series of iterations from first creating a delegate and event in a basic manner up to how you are recommended to implement events in your own libraries (code is based on .Net 2.0 syntax and above). 
 
For our example we will start with a simple example of a chat application, where when a message is received at the ChatServer an event is raised for clients that are listening, below is a first attempt at what someone might write:
 
 
using System;
using System.Collections.Generic;
 
namespace EventExample
{
    class Program
    {
        static void Main(string[] args)
        {
            ChatServer server = new ChatServer();
 
            //Add a listener who want to know of new message arrivals
            server.MessageReceived += server_MessageReceived;
 
            //Simulate receiving a message;
            server.AlertNewMessageArrival("This is a message from Frank");
        }
 
        static void server_MessageReceived(string message)
        {
            Console.WriteLine("New message received=[{0}]", message);
        }
    }
 
    class ChatServer
    {
        public delegate void MessageReceivedEventHandler(string message);
        public event MessageReceivedEventHandler MessageReceived;
 
        public void AlertNewMessageArrival(string message)
        {
            if (MessageReceived != null)
            {
                MessageReceived(message);
            }
        }
    }
}
 
In this example, the message is received by the ChatServer and the message will be printed to the console window, since the server_MessageReceived method has subscribed to the event. Now there are a couple of problems with this implementation:
 
1.  If we want to change the information that is passed to the MessageReceivedEventHandler, for example maybe we want to pass the time the message was received as well as the message, then we will have to update our MessageReceivedEventHandler delegate signature and also all of the methods that subscribed to this event will also have to be updated, this is not very future proof.
 
2.  The event code is not thread safe (I will go into why a bit later).
 
3.  It is not possible to inherit from the CharServer class and raise the MessageReceived event from the derived class.  The reason for this is because events can only be raised from the class in why they were defined.
So lets update our code to resolve each one of these issues in turn.  We will start with number three, being able to extend the events from a derived class.  We will update the example to create an EnterpriseChatServer class that derives from ChatServer, the difference here is that in order to be able to receive messages from an EnterpriseChatServer you must have paid a subscription fee.  In the example below the AlertNewMessageArrival method has been overridden and a new method called OnMessageReceived has been added to the ChatServer class:
 
 
using System;
using System.Collections.Generic;
 
namespace EventExample
{
    class Program
    {
        static void Main(string[] args)
        {
            EnterpriseChatServer server = new EnterpriseChatServer();
 
            //Add a listener who want to know of new message arrivals
            server.MessageReceived += server_MessageReceived;
 
            //Customer paid their bill, so they can now receive messages
            server.SubscriptionPaid = true;
 
            //Simulate receiving a message;
            server.AlertNewMessageArrival("This is a message from Frank, who paid his bill!!");
        }
 
        static void server_MessageReceived(string message)
        {
            Console.WriteLine("New message received=[{0}]", message);
        }
    }
 
    class ChatServer
    {
        public delegate void MessageReceivedEventHandler(string message);
        public event MessageReceivedEventHandler MessageReceived;
 
        public virtual void AlertNewMessageArrival(string message)
        {
            OnMessageReceived(message);
        }
 
        protected virtual void OnMessageReceived(string message)
        {
            if (MessageReceived != null)
            {
                MessageReceived(message);
            }
        }
    }
 
    class EnterpriseChatServer : ChatServer
    {
        private bool subscriptionPaid = false;
 
        public override void AlertNewMessageArrival(string message)
        {
            if (SubscriptionPaid)
            {
                //This would throw a compiler error:
                //The event 'EventExample.ChatServer.MessageReceived'
                //can only appear on the left hand side of += or -=
                //(except when used from within the type 'EventExample.ChatServer')
                //
                //if (MessageReceived != null)
                //{
                //    MessageReceived(message);
                //}
 
                OnMessageReceived(message);
            }
        }
 
        public bool SubscriptionPaid
        {
            get { return this.subscriptionPaid; }
            set { this.subscriptionPaid = value; }
        }
    }
}
 
So the above example shows that the derived classes can call the OnMessageReceived method which is defined in the base class to raise events.  This is a standard practice, to create a method called On<EventName> which methods call to raise the event.  It is also good programming practice because now we have only one place where the logic to raise the event is defined, all other methods call this method.  The OnXXXX methods are defined as being “protected virtual” so that derived classes also have the opportunity to override the functionality of the method to change the behavior of how the event is raised.  We could have also just overridden the virtual OnMessageReceived method to perform the subscription check, but I wanted to show how the event cannot be called directly from the derived class.  If we had overridden the OnMessageReceived method it would have looked something like:
 
        protected override void OnMessageReceived(string message)
        {
            if (SubscriptionPaid)
            {
                base.OnMessageReceived(message);
            }
        }
 
If we had overriden the OnMessageReceived method, we would have not needed to override the AlertNewMessageArrival method.
 
So now lets take a look at issue number two, where I said the event raising is not thread safe.  Normally in code you see the following pattern:
 
        protected virtual void OnMessageReceived(string message)
        {
            if (MessageReceived != null)
            {
                MessageReceived(message);
            }
        }
 
There is a check for null against the event, which ensures the delegate is not called if there are no subscribers, which would lead to a “Object reference not set to an instance of an object” exception being raised.  The problem here is that if you have a multi threaded application, it is possible that after the check for null, another thread could be executed on the processor and the second thread might remove the last event listener.  Then when the execution context is returned to the first thread, it is now inside the if statement and tries to raise the event, which is going to cause an exception to be raised.
 
A way around this is to first assign the delegate to a local member variable.  Delegates are immutable so the local variable actually refers to a copy of the delegate, so if the main delegate is changed the contents of the local delegate will remain the same. So we will update our OnMessageReceived method to take this into account:
 
        protected virtual void OnMessageReceived(string message)
        {
            MessageReceivedEventHandler handler = MessageReceived;
            if (handler != null)
            {
                handler(message);
            }
        }
 
This is not a panacea, there are other issues still present in that another thread can add / remove a listener after we have assigned to the local handler instance, so our chat server will either still send a message to a client that just removed its reference, or we will not send a message to a client that just added itself as a listener.  There are also other subtle issues with events, to read more see another article I wrote: http://themightycoder.spaces.live.com/blog/cns!EBFBA22CD769E10B!129.entry However the above solution is pretty reasonable for most applications.
 
 
Run out of space to finish writing this entry, please see part2 to continue: http://themightycoder.spaces.live.com/blog/cns!EBFBA22CD769E10B!277.entry
June 25

Computer Vision Library - C#, Webcam Video Capture

C# - Computer Vision Framework
One of the areas of computing that interests me is computer vision.  My masters thesis was all about attempting to identify a person from a video stream based on the way they were walking (Gait), see: http://www.doc.ic.ac.uk/teaching/projects/Distinguished02/MarkDawson.pdf Basically if you have ever seen anyone from a distance and been able to recognize who they were without seeing their face just by looking at how the person is walking, then you have been performing Gait recognition J.
 
With processors ever increasing in computing power and other sources of processing power, such as graphics adapters that are starting to trend towards general purpose computing (GPGPU – General Purpose Graphics Processing Unit) the ability to perform complex image processing and computer vision techniques is coming to the masses.  Recently at nights and weekends when I get some spare time in-between doing real work, sorting out a new condo and trying to keep fit I started to develop a general purpose framework for computer vision.  The bulk of the processing code is actually written in C++, but the logic and GUI are built using C# which PInvokes down into the C++ DLL.
 
The framework is general purpose in that individual processing units can be easily connected together in all manner of configurations, the basic components are sources, processors and links.  Any number of image sources can be connected to processors via links.  For example you can have a webcam video source that you connect to a rotation processor, the rotation processor can be connected to a RGB->HSL processor, which can be connected to a file save processor.  As video frames are sent from the source, they pass through each processor and are eventually either displayed on the screen or saved to disk. 
 
For example, say that you wanted to develop an application that could track objects of a certain color in a video scene.  In order to do this you would need to do the following:
  1. Capture the video input
  2.  Take the input and possibly rotate / flip into the correct orientation
  3.  Convert the RGB video signal into a different color model.  An example of this is converting the RGB pixel    values of an image into HSV (Hue, Saturation, Value) color model.  The reason why we want to do this is because an RBG value takes into account not only the hue (color) or a pixel but also the brightness as well, the hue and brightness are linked.  So if we wanted to track a color, say blue, then the RGB value of this color will be affected easily by shadows, as the blue gets darker or lighter it will move away from our target color, even though it is still blue, this will make our tracking not as accurate.  The HSV splits up the hue from the brightness, so that we can identify a color to track by its hue and reduce the affect of shadows and lighting on our tracking.
  4.  Capture and train the system for the color we want to match.
  5.  Sample all of the pixels in the image to see what pixels are considered to match our target color
  6.  At this point if the image quality is not very clear, there may be a lot of noise in the image where pixels have been incorrectly classified, leading to small blobs of matching pixels.  We want to remove these and only leave the larger solid blobs of matching pixels.  One way to do this is to use Connected Component Labelling – this method marks all matching pixels that are touching with a unique label, once the whole image is processed we can count the number of pixels associated with each label and then remove the blobs that fall below a certain threshold, only leaving the larger blobs.
  7.  Once the image is processed, want to overlay one the original image where the matching pixels have been found
  8.  Display the captured video image on screen, with the areas of matching pixels highlighted on top of the image.

Phew – just to track a few matching color blobs!  As you can see image processing take quite a bit of processing.  The great thing about the framework I am developing is that each step in the processing pipeline can be plugged together and mixed and matched to enable easy creation of new scenarios.

On my laptop, the demo below runs in real time, tracking of the color is instantaneous, however my laptop is not powerful enough to run this app and Microsoft Windows Media Encoder which I used to capture the desktop video at the same time, resulting in a jerky video for you guys (or there is someway to get a bettr framerate from windows Media Encoder, if anyone knows how please leave a comment).  At some point in time I need to get a nice beefy machine.

 
Below you can see the first sample app that I created using the framework.  My intial aim is to develop some small games using the framework and then gradually build up the individual processing components over time to make a useful set of libraries.  I hope to be releasing v0.1 at some point in the near future so others can play around and maybe contribute to this library.
 
So the first video shows the app running, and switching the captured image from an RGB representation to one based just on the hue (HSL).  I stored the hue value in the Red component of the pixle, so all of the different colors ROYGBIV hues will show up as shades of red.  You can see some items I picked up to show in the video.  Notice how the itesm have dark shadows on them in the RGB representation, however in the HSV version the items are a solid hue, without the interference of shadows (one good thing about choosing the correct color model):
 
 
 
 
The next video shows me training the software to match the color of the blue sleeping pillow (the red square is the region where the color model is captured).  First I flip the image, the convert the RGB pixels to HSL, I then turn on the pixel matching, initially pixels which are considered to match the training color show up as green pixels (non matching pixels are black).  Initially you can see the blue pillow has been matched but there is also a lot of noise in the matching, where other pixels are considered to match (the image quality from my webcam is quite poor).  I then overlap the matching pixels onto the live video capture, when I turn on blob detection the noise can be eliminated by changing the cutoff size for the minimum allowed blob size (moving the slider).  By increasing the minimum blob size allowed, we can remove the small blobs i.e. the noise from the matching pixels.
 
This is all realtime on my laptop and alot better quality, need to figure out how the use windows Media Encoder better:
 
 
Video: Computer Vision II  
 
Notice at the end of the video I turned on the blob view, where each individual blob that is detected is filled in a different color, so you can see individually classified blobs, it is quite cool when it is faster.  Blob detection is a good way of reducing noise.
 
Where do I want to go with this library, eventually I want try to take some of the processing which currently is done exclusively on the CPU and move it into the GPU, which will leave more processing power to create more responsive games.  I also hope to create lots of processors that can be linked together to make powerful computer vision available to the casual person who wants to develop a cool application. 
 
I will be posting some code samples in a few later posts that show how easy it is to configure new processing topologies, keep coming back :-)
June 24

F#.Net and functional programming - part II

Please look at the first part of this entry first: http://themightycoder.spaces.live.com/blog/cns!EBFBA22CD769E10B!271.entry
 
#light
 
let rec merge l1 l2 =
 match l1, l2 with
  | [], [] -> []
  | [], l2 -> l2
  | l1, [] -> l1
  | h1::t1, h2::t2 when h1 <= h2 -> h1 :: merge t1 l2
  | h1::t1, h2::t2 -> h2 :: merge l1 t2
 
let rec splitList i l =
 match l with
  | [] -> [],[]
  | l when i = 0 -> ([], l)
  | h::t ->
      let l1, l2 = splitList (i-1) t;
      h::l1, l2
 
let rec mergeSort l =
 match l with
  | [] -> []
  | [x] -> [x]
  | l ->
      let l1,l2 = splitList (l.Length/2) l
      merge (mergeSort l1) (mergeSort l2)
 
let sortedList = mergeSort [1;12;2;9;18;3;14;6]
print_any sortedList
 
Let’s start with the merge function, it takes two list l1 and l2, you can see the guard cases where we perform pattern matching on the lists, when we have two empty lists we return an empty list [], in the case where only one of the lists does have any elements we return that list.  For the final cases:
  a.  | h1::t1, h2::t2 when h1 <= h2 -> h1 :: merge t1 l2
  b.  | h1::t1, h2::t2 -> h2 :: merge l1 t2
 
We have split the two lists up into a head h1, h2 and tails t1, t2 (all of the elements in the list excluding the head element, this can also be the empty list in the case of a list with just one element).  In the first case the condition for matching is that if the head element h1 from l1 is <= the head element h2 in l2 then the result should be a list which is comprised of h1 concatenated onto the list which is created from merging the rest of the elements of l1 (excluding h1) with all of the elements of l2.  As you can see this definition is nice and clear once you understand the syntax of the language, notice we have not had to define any types for the identifiers, create temporary storage etc, it is very elegant and clearly shows the intention of the code, as you can see the F# code is less verbose than the C# equivalent.
 
The splitList function splits a list at the specified element index and returns a tuple consisting of two lists, hopefully this code is okay to follow.  Finally the mergeSort function is the same as the MergeSort function we wrote in C# in functionality, for a list l, in the case where we have any empty list an empty list is returned, in the case of a list with just one element a list of one element is returned.  Finally the interesting guard case is:
  | l ->
    let l1,l2 = splitList (l.Length/2) l
    merge (mergeSort l1) (mergeSort l2)
 
This means that in the case of a list (where the other previous guard cases are not matched) we can define two identifiers l1,l2 which are the split halves of the original list l, then we simply merge the result of the recursive mergeSort of the split elements.  The result of splitList is a tuple of two elements.  One nice thing about F# is that it is strongly typed, but types are inferred, they do not need to be explicit, this is like generics in C#, notice in the F# code that not at any point in the code did we even specify any types, the F# compiler was able to infer all of this from the code.  Initially this may be a bit of a shock to some imperative programmers and they may associated it with the var types in Visual Basic which are not strongly typed, but this is not the case in F# as even though the types are not explicitly defined it is strongly type as you cannot incorrectly add a string to an int and so on, the freedom to not have to explicitly define types is a good feeling once you get use to it.  We will be seeing more of this in the upcoming version of C# (3.5 I think) where there are anonymous types, this is an idea pulled straight from functional programming paradigms.
 
This was a very brief intro to F#, I am definitely interested in reading through this book when I get chance to see how this language can be used in every day real world programming scenarios, who knows one day maybe this will be my language of choice J  I hope that this brief into will make some people want to take a look into the benefits that this language can offer.

F#.Net and functional programming

F#.Net and functional programming - Part 1
 
This blog is primarily concerned with C#, but last weekend I was browsing through the C# books in the local Barnes & Noble store and came across a copy of “Foundations of F#” (http://www.amazon.com/Foundations-F-Robert-Pickering/dp/1590597575/ref=sr_1_13/002-2807637-8507208?ie=UTF8&s=books&qid=1182798120&sr=8-13) definitely worth reading. In an imperative language actions are explicitly written down, whereas in a functional language (a pure functional language) there is no concept of state and the code looks more like a mathematical representation of the algorithm.
 
One of the first courses that I studied in my Computer Engineering degree (www.doc.ic.ac.uk to doc website) was functional programming in Haskell.  I enjoyed the course (see some excellent course note at the following link if you want to learn Haskell: http://www.doc.ic.ac.uk/~ajf/Teaching/Haskell/LectureNotes.pdf) but didn’t really see how the language was useful beyond list manipulation or language parsing, it was something like an academic exercise.  As I am getting chance to read through this book I hope to see how a functional language with the full power of the .Net framework libraries can be used to possibly provide more efficient programming in certain scenarios than C# or how concepts from functional programming languages can be used to improve C# (as we will see in C# 3.0).
 
For a quick introduction to F#, I will go through an example below, showing List manipulation.  In order to run this sample you will need to get the F# Interactive Console or the F# compiler, you can get these and more information from the F# home page: http://research.microsoft.com/fsharp/fsharp.aspx
 
A basic example of F# is shown below, here the identifier InsertIntoSortedList will add an element into a sorted list at the correct location:
 
#light
let rec InsertIntoSortedList x l =
 match l with
  | [] -> [x]
  | head :: tail when x <= head -> x :: head :: tail
  | head :: tail -> head :: InsertIntoSortedList x tail
 
let sortedList = InsertIntoSortedList 5 [1;3;4;8;9;12]
print_any sortedList
 
The #light statement, tells the compiler that whitespace is important and the position of identifiers have meaning in terms of scope.  The let statement is used to define an identifier, in F# you do not have variables, since once a value is assigned to an identifier it cannot be changed, it is not like a variable.  A cool thing is that identifiers can be both values and function, you can use then interchangably.  Here we have some list manipulation, the guard statements are like if statements in C# they are pattern matching, specifying what should happen in certain scenarios.  In the above example we are pattern matching on the list l, when the list is empty the function will return a list that contains a single element, x, which is the value we want to insert into the list.    The next guard case:
 
  | head :: tail when x <= head -> x :: head :: tail
 
Says that if we split the list l into two pieces, a head element and a tail, which consists of all the elements of l excluding the head (this can also be an empty list in the case of a list which only has a single element), if the element we want to insert into the list is <= to the current head of the ordered list then we want to return a list that is the concatenation of x :: head :: tail, i.e. we have added the element at the front of the list.  In the other case:
 
  | head :: tail -> head :: InsertIntoSortedList x tail
 
Where the current head of the list is less that the value we want to insert, x, into the ordered list we want to return the concatenation of head with the result of adding the value x, into the remaing values in the list, tail.  In functional programming, normally recursion is used where a looping mechanism would have been used in an imperative programming language.  If you are not very familiar with recursion it can be a very useful tool in your programming arsenal, definitely worth investigating more.
 
As a more interesting example we can see how the MergeSort algorithm can be implemented in both C# and F# to compare the code (I do not claim these algorithms to be optimal or robust, just informative J).  The basic premise behind the MergeSort is that given a list of elements, the list is split in half and each half is split and so on, until you have either empty lists or lists with one element in them, at this point the algorithm then starts to recombine the small lists by merging two lists into a sorted list.  For more information on MergeSort please see the following link (it may make the following code more understandable): http://en.wikipedia.org/wiki/Mergesort
 
So the basic components we need for a merge sort is a function that can merge two sorted lists into a single list e.g.
L1 = [1,2,4,7]
L2 = [3,4,9,12]
mergedList L1 L2 = [1,2,3,4,4,7,9,12]
 
and also a method that will split the lists down into the smaller and smaller list, then recombine the small list in order by using the merge functionality.  The following code uses C# generics so that the MergeSort method is capable of sorting lists of any type that are capable of supporting the IComparable<T> interface:
 
 
using System;
using System.Collections.Generic;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> l1 = new List<int>();
            l1.Add(1);
            l1.Add(12);
            l1.Add(2);
            l1.Add(9);
            l1.Add(18);
            l1.Add(3);
            l1.Add(14);
            l1.Add(6);
 
            List<int> sortedList = MergeSort(l1);
 
            for (int i = 0; i < sortedList.Count; ++i)
            {
                Console.WriteLine(sortedList[i]);
            }
        }
 
        /// <summary>
        /// Merges two ordered lists into one list
        /// </summary>
        /// <param name="l1">List to merge</param>
        /// <param name="l2">List to merge</param>
        /// <param name="output">Contains the sorted elements of l1 and l2 combined</param>
        public static void Merge<T>(List<T> l1, List<T> l2, List<T> output) where T : IComparable<T>
        {
            int i = 0;
            int j = 0;
 
            while (i < l1.Count || j < l2.Count)
            {
                if (i == l1.Count)
                {
                    //All the elements of l1 have been added to the merged list,
                    //so only elements of l2 left to add
                    output.Add(l2[j++]);
                }
                else if (j == l2.Count)
                {
                    //All the elements of l2 have been added to the merged list,
                    //so only elements of l1 left to add
                    output.Add(l1[i++]);
                }
                else
                {
                    //If element of l1 is < element of l2 then want to add l1 element
                    //to the merged list, then continue
                    if (l1[i].CompareTo(l2[j]) < 0)
                    {
                        output.Add(l1[i++]);
                    }
                    else
                    {
                        output.Add(l2[j++]);
                    }
                }
            }
        }
 
        public static List<T> MergeSort<T>(List<T> listToSort) where T : IComparable<T>
        {
            List<T> sortedList = new List<T>();
 
            if (listToSort.Count == 0)
            {
                //Nothing to sort, can just return empty list, this is
                //one of our base cases to stop the recursion
                return sortedList;
            }
            else if (listToSort.Count == 1)
            {
                //If the list only has one element, we can just add that one
                //element to our merged list and continue, this is the second
                //base case to stop recursion
                sortedList.Add(listToSort[0]);
                return sortedList;
            }
            else
            {
                //We will split the list into two halves, then recursively keep splitting
                //the lists and finally merge the halve back together – this is the recursive case
                List<T> l1 = listToSort.GetRange(0, listToSort.Count / 2);
                List<T> l2 = listToSort.GetRange(listToSort.Count / 2, listToSort.Count - listToSort.Count / 2);
 
                l1 = MergeSort(l1);
                l2 = MergeSort(l2);
                Merge<T>(l1, l2, sortedList);
 
                return sortedList;
            }
        }
    }
}
 
Hopefully all of the above makes sence, if not then go back to the Wikipedia entry to learn more about how the algorithm works.  Now for the F# equivalent:
 
Please see the second entry for the rest of this article, unfortunately I went over the text limit for each blog entry :-(
 
June 03

Loops and floats

So I have never found the need to use a float data type as the index of a for loop, but apparently non-integral types are allowed so you can do something like:
 
for(float f = 0; f<20000000.0f; ++f)
{
    Console.WriteLine(f);
}
 
Looks harmeless enough, however if you run this piece of code you will see something interesting, you get stuck in an infinte loop, eventually the loop is stuck at a value of 16777216.0f, even though 1 is being added to the number each time, strange!  Well the issue is one relating to floating point numbers being represented in a computer.  Every software engineer should know about floating point numbers and common pitfalls, an excellent place to start reading is "What every computer scientist should know about floating point numbers" http://www.physics.ohio-state.edu/~dws/grouplinks/floating_point_math.pdf.
 
The problem in the example above is that 16777217 cannot be represented in floating point numbers, so 16777216.0f + 1.0f returns a value of 16777216.0f, hence you are trapped forever.  So the lesson here is that you should be aware of issues of using floating point numbers as loop indexes and unless you really have some pressing reason stick to ints, because if x can be represented and x+n can be represented then all of the values inbetween x and x+n can also be represented precisely, no infinte loop issues.  The aboveexample was taken from:http://www.cs.princeton.edu/introcs/91float/
May 28

Math.Abs - simple

Take a look at the following lines of code:
 
using System;
namespace ConsoleApplication1
{ 
    class Program
    {
        static void Main(string[] args)
        {
            int i = -12345;
            int iAbs = Math.Abs(i);
        }
    }
}

Looks fairly simple, basically Math.Abs takes a number and returns the positive version of that number, so values returned from it will always be >= 0.  Now imagine that the input to Math.Abs, i, is set to some random number that can be in the range of int.MinValue to int.MaxValue, is this code always going to work?

The answer is NO, the reason being that integral numbers are represented in binary by a number of bits, for an int that is 32 bits, since these numbers can be both positive and negative one of the bits is used up to indicate the sign of the number, leaving 31 bits for the actual range of numbers, this leaves us with 2^31 unique numbers we can represent (excluding the sign of the number). For ints this range is -2^31 to 2^31-1 the reason for the -1 is because one entry is taken up by the 0 representation.  What this means is that there is an extra negative value int.MinValue -2147483648, that does not have a corresponding positive representation, since the max positive value is 2147483647.

Long sotry short if you are using Math.Abs for values that includes int.MinValue then it is possible Math.Abs could throw an OverFlowException, which might lead to random failures that are hard to track, without adequate logging, so make sure you are taking this into consideration when using this simple function :-)

May 27

C# Graphics Engine - Let the journey begin

Hi all,
  I have two main interests when it comes to software development and that is Computer Vision and Computer Graphics.  I think these two go well together because they both require a good mathematical understanding and also require optimization techniques to get the system up and running at a decent speed.  My aim in this set of articles is to build a 3D graphics engine from scratch using entirely C#.  This will hopefully be a good set of tutorials for students or people interested in computer graphics to get an understanding of the fundamental concepts of #D graphics.  There are now other libraries you can use such as WPF for 3D but you still need to have a good understanding of the basic graphics concepts and mathematics to understand what you are doing :-)
 
  So keep coming back and hopefully I will have a good set of articles and source code to allow everyone to follow along.
 
Later,
Mark.
May 21

Null Coalescing Operator

There are a lot of scenarios where before using a value you need to check if it is null or not, and if it is then use an alternate value, something along the lines of (a rather contrived example):
 
Person p = new Person();
 
string personName = "N/A";
if(p.Name != null)
{
    personName = p.Name;
}
 
In C# 2.0 and above there is the handy and friendly named "null coalescing operator", which takes the syntax x ?? y which is x is not null will return x otherwise it will return y.  So we can replace the above code with:
 
Person p = new Person();
string personName = p.Name ?? "N/A"
 
A lot of times this will be useful,  especially with nullable types, for example when you are T? to T there is probably a value that signifies the null value, normally you would have to do:
 
int? x = null;
int y = -1;
if(x.HasValue)
{
   y = x.Value;
}
 
Again we can replace this with:
int? x = null;
int y = x ?? -1
 
Which is pretty handy and useful.  I would love to be able to have an extended version of this that would allow evaluation of multiple sequential property calls, for example normally when you need to navigate a few layer of properties you are always checking for null:
 
Person p = .....
string bankManagerName = "N/A";
if(p.BankAccount != null)
{
   if(p.BankAccount.BankManager != null)
   {
       bankManagerName = p.BankAccount.BankManager.Name;
   }
}
 
which could be something like:
 
Person p = ...
string bankManagerName = p??BankAccount??BankManager.Name??"N/A";
 
As soon as a null value is found the last value in the chain is used, in the above case it would be "N/A", if null is not found the properties are executed.  Maybe we can see something like that in C#3.5 :-)

ConditionalAttribute and pre-processor directives

A pre-processor directive if a language construct that allows you to specify information for the compiler.  It is possible to conditionally compile code out of the final product, this is usually useful when you want to have extra checks in the code (asserts, invariant checking) during development and testing, in debug mode, but do not want to incur the cost of this checking in the final release product.  An Example of this is:
 
public void Foo()
{
    #if DEBUG
        //check state, possibly perform expensive operations
    #endif
 
    //Do something
}
 
The problem with pre-processor directives is that it can be easy if they are spread all around your codebase to make a mistake and accidentally remove a piece of code from the released version of your product, or not compile out the right code, a more structured approach is to put all of the checking into a method, this method ideally can be conditionally compiled out to remove the function call in the MSIL to remove the performance hit.  In C# this can be accomplished using the System.Diagnostics.ConditionalAttribute. The attribute can be placed above a method that has a void return type e.g.:
 
[Conditional("MYDEFINE")]
private void CheckMyObject()
{
    //do some stuff
}
 
You can define the values used to evaludate the conditional (MYDEFINE) above either on the compiler command line /define:MYDEFINE or you can define it in the code somewhere "#define MYDEFINE".  It is even possible to put more than one conditional attribute on a single method, in this case the result is an OR of the two defines.  If you want to create an AND situation then you will still have to use preprocessor directive directly to achieve this e.g.
 
#if (DEF1 && DEF2)
  #define  MYDEFINE
#endif
 
If you compile your project in Debug mode then a /define:DEBUG is appended to the compiler command line arguments, this is not present in the release version of the project.
 
For more information on preprocessor directive see: http://msdn2.microsoft.com/en-us/library/ed8yd1ha(VS.71).aspx
May 20

Long Time

Wow - it's been a little while since I added a new entry to this blog.  I have been busy at work and hadn't realized just how much time has flown past :-)  Well I have a number of half finished entries that hopefully will get added soon, so keep on coming back :-)
 
In the mean time, every thought about learning a bit of MSIL,  if you want to go under the hood of C#, take a look at this beginners tutorial: http://www.codeguru.com/csharp/.net/net_general/il/article.php/c4635/
February 22

OfficeLive - www.tachographtraining.com

Hi all, 
  not really a C# post but just a quick one about www.officelive.com.  If you have not seen this service already then you should take a look, basically it is Microsoft offering online services for small businesses.  They have a free service where they will buy the domain name for you and then provide you with web hosting, which is a great deal, so basically for $0 I created my uncle a new website www.tachographtraining.com in a few hours over the weekend - awesome.  For small businesses this is a really great opportunity.  The online web page authoring interface is very easy to use, a little bit limiting in its flexibility, but in the paid versions of the service you can author your own HTML.  Just thought I would blog this since it is a great opportunity, especially when Microsoft is willing to pay for the domain name for you.
 
 
 
February 12

Creating your first 3D application in Windows Presentation Foundation (WPF) - Part II

 

5. Transform & Animation

Now that we have drawn the model and added a texture to it's surface the last thing to do is to add a little bit of animation (a static image would be pretty boring).  We are going to rotate the model in 3D around an axis that is vertical and goes straight through the centre of the model at point (0,0,-5).  To rotate in 3D we can use the RotateTransform3D class,  this class takes a set of co-ordinates around which the model will rotate and an axis of rotation (for example the x axis, y-axis or it can be any arbitary axis). 
 
To animate the rotation we can use the DoubleAnimation class, you can set the from and to value for the range of animation, plus a duration and specify if the animation should continue after one cycle.  To animate an object you call BeginAnimation and specify the property that you want to animate (these properties are specal properties called Dependency Properties in WPF - you can look these up in more detail on the web).
 
Below is the code showing how to set the transform and the animation details:
 

        private void AnimateModel(GeometryModel3D model)

        {
            //Create a rotation around the y axis
            AxisAngleRotation3D rotation = new AxisAngleRotation3D();
            rotation.Angle = 0;
            rotation.Axis = new Vector3D(0, -1, 0);
 
            //Set the point of rotation to be (0,0,5)
            RotateTransform3D transform = new RotateTransform3D();
            transform.Rotation = rotation;
            transform.CenterX = 0;
            transform.CenterY = 0;
            transform.CenterZ = -5;
 
            //Apply the transform to the model
            model.Transform = transform;
 
            //Animate the angle of the rotation transform
            DoubleAnimation angleAnimation = new DoubleAnimation();
            angleAnimation.RepeatBehavior = RepeatBehavior.Forever;
            angleAnimation.From = 0;
            angleAnimation.To = 359;
            angleAnimation.Duration = new Duration(TimeSpan.FromSeconds(10));
            rotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, angleAnimation);
        } 
 

Video of 3D application in action

Below is a link to a video showing the 3D application while it is running.  Please note the video is a little jerky due to the fact I was running Windows Media Encoder to capture the application on my old laptop, normally the demo runs beautifully, especially on a relatively capable machine.
 
 
  
Video: WPF 3D Demo - Turtle Rotate
 
So now you have seen how to create your first 3D application you should be able to investigate and create your own applications.  3D graphics are really fun, you can change your material types to give the appearances of a shiny surface, change the colour of the lightsource and all other kinds of fun things.  I will be posting more articles of tips and tricks as I figure them out :-).
 

Complete Code

The complete source code listing for the example shown in this blog post, http://themightycoder.spaces.live.com/blog/cns!EBFBA22CD769E10B!184.entry, is shown below:
 
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Media3D;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
 
namespace WpfTutorial
{
    public class MainWindow : Window
    {
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new MainWindow());
        }
 
        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);
 
            Viewport3D viewport = SetupViewport();
            //Need a container to hold our model and the light, the light object
            //inherits from Model3D
 
            Model3DGroup modelGroup = new Model3DGroup();
 
            //Without a light, all of our objects would appear black, you can shine
            //coloured light or just plain white light. You also need to specify
            //a direction for the light to shine, remember z must be negative so we
            //are shining into the screen onto the model.
            DirectionalLight light = new DirectionalLight(Colors.White, new Vector3D(0, 0, -1));
            modelGroup.Children.Add(light);
 
            //Create the 3D model, this will be the piece of paper
            //with the image texture mapped onto it
            GeometryModel3D model = CreateModel(@"c:\users\mark\turtle.jpg");
 
            //Animate the model
            AnimateModel(model);
 
            //Add the model to the model group
            modelGroup.Children.Add(model);
 
            ModelVisual3D modelVisual = new ModelVisual3D();
            modelVisual.Content = modelGroup;
            viewport.Children.Add(modelVisual);
 
            //We need to set the viewport as the content of the window
            this.Content = viewport;
        }
 
        public Viewport3D SetupViewport()
        {
            Viewport3D viewPort = new Viewport3D();
            PerspectiveCamera camera = new PerspectiveCamera();
 
            //Need to set the location of the camera, x positive is left, y positive is down
            //and z positive is away from the screen
            camera.Position = new Point3D(0, 0, 12);
 
            //The z axis is positive in the direction coming out of the screen
            //we want it to look into the screen at the model we are going to create
            camera.LookDirection = new Vector3D(0, 0, -1);
 
            //Set how view the viewing angle of the camera is, this dictates how wide the
            //viewport is
            camera.FieldOfView = 80;
 
            //Set the camera in the view port
            viewPort.Camera = camera;
 
            return viewPort;
        }
 
        public GeometryModel3D CreateModel(string imagePath)
        {
            GeometryModel3D model = new GeometryModel3D();
 
            //A model has two main parts, the Mesh which describe
            //the vertices and links between the vertices, and a
            //material which is texture mapped onto the model.
 
            //First create the material, this is going to be a
            //picture of a turtle, we need to load the image and
            //then create an ImageBrush, in WPF all surfaces are
            //painted using a brush.
            DiffuseMaterial material = new DiffuseMaterial();
            ImageBrush brush = new ImageBrush();
            brush.ImageSource = new BitmapImage(new Uri(imagePath));
            material.Brush = brush;
            model.Material = material;
 
            //For the back of the mode we will just paint it red.
            model.BackMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Red));
           
            //Next we need to create the model, this first involves specifying
            //the vertices used in the model
            MeshGeometry3D mesh = new MeshGeometry3D();
            /*
            * -5,5 (0)  ============== 5,5 (1)
            *           |            |
            *           |            |
            *           |            |
            * -5,-5 (3) ============== 5,-5 (2)
            *
            */
            Point3DCollection meshVertices = new Point3DCollection();
            meshVertices.Add(new Point3D(-5, 5, -5)); //0
            meshVertices.Add(new Point3D(5, 5, -5)); //1
            meshVertices.Add(new Point3D(5, -5, -5)); //2
            meshVertices.Add(new Point3D(-5, -5, -5)); //3
            mesh.Positions = meshVertices;
 
            //The next part is to specify how the vertices are connected together
            //to create the triangles.
            mesh.TriangleIndices.Add(3);
            mesh.TriangleIndices.Add(2);
            mesh.TriangleIndices.Add(0);
            mesh.TriangleIndices.Add(2);
            mesh.TriangleIndices.Add(1);
            mesh.TriangleIndices.Add(0);
 
            /* The texture co-ordinates should map to the order the
            * vertices were specified
            *
            * Texture
            *
            * A:(0,0) ============= B:(1,0)
            *         |           |
            *         |           |
            *         |           |
            * C:(0,1) ============= D:(1,1)
            *
            * So this maps to our vertices above as:
            * 0 => A, 1 => B, 3 => C, 4 => D
            */
 
            PointCollection textureCoordinates = new PointCollection();
            textureCoordinates.Add(new Point(0, 0));  // 0 -> A
            textureCoordinates.Add(new Point(1, 0));  // 1 -> B
            textureCoordinates.Add(new Point(1, 1));  // 4 -> D
            textureCoordinates.Add(new Point(0, 1));  // 3 -> C
            mesh.TextureCoordinates = textureCoordinates;
 
            //Add the geometry points to the model.
            model.Geometry = mesh;
 
            return model;
        }
 
        private void AnimateModel(GeometryModel3D model)
        {
            //Create a rotation around the y axis
            AxisAngleRotation3D rotation = new AxisAngleRotation3D();
            rotation.Angle = 0;
            rotation.Axis = new Vector3D(0, -1, 0);
 
            //Set the point of rotation to be (0,0,5)
            RotateTransform3D transform = new RotateTransform3D();
            transform.Rotation = rotation;
            transform.CenterX = 0;
            transform.CenterY = 0;
            transform.CenterZ = -5;
 
            //Apply the transform to the model
            model.Transform = transform;
 
            //Animate the angle of the rotation transform
            DoubleAnimation angleAnimation = new DoubleAnimation();
            angleAnimation.RepeatBehavior = RepeatBehavior.Forever;
            angleAnimation.From = 0;
            angleAnimation.To = 359;
            angleAnimation.Duration = new Duration(TimeSpan.FromSeconds(10));
            rotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, angleAnimation);
        }
    }
}