Kinect Tutorial – Hacking 101

Microsoft’s Kinect has been out for a few months now and has become a fairly popular accessory for the Xbox 360. Let’s face it though, using the Kinect for what it was intended didn’t end up being the most exciting part of this new toy. What has become far more interesting is seeing the various hacks developed that makes the device so much more than simply an input mechanism for games. Now it’s your turn to do something amazing, and this tutorial will get you started. Today I’m going to get your Kinect up and running and demonstrate how to get the camera and depth information into your very own C# application.

Example Kinect Output

Above is some example output that our app will produce. In this case it’s the corner of my office with some bookshelves and a guitar. The RGB data is on the left and the depth information is on the right. The darker things are, the closer they are to the camera.

1. Setup libfreenect

openkinect.org is going to be your best friend for this portion of the project. We’re going to be depending on libfreenect for our drivers and the library used to communicate with the Kinect. They’ve got pretty good instructions for all platforms, but since we’re doing C#, you’ll want to follow the Windows installation guide. I found the instructions to be fairly straight forward and worked without too much hassle. After you’ve followed all of those instructions return here to continue the tutorial. This portion of the project will probably take a while to complete – so be patient.

2. Setup the C# Application

Since our plan with this tutorial is just to display output, we can get away with a basic WPF application, which actually performs surprisingly well. If your app is going to do some really incredible things, you may want to consider something like DirectX or OpenGL.

New WFP Application

Bundled as part of the libfreenect source are a set of wrappers for various languages. We’re going to want the C# one (\libfreenect\wrappers\csharp). Go ahead and add the wrapper project to your new solution.

Solution Explorer

You should now be able to build the solution without any errors. Of course, since we haven’t written any code, nothing will happen when you run the app. Also, our application now depends on the freenect.dll file that was created as part of step 1. Depending on how you installed it, you may have to copy this file somewhere where you app can load it (somewhere in the path, or the project’s output directory).

3. Writing some Code

Now we’re at the meat of this tutorial, writing some code to retrieve the Kinect’s output. The first thing we’re going to do is setup the Kinect and tell it to start recording data. I did all of this in my MainWindow’s constructor.

using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using freenect;

namespace Kinect101
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window
  {
    // The kinect object.
    Kinect _kinect;

    // Whether or not the Window has been closed.
    bool _closed;

    // Prevents handlers from being called while
    // a previous one is still working.
    bool _processingRGB;
    bool _processingDepth;

    public MainWindow()
    {
      InitializeComponent();

      // See if any Kinects are connected.
      int kinectCount = Kinect.DeviceCount;

      if (kinectCount > 0)
      {
        // Get the first connected Kinect – I guess you could have more
        // than one connected.
        _kinect = new Kinect(0);

        // Open a connection to the Kinect.
        _kinect.Open();

        // Setting these to IntPtr.Zero notifies the wrapper
        // library to manage the memory for us.  More advanced apps
        // will probably provide a pointer for their own buffers.
        _kinect.VideoCamera.DataBuffer = IntPtr.Zero;
        _kinect.DepthCamera.DataBuffer = IntPtr.Zero;

        // Hook the events that are raised when data has been recieved.
        _kinect.VideoCamera.DataReceived += VideoCamera_DataReceived;
        _kinect.DepthCamera.DataReceived += DepthCamera_DataReceived;

        // Start the cameras.
        _kinect.VideoCamera.Start();
        _kinect.DepthCamera.Start();

        // Create a thread to continually instruct the Kinect
        // to process pending events.
        ThreadPool.QueueUserWorkItem(
          delegate
          {
            while (!_closed)
            {
              _kinect.UpdateStatus();
              Kinect.ProcessEvents();

              Thread.Sleep(30);
            }
          });
      }
    }

As you read through the code, it should be very self-explanatory. Basically we’re just connecting to a Kinect and telling it to start recording video and depth information. In order to events to be processed and raised by the Kinect library, we have to periodically call Kinect.ProcessEvents. Since we can’t block our main thread doing that, I just created a simple worker thread using the ThreadPool.

Now that we’ve got the Kinect setup, let’s take a look at the event handler, VideoCamera_DataReceived. This is where we’re going to receive the raw RGB data and convert it to something that can be displayed on the screen.

void VideoCamera_DataReceived(object sender, VideoCamera.DataReceivedEventArgs e)
{
  // Prevent re-entrancy so events don’t stack up.
  if (_processingRGB)
    return;

  _processingRGB = true;

  this.Dispatcher.Invoke(
    new Action(
      delegate()
      {
        // Convert the byte[] returned by the Kinect library
        // to a BitmapSource and set it as the source of our
        // RGB Image control.
        _colorImage.Source = BitmapSource.Create(
          e.Image.Width,
          e.Image.Height,
          96,
          96,
          PixelFormats.Rgb24,
          null,
          e.Image.Data,
          e.Image.Width * 3);
      }));

  _processingRGB = false;
}

Fortunately for us, this part of the project is a breeze. The Kinect library returns RGB data in a form that can be directly fed into a BitmapSource object. I added some very basic protection against this event handler being called before the previous one had completed. I noticed that as the app ran longer and longer, it got slower and slower. This simple fix seemed to address that bug. All we have to do now is feed the raw data into BitmapSource.Create and give that to our Image control, which was added to our MainWindow in the XAML. The most complicated part of the Create call is the last parameter – stride. This argument represents the number of bytes in a single row of the image. Since our image contains 3 bytes per pixel, the number of bytes in a row will by the width multiplied by 3.

Now on to depth. This one is slightly more complicated, but still not too bad.

void DepthCamera_DataReceived(object sender, DepthCamera.DataReceivedEventArgs e)
{
  if (_processingDepth)
    return;

  _processingDepth = true;

  // Create an array to hold translated image data.
  short[] image = new short[e.DepthMap.Width * e.DepthMap.Height];
  int idx = 0;

  for (int i = 0; i < e.DepthMap.Width * e.DepthMap.Height * 2; i += 2)
  {
    // Read a pixel from the buffer.
    short pixel = Marshal.ReadInt16(e.DepthMap.DataPointer, i);

    // Convert to little endian.
    pixel = IPAddress.HostToNetworkOrder(pixel);
    image[idx++] = pixel;
  }

  this.Dispatcher.Invoke(
    new Action(
      delegate()
      {
        // Create the image.
        _depthImage.Source = BitmapSource.Create(
          e.DepthMap.Width,
          e.DepthMap.Height,
          96,
          96, PixelFormats.Gray16, null, image, e.DepthMap.Width * 2);
      }));

  _processingDepth = false;
}

Depth data comes from the Kinect as 11 bits per pixel. The Kinect library packs that into a little friendlier 16 bits per pixel before passing it up to the C# wrapper and then on to us. What makes this difficult is that the bit order is big endian, whereas our Windows box needs little endian. In order to fix this, we need to read each and every pixel from the buffer and convert the endianness. Fortunately, .NET has a helper function designed for networking that comes in handy for this task – IPAddress.HostToNetworkOrder. After we’ve got all the pixels out and converted, we simply do the same thing as before to create our image. Instead of RGB format, this time we need to use Gray16, since each pixel is now represented by 2 bytes (16 bits).

And that’s it for retrieving Kinect data. If you combine this code with our XAML:

<Window x:Class="Kinect101.MainWindow"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       Closing="Window_Closing"
       Title="MainWindow" Height="350" Width="525">
  <Grid>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Image x:Name="_colorImage" />
    <Image x:Name="_depthImage" Grid.Column="1" />
  </Grid>
</Window>

and a little cleanup code:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
  _closed = true;

  // All of these seem to lock up the app.
  //_kinect.VideoCamera.Stop();
  //_kinect.DepthCamera.Stop();
  //_kinect.Close();
  //Kinect.Shutdown();
}

you should now have a working app that displays output very similar to the image below.

Example Kinect Output

All of the libraries and wrappers used for this tutorial are in constant flux. Please refer to the most up-to-date documentation before starting to make sure nothing has changed. The libraries are also pretty buggy – so be prepared for things to not work correctly right out of the box.

Hopefully this tutorial will help save you some time bootstrapping your awesome Kinect hack. As we get more time to work with the libraries, we’ll be creating some more compelling demos. If you happen to make something neat, please drop us a line so we can check it out. If you have questions or comments, feel free to leave them below.

How to Create .Net DataGridView Image Buttons

As you may have guessed by now, here at Switch On The Code, we are very big advocates of the .Net framework and all it has to offer. Sometimes however, things can be a little bit on the tricky side. Recently I ran into a tricky solution when I was trying to get image buttons in a DataGridView control, and in this tutorial I will go over the solution I came up with, which may just give you the edge the next time you need a fancy DataGridView.

DataGridViews do offer a few different column types, including fairly simple ways to brew up your own custom column types. However, none of the default column types offer a truly good solution for clickable images. What we want here is an image that does something when we click it. Sure we can have a button with an image in it if we use a Button Column, but that is not really what I am looking for. This is where the tricky solution comes in.

For a moment, we have to step back and consider all the options a DataGridView offers, especially the events that can be captured by it. One of these events happens to be CellClick, which is the key to our solution. Using this event we can capture which row and column is clicked, and therefore we can determine if one of our image cells is being clicked. Even better, we can even tell which actual cell was clicked. Using this information we can have image cells that act like buttons, and the best part is that it is not that complicated to get working.

So the first part is pretty strait forward, we need a DataGridView with some image columns. It doesn’t matter what images you use, or how you set up your columns, but you just have to keep track of the column names. Once you have your DataGridView all set up, we need to give it a couple test rows to work with, which we will do during initialization:

public Form1()
{
  InitializeComponent();
  dataGridView1.Rows.Add(5);
}

If you run the project and start clicking away, you will notice that nothing happens when you click on the image cells. This is not what we are after, but with some simple event parsing, we can get a click event going for these cells. In fact, we are going to hook to the CellClick event:

private void dataGridView1_CellClick(
  object sender, DataGridViewCellEventArgs e)
{
  string message = "Row " + e.RowIndex.ToString() + " is ";
 
  //Switch through the column names
  switch (dataGridView1.Columns[e.ColumnIndex].Name)
  {
    case "bug":
      message += "bugging you!";
      break;
    case "chance":
      message += "taking a chance!";
      break;
    case "yes":
      message += "has been marked yes!";
      break;
    case "no":
      message += "has been marked no!";
      break;
  }

  MessageBox.Show(message);
}

Basically what we are doing here is looking for specific columns when a cell is clicked. Technically, in this respect, you could use this method to tell if any specific column is clicked, like a text column as well. However, for this tutorial we just want something to happen when the user clicks on an image cell, and this code does exactly that. When the use clicks on a cell, this event is fired and we check the column of the cell that was clicked. If it is a column we are looking for, we do something, in this case we show a message.

There is one issue with this code though, it fires if ANY cell is clicked, including header cells (row and column headers). This a a fairly big issue, but one that can be fixed very easily. With a simple check, we can fix the problem:

private void dataGridView1_CellClick(
  object sender, DataGridViewCellEventArgs e)
{
  //Do nothing if a header is clicked
  if (e.RowIndex < 0 || e.ColumnIndex < 0)
    return;

  string message = "Row " + e.RowIndex.ToString() + " is ";
 
  //Switch through the column names
  switch (dataGridView1.Columns[e.ColumnIndex].Name)
  {
    case "bug":
      message += "bugging you!";
      break;
    case "chance":
      message += "taking a chance!";
      break;
    case "yes":
      message += "has been marked yes!";
      break;
    case "no":
      message += "has been marked no!";
      break;
  }

  MessageBox.Show(message);
}

With one simple if we now have a solid solution for image buttons in a DataGridView. Each time a cell in one of these columns is clicked, the corresponding message is displayed:

Clicking on an image cell

That is about it for this tutorial. I hope this quick solution helps you in your DataGridView endeavors, and just remember that when you need coding help all you have to do is Switch On The Code.

XNA Content Pipeline, Part 1 – The Pipeline and You

One of Microsoft’s most successful products in the past years has been the Xbox and Xbox 360. In the more recent years Microsoft has given us developers the chance to add our own creations to the 360 Indie Arcade with their powerful XNA framework. Using XNA, you can go from concept to finished game in literally days, and with a few more hours you can have it deployed to Indie Arcade. This is why SOTC has decided to tackle some of the concepts behind XNA, starting with the Content Pipeline.

For our first foray into the XNA content pipeline, we are going to go over the basics of what, why, and how for this pipeline thing. It can be a little bit confusing for the novice XNA developer, but once you learn about it, it becomes much easier to understand and use. So enough chit-chat, on to the Content Pipeline.

What?

In the simplest of terms, the content pipeline loads and manges the content for your game, which could be anything from a level file to a fully animated character model. The pipeline framework itself is quite complicated, but basically it helps you get your content loaded in the most efficient way possible, then gives you the tools to use and modify that content at run-time. When you are using XNA, you can load and manage content without actually using the content pipeline, but that would be severely inadvisable considering our good friends at Microsoft already provide us with the best solution.

Why?

Well, there are a whole lot of reasons why you would use the content pipeline. First off, according to Microsoft’s documentation on the subject: “The chief reason XNA Game Studio uses a Content Pipeline is to help your game run fast.” This is due to the fact that all the game assets are converted to a binary format, then stuffed inside the executable, making loading much faster. On the performance side of things, the content pipeline definitely helps.

Another thing about the content pipeline that I love is its flexibility and extensibility. While you are given a few basic importers (such as bitmap or x files) to work with by default, but lets face facts, any self respecting game project will have custom content types. I know on several occasions I have used custom level file formats. But with the content pipeline framework in your hands, you can easily create the custom handlers that allow you to use the content pipeline to do the work for you. As noted above, this gives you the best performance possible, and also cuts down the overall code you need in your game project.

Speaking of cutting code, that is definitely another reason to use the content pipeline.The code that you have to write it drastically reduced when you use the content pipeline, because most of the code has already been implemented for you. When coupled with Visual Studio, XNA allows you to literally add a file to your project and load it for use in code with just one line. While it may seem a little confusing, that one line of code, it is still quicker than the four or five lines needed to load such content in with straight C# code.

To Convert an image to and from a byte array in C# .NET:

Bitmap bmp = new Bitmap("PathToImage");
MemoryStream mStream = new MemoryStream();
bmp.Save(mstream, ImageFormat.Jpeg);
byte[] bytes = new byte[mstream.Length];
mstream.Read(bytes, 0, (int)mstream.Length);

Loading an image asset in XNA (which is in binary form already):

public static Texture2D spriteTexture;
spriteTexture = content.Load<Texture2D>("MyTexture");

To me, it is better to use this one line, especially when you consider the content pipeline is there and works, so you don’t have to worry much about things going wrong. It is cleaner, and a lot easier to understand what is going on when you have XNA doing some of the grunt work for you. We also must remember that XNA does some of this work when you compile your project, not at run-time, so it only decreases the amount of code you need even more so.

It is pretty apparent that there are many reasons to use the content pipeline. Between the faster load times and the flexibility alone, you know you want to use the content pipeline. However, the next question on all of our minds is how exactly this miracle manager works…

How?

Now we come to the confusing part of the content pipeline, how it works. It is not so straight forward, but once you throw together a few diagrams, it becomes a bit easier to understand. Lets start with the process your content takes when you build your project.

The steps an asset takes in the pipeline.

One of the reasons the content pipeline is so efficient is because your content is converted to a special file type called an XNB file when you compile your project. These XNB files have no type associated with them, and are completely binary, which makes loading a lot faster. It starts this conversion process by using an Importer to parse the file into an object. Once the asset has been “Imported”, it is passed off to a content Processor which takes the imported data and compiles it into a binary format. The final step is to take this binary data and write it out to the XNB file, and you guessed it, that is the job of the content Writer. Between these three, your asset will go from a bitmap file to a binary XNB file in no time flat.

So, the content pipeline compiles our assets into these magical XNB files, which allows our content to be loaded lightning fast. Since this happens when we build the project, it saves a lot of processing during run-time as well, but what happens during run-time? Well, there is only one really important part of the run-time loading process, the content reader. What this reader does is it takes the XNB file and parses it into an object to use in your game code. It is the only component used during run-time, which adds to the code minimization.

The best part about this is that any of these steps can be overridden and customized to fit your needs. You can write custom imports, processors, writers, and readers that parse your assets through the content pipeline, but load the data in the way you want. Essentially, you could write your own data types for the pipeline to handle.

So now you know what the content pipeline is, and why to use it. We also went over how it works, and the basic steps XNA takes to load and manage your assets. Its a lot to take in on a purely knowledge standpoint, but once your start digging it, it gets a lot simpler. This is it for this installment into the content pipeline, but keep an eye out for the next one, because we will be going over what it will all look like in your code. Just remember, when you need coding help, all you have to do is Switch On The Code.

"Importing" Old Emails into Google Apps for Domain Gmail

As the nerds we are, we have a natural affinity for Google and its many benefits. However, on the other hand, as nerds we also like to have our own custom way of doing things. This is especially true when it comes to email. Google has a lot to offer us with Gmail, but most of use enjoy having our own domain to tack on the end of our name, [email protected] for example (please do not email frank, he is not affiliated with SOTC). But what happens if you decide to move your domain management over to google apps and have 10,000 emails to move? This is what I am going to show you today, how to transfer you beloved emails to your shiny new Gmail account.

Now google itself has a very limited support for uploading your old emails into your Gmail account. This is understandable considering Gmail is designated more for a “from the beginning” approach of email management. However, there are a few ways you can get emails from an old account into your new Gmail account.

Quick Steps

1. Try the desktop uploaders.
2. If the desktop software failed to upload your email, setup your Gmail for IMAP access
3. Add your Gmail account to a desktop Email client, such as Outlook, along with your old email account.
4. Using the desktop client, move your Email from your old account to your new Gmail account.

The Details

The first way you can transfer mail to Gmail is to use the “official” email uploaders. However, if you are on windows, you might find it a bit more difficult to get the uploader to work for you. I know I had quite a bit of trouble getting the Outlook uploader to work. If you use Outlook though, you might have more luck than I did, so its worth a try. The Mac versions seems to be a bit more flexible, so if you do happen to use a mac for your email, I would try to use that before trying anything else.

If the uploaders don’t work out too well (as they did for me), then your second option is what I like to call a “hard transfer.” This involves using an email client, such as Outlook or Thunderbird, to transfer the Email manually from one inbox to the other. This takes a bit more time than the automatic uploaders, but it gets the job done.

The first step is to turn on IMAP access to your Gmail account, only temporarily. To do this, you have to go to Settings in Gmail, then to Forwarding and POP/IMAP, and finally enable IMAP Access. Here is a screenshot to help you out:

Enabling IMAP Access in Gmail

Once that is done, all you have to do is setup the IMAP account in the desktop client you will be using, which you can find out how to do for most clients here. Using Gmail labels, you can even set up folders to move specific mail into, that is if you use folders and filtering. The simplest way I found to do the job is to just move all your mail in the Inbox, then transfer it to your Gmail inbox. But, you can transfer your Emails from any folder to any folder, so you can organize the transfer any way you want. All you have to do is move your Emails from one account to another. In most clients you can simply click-and-drag emails across accounts.

And that’s it. It is as simple as loading up two accounts and dragging mail from one to another. I hope if you ever need to transfer mail to Gmail this helps you get the job done. Just remember, when you need tech help, all your have to do is Switch On The Code.

"Importing" Your Old Emails to Gmail

As the nerds we are, we have a natural affinity for Google and its many benefits. However, on the other hand, as nerds we also like to have our own custom way of doing things. This is especially true when it comes to email. Google has a lot to offer us with Gmail, but most of use enjoy having our own domain to tack on the end of our name, [email protected] for example (please do not email frank, he is not affiliated with SOTC). But what happens if you decide to move your domain management over to google apps and have 10,000 emails to move? This is what I am going to show you today, how to transfer you beloved emails to your shiny new Gmail account.

Now google itself has a very limited support for uploading your old emails into your Gmail account. This is understandable considering Gmail is designated more for a “from the beginning” approach of email management. However, there are a few ways you can get emails from an old account into your new Gmail account.

Quick Steps

1. Try the desktop uploaders.
2. If the desktop software failed to upload your email, setup your Gmail for IMAP access
3. Add your Gmail account to a desktop Email client, such as Outlook, along with your old email account.
4. Using the desktop client, move your Email from your old account to your new Gmail account.

The Details

The first way you can transfer mail to Gmail is to use the “official” email uploaders. However, if you are on windows, you might find it a bit more difficult to get the uploader to work for you. I know I had quite a bit of trouble getting the Outlook uploader to work. If you use Outlook though, you might have more luck than I did, so its worth a try. The Mac versions seems to be a bit more flexible, so if you do happen to use a mac for your email, I would try to use that before trying anything else.

If the uploaders don’t work out too well (as they did for me), then your second option is what I like to call a “hard transfer.” This involves using an email client, such as Outlook or Thunderbird, to transfer the Email manually from one inbox to the other. This takes a bit more time than the automatic uploaders, but it gets the job done.

The first step is to turn on IMAP access to your Gmail account, only temporarily. To do this, you have to go to Settings in Gmail, then to Forwarding and POP/IMAP, and finally enable IMAP Access. Here is a screenshot to help you out:

Enabling IMAP Access in Gmail

Once that is done, all you have to do is setup the IMAP account in the desktop client you will be using, which you can find out how to do for most clients here. Using Gmail labels, you can even set up folders to move specific mail into, that is if you use folders and filtering. The simplest way I found to do the job is to just move all your mail in the Inbox, then transfer it to your Gmail inbox. But, you can transfer your Emails from any folder to any folder, so you can organize the transfer any way you want. All you have to do is move your Emails from one account to another. In most clients you can simply click-and-drag emails across accounts.

And that’s it. It is as simple as loading up two accounts and dragging mail from one to another. I hope if you ever need to transfer mail to Gmail this helps you get the job done. Just remember, when you need tech help, all your have to do is Switch On The Code.

Saving Settings using NSUserDefaults Class

Saving simple configuration options can be a chore unless you’ve found the right object. Today we’re going to cover the NSUserDefaults object, which makes saving settings quick and easy. The app we’re going to build as an example is a basic segmented control that will remember which button you’ve selected between launches.

The NSUserDefaults class works a lot like a dictionary. For a given key, you can provide most primitive types and a few object types – NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. The values are stored in a database and are cached to increase performance if they’re being requested often.

The data will automatically be saved back to disk periodically, however you’ll still have to manually invoke synchronize when the application is about to exit.

Adding a UISegmentedControl is pretty basic, so I’ll leave that up to you. What this tutorial will cover is how to update the database when the selection changes and how to set the index when the app loads. First up, we’ll catch the event that occurs when the index changes and save the index.

(IBAction)selectionChanged:(id)sender {
  NSInteger index = ((UISegmentedControl*)sender).selectedSegmentIndex;
 
  // Get the shared defaults object.
  NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
 
  // Save the index.
  [settings setInteger:index forKey:@"MySelectedValueKey"];
 
  // Write them to disk – this is optional here,
  // but should be done when the app exits.
  [settings synchronize];
}

As you can see, it’s pretty simple to save things. I first get the selected index from the UISegmentedControl, then I save it with the key, “MySelectedValueKey”. The key can be anything you want and should probably be set using a #define. The last thing I do is synchronize the database, which will write all changes back to disk. This doesn’t have to be done here, but should at least be done when the application exits, or you may risk losing your setting.

The next thing we need to do is set the selected index when the application launches.

(BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
   
  // Override point for customization after application launch.
   
  [self.window makeKeyAndVisible];
 
  // Get the settings and set the selected index.
  NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
  if([settings objectForKey:@"MySelectedValueKey"] != nil) {
    options.selectedSegmentIndex = [settings integerForKey:@"MySelectedValueKey"];
  }
   
  return YES;
}

NSUserDefaults doesn’t have a great way to see if a key exists. Since objectForKey will return nil if there’s nothing there, I like using that method. If something is there, then I use the more specific integerForKey method and set the selected index to the value stored in the database.

And that’s all there is to it. Every time the user launches the app, it will set the selected segment to whatever they last chose. As you can see, the NSUserDefaults object is a great way to store simple settings without all the hassle of file I/O or sqlite access. If you have any questions, feel free to leave them below or check out the forums.

Spam Filter Gone Wild

It appears as though our spam filter has been running amok marking anything and everything as spam. We noticed a definite drop in comment volume, but failed to find where our new spam filter was putting all the marked content. Well, we found it, and whereas I tried to release everything that wasn’t spam, some things were left irretrievable.

If you’ve been attempting to comment these past few weeks, we apologize for the inability to do so. The spam system has been essentially disabled while we search for another alternative.

C# Code Generation

Code generation is a big part of most modern frameworks. .NET is full of code generators that you’ve probably used – maybe without even knowing it. XAML files are converted to .g.cs files that are then fed to the compiler at compilation time. WCF is bundled with a code generator that will convert a WSDL file to a client to easily connect to existing web services. Today’s tutorial will cover how to use objects provided by the .NET framework to build your own code generator.

The code we’re going to generate today won’t be especially useful, however it will demonstrate a lot of the available functionality. I’m going to use C# to generate another C# class that can hold part of someone’s Twitter feed.

The .NET namespace that makes all this possible is System.CodeDom. Much like the name implies, these classes allow you to build a “DOM” of class hierarchies and then dump them out to text.

The first thing you should check out before starting is a Twitter feed – I would suggest Switch On The Code’s. There’s a lot of available elements in a feed, however I’m only really interested in a couple for this tutorial – date, text, and source.

All right, let’s start generating some code. Like any other C# class, we’re going to need to start with a namespace.

using System.CodeDom;
using Microsoft.CSharp;
using System.IO;

namespace CodeGeneration
{
  class Program
  {
    static void Main(string[] args)
    {
      CodeCompileUnit compileUnit = new CodeCompileUnit();

      // Add a namespace.
      CodeNamespace twitterNamespace = new CodeNamespace("TwitterClient");
      compileUnit.Namespaces.Add(twitterNamespace);
 
      // Write the code to a file.
      using (var fileStream = new StreamWriter(File.Create(@"C:\outputfile.cs")))
      {
        var provider = new CSharpCodeProvider();
        provider.GenerateCodeFromCompileUnit(compileUnit, fileStream, null);
      }
    }
  }
}

The root of every code DOM is the CodeCompileUnit. Inside it I create and add a CodeNamespace. Lastly, I use a CSharpCodeProvider to write the code I just generated to a file.

//——————————————————————————
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//——————————————————————————

namespace TwitterClient {
   
}

Out of the box, there’s not much going on. It created some comments at the top and our namespace. We now need a class inside this namespace to hold a single Tweet.

// Add a Tweet class.
CodeTypeDeclaration twitterClass = new CodeTypeDeclaration("Tweet");
twitterClass.IsClass = true;
twitterClass.Attributes = MemberAttributes.Public;
twitterNamespace.Types.Add(twitterClass);

Our generated class is now up to this:

namespace TwitterClient {
   
   
    public class Tweet {
    }
}

A class isn’t very useful if it can’t hold anything, let’s add some fields to hold the date, text, and source of the tweet.

// Create a field to hold the date.
CodeMemberField dateField = new CodeMemberField(typeof(DateTime), "_date");
dateField.Attributes = MemberAttributes.Private;
twitterClass.Members.Add(dateField);

// Create a field to hold the text.
CodeMemberField textField = new CodeMemberField(typeof(string), "_text");
dateField.Attributes = MemberAttributes.Private;
twitterClass.Members.Add(textField);

// Create a field to hold the source.
CodeMemberField sourceField = new CodeMemberField(typeof(string), "_source");
dateField.Attributes = MemberAttributes.Private;
twitterClass.Members.Add(sourceField);

We now need properties to access each of these fields. There’s a lot of syntax required to make a property, so I created a simple helper function to make this a little cleaner.

/// <summary>
/// Creates a public property with getters and setters that wrap the
/// specified field.
/// </summary>
/// <param name="field">The field to get and set.</param>
/// <param name="name">The name of the property.</param>
/// <param name="type">The type of the property.</param>
/// <returns></returns>
static CodeMemberProperty CreateProperty(string field, string name, Type type)
{
  CodeMemberProperty property = new CodeMemberProperty()
  {
    Name = name,
    Type = new CodeTypeReference(type),
    Attributes = MemberAttributes.Public
  };

  property.SetStatements.Add(
    new CodeAssignStatement(
      new CodeFieldReferenceExpression(null, field),
          new CodePropertySetValueReferenceExpression()));

  property.GetStatements.Add(
    new CodeMethodReturnStatement(
      new CodeFieldReferenceExpression(null, field)));

  return property;
}

Since implicit properties are syntactic sugar added to C#, they’re not supported by the CodeDom. This means we need to explicitly create getters and setters for our private fields we added earlier. The setter is created by using a CodeAssignStatement. This object takes two parameters – essentially the left and right sides of the assignment. The left side is the field we want to assign. I passed null as the first parameter to CodeFieldReferenceExpression because I didn’t want an object before the field name (object.fieldname) since the field exists within this class. The right side of the assignment is a special expression to represent the value keyword.

Let’s now call this function to add our properties.

// Add a property for date.
twitterClass.Members.Add(CreateProperty("_date", "Date", typeof(DateTime)));

// Add a property for text.
twitterClass.Members.Add(CreateProperty("_text", "Text", typeof(string)));

// Add a property for source.
twitterClass.Members.Add(CreateProperty("_source", "Source", typeof(string)));

If we combine all of the code and run it, our class now looks like this:

//——————————————————————————
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//——————————————————————————

namespace TwitterClient {
   
   
    public class Tweet {
       
        private System.DateTime _date;
       
        private string _text;
       
        private string _source;
       
        public virtual System.DateTime Date {
            get {
                return _date;
            }
            set {
                _date = value;
            }
        }
       
        public virtual string Text {
            get {
                return _text;
            }
            set {
                _text = value;
            }
        }
       
        public virtual string Source {
            get {
                return _source;
            }
            set {
                _source = value;
            }
        }
    }
}

That’s it for a class that holds basic information about a tweet. You may notice the virtual keyword applied to each property. I can’t figure out how to remove this, however it won’t affect how the class is used. We now need some way to store a collection of these. Let’s create a class that extends a generic List of Tweet objects.

// Add a class to hold a collection of tweets.
twitterNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
CodeTypeDeclaration twitterCollection = new CodeTypeDeclaration("Tweets");
twitterCollection.BaseTypes.Add(new CodeTypeReference("List",
  new CodeTypeReference("Tweet")));

twitterNamespace.Types.Add(twitterCollection);

In order to make this file compile, we first need to include an import to System.Collections.Generic. We then add a new type that extends List. The List takes an argument for it’s generic – in this case it’s the type for the generic – or our Tweet class. That’s it for our code, we can run this one last time and see our output.

//——————————————————————————
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//——————————————————————————

namespace TwitterClient {
    using System.Collections.Generic;
   
   
    public class Tweet {
       
        private System.DateTime _date;
       
        private string _text;
       
        private string _source;
       
        public virtual System.DateTime Date {
            get {
                return _date;
            }
            set {
                _date = value;
            }
        }
       
        public virtual string Text {
            get {
                return _text;
            }
            set {
                _text = value;
            }
        }
       
        public virtual string Source {
            get {
                return _source;
            }
            set {
                _source = value;
            }
        }
    }
   
    public class Tweets : List<Tweet> {
    }
}

For completeness, here’s the entirety of the code required to generate the above example:

using System.CodeDom;
using Microsoft.CSharp;
using System.IO;
using System;

namespace CodeGeneration
{
  class Program
  {
    static void Main(string[] args)
    {
      CodeCompileUnit compileUnit = new CodeCompileUnit();

      // Add a namespace.
      CodeNamespace twitterNamespace = new CodeNamespace("TwitterClient");
      compileUnit.Namespaces.Add(twitterNamespace);

      // Add a Tweet class.
      CodeTypeDeclaration twitterClass = new CodeTypeDeclaration("Tweet");
      twitterClass.IsClass = true;
      twitterClass.Attributes = MemberAttributes.Public;
      twitterNamespace.Types.Add(twitterClass);

      // Create a field to hold the date.
      CodeMemberField dateField = new CodeMemberField(typeof(DateTime), "_date");
      dateField.Attributes = MemberAttributes.Private;
      twitterClass.Members.Add(dateField);

      // Create a field to hold the text.
      CodeMemberField textField = new CodeMemberField(typeof(string), "_text");
      dateField.Attributes = MemberAttributes.Private;
      twitterClass.Members.Add(textField);

      // Create a field to hold the source.
      CodeMemberField sourceField = new CodeMemberField(typeof(string), "_source");
      dateField.Attributes = MemberAttributes.Private;
      twitterClass.Members.Add(sourceField);

      // Add a property for date.
      twitterClass.Members.Add(CreateProperty("_date", "Date", typeof(DateTime)));

      // Add a property for text.
      twitterClass.Members.Add(CreateProperty("_text", "Text", typeof(string)));

      // Add a property for source.
      twitterClass.Members.Add(CreateProperty("_source", "Source", typeof(string)));

      // Add a class to hold a collection of tweets.
      twitterNamespace.Imports.Add(
        new CodeNamespaceImport("System.Collections.Generic"));
      CodeTypeDeclaration twitterCollection =
        new CodeTypeDeclaration("Tweets");
      twitterCollection.BaseTypes.Add(new CodeTypeReference("List",
        new CodeTypeReference("Tweet")));

      twitterNamespace.Types.Add(twitterCollection);
 
      // Write the code to a file.
      using (var fileStream = new StreamWriter(File.Create(@"C:\outputfile.cs")))
      {
        var provider = new CSharpCodeProvider();
        provider.GenerateCodeFromCompileUnit(compileUnit, fileStream, null);
      }
    }

    /// <summary>
    /// Creates a public property with getters and setters that wrap the
    /// specified field.
    /// </summary>
    /// <param name="field">The field to get and set.</param>
    /// <param name="name">The name of the property.</param>
    /// <param name="type">The type of the property.</param>
    /// <returns></returns>
    static CodeMemberProperty CreateProperty(string field, string name, Type type)
    {
      CodeMemberProperty property = new CodeMemberProperty()
      {
        Name = name,
        Type = new CodeTypeReference(type),
        Attributes = MemberAttributes.Public
      };

      property.SetStatements.Add(
        new CodeAssignStatement(
          new CodeFieldReferenceExpression(null, field),
              new CodePropertySetValueReferenceExpression()));

      property.GetStatements.Add(
        new CodeMethodReturnStatement(
          new CodeFieldReferenceExpression(null, field)));

      return property;
    }
  }
}

There you have it. This tutorial demonstrated how to generate classes, fields, properties, generics, and inheritance. The sky’s the limit on how you can put code generation to use for you and your projects. If you’ve got any questions or comments, please leave them below or check out the forums.

Updated Switch On The Code Spam Filtering

Hey everyone, we’re still here and wanted to update our readers with something we changed here on the site. One thing we get a lot of here at Switch On The Code is spam, mostly comment spam on posts. This causes a couple issues, first is trying to put something in place to reduce the amount of manual work done to remove spam. On this front we have long used the hashcash module which has performed decently. It captures nearly all of the spam comments we were getting but has a problem stopping legitimate people from posting comments. Not to mention the module is not being actively developed at all. So, we changed what we are using.

The Spam module is our new filtration system. It uses a combination of filters to check the content of a post (comment) and decide whether it is spam or not. Basically each filter that is run on the content gives it a score of 1-99, 1 being the worst spam possible and 99 being good content. Once done the values are averaged and if the average score fall under a threshold then the post is marked as spam and thrown into spam hell. What this all means it is takes a little bit of work to get everything setup perfectly and that means there will some false positives (not many we hope) and some spam that gets through (more likely). While you can speculate what settings will work best the only real way to get it dialed in is run it on the actual site. Which we are doing.

Please bear with us if you see any spam in comments on post and we are really, really sorry if your comment doesn’t make it through. I promise we will improve the spam filters as time goes by. If you have any other suggestions or use something different on Drupal then let us know and we’ll check it out as well.

Qt Developer Days 2010

Today concludes Nokia’s Qt 2010 Developer Days. As an attendee, I’d say the conference was a success. Like many conferences, this one was split into tracks and sessions. One track was dedicated to technical information and the other was full of people from the community demonstrating how they’ve used Qt to solve their problems. As someone new to Qt, I found the conference to be extremely valuable and informative.

The main conference is two days long, however they offer a pre-conference training day to those that are interested. This was probably the most valuable part for me. Unlike pretty much every person at this conference, I’ve never used Qt. I would have been lost for the main conference had they not offered the “Qt Fundamentals” training day.

I immediately found out it’s not pronounced “Q.T.” – it’s actually pronounced “cute”. This added a layer of hilarity to the entire conference – as I can’t count the number of times I heard the phrase “cute engineer” or “cute guy”.

The number of attendees this year was stated to be 650, which has more than doubled from two years ago. I don’t see any reason why the event won’t continue to grow and expand to larger venues.

The conference kicked off with a series of keynote addresses that was highlighted by Inder Sidhu – the Senior Vice President of Strategy and Planning for Worldwide Operations at Cisco – who presented “Doing Both” – an incredible insight into Cisco’s business philosophy.

Every session was informative and put together well. It might be because the same conference took place in Munich just a few weeks earlier, so they had time to iron out the wrinkles. The difficulty of most sessions ranged from beginner to medium-advanced. As for me, this worked out well, but I did talk to one other developer that wanted a little more in-depth information. Most presenters talked about the area of Qt they were actually developing, which made them extremely knowledgable for post-session Q&A.

There was definitely an emphasis on Qt Quick. Qt Quick is tailored for quick UI development for mobile devices. Nokia is moving entirely to Qt for their mobile phones, so it makes sense that they would invest heavily in this technology. At the moment, Quick is centered around QML, which is an impressively powerful declarative markup language.

Like every other conference I’ve attended, the most fun I had was interacting with other developers. I met several people from around the world and had a great time sharing what we do and how we use Qt. Nokia added an extra layer to this with “Dinner with the Trolls” (Qt developers are called Trolls). This was a dinner where the Qt developers were all spread out so pretty much everyone got to eat and talk with them.

The hotel that hosted the event did an incredible job – the food was great, the session areas were always clean, and the staff was exceptionally nice and helpful. It’s clear that hotel does its fair share of events like this. There was even a person that walked around playing a small Xylophone when it was time to start the next event.

I went from someone who never touched Qt to someone that can sit down and hammer out an app in a matter of minutes. Look forward to some tutorials on this site as I get chances to use the technology (especially Qt Quick). As for the conference, if you have a chance to attend in the future, I would highly recommend it.

WPF Tutorial – Binding without XAML

The introduction of binding and XAML has made creating user interfaces in .NET a much more enjoyable experience compared to previous incarnations. Binding is such an integral part of the WPF experience that most developers thoroughly understand how to do it in XAML, however what we’re going to look at today is how to create a binding using only C# code.

I’m going to build a very basic example application – it has a TextBlock and a TextBox. Whatever is typed into the TextBox, will be reflected in the TextBlock. Here’s a screenshot of what I’m talking about:

Example App Screenshot

This application lends itself perfectly to XAML binding, and in fact that’s the first way I implemented it.

<Window x:Class="BindingWithoutXAML.MainWindow"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       Title="MainWindow"
       Height="350"
       Width="525">
  <Grid Margin="10">
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="10" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBox x:Name="textBox"
            VerticalAlignment="Center" />

    <TextBlock x:Name="textBlock"
              VerticalAlignment="Center"
              Grid.Column="2"
              Text="{Binding ElementName=textBox, Path=Text,
                       UpdateSourceTrigger=PropertyChanged}" />

  </Grid>
</Window>

You can clearly see my two controls and the binding that links the two. Whenever the Text property of the TextBox changes, the Text property of the TextBlock will be updated. Now let’s move the binding to the code-behind.

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
   public MainWindow()
   {
      InitializeComponent();

      // Create a binding object for the Text property of the TextBox.
      Binding binding = new Binding("Text");

      // Set the binding to update whenever the property changes.
      binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

      // Set the source object of the binding to the TextBox.
      binding.Source = textBox;

      // Add the binding to the TextBlock.
      textBlock.SetBinding(TextBlock.TextProperty, binding);
   }
}

You can definitely see the correlation between the XAML and the C#. The first thing we do is create a Binding object and tell it to bind to the Text property of its source object. We then tell the binding to update the destination property whenever the source property changes. We then give it the actual source object – the one that owns the property “Text”. Lastly we set the binding on the destination object and specify the property we’d like to bind to. If we run the application, we’d get the exact same behavior.

It’s not always obvious where you’ll need to specify bindings in the C# code, but one scenario I’ve encountered in the past is that my source object doesn’t exist right away. Sometimes I need to delay the binding until it does, and XAML doesn’t have the ability to wait until the source property exists before creating and applying the binding.

In this tutorial you’ve learned how to create bindings without using XAML. If you’ve got questions or comments, please leave them below or check out the forums.

Have You Heard? BirdBot is the Word

Every now and then I get to work on some really cool stuff at HyperQuake. Today HyperQuake launched something I have been working on (with others) to create, the BirdBot Factory. The basic idea is that you can design your own paper craft robot bird – tell me that isn’t sweet.

So here are couple pics that show off some of the online and printed out bots.

Finally, for good measure here is the video on how to put one of the printed bots together.

<!–

Get Adobe Flash player

<!–

On the technical side of things we built the site using Flex 3 & 4 with Away3D for viewing the bot as you create it. We also take advantage of the new Flash 10 ability to download files. Once the bot is created on the front end we send the details to our PHP backend which creates the PDF to download.

Anyway, I hope everyone gets a chance to play around with it. It’s a very cool fun way to spend a little bit of time.

WPF Tutorial – Binding to a TabControl

Here’s a very basic scenario – you’ve got a collection of items and you’d like to display a tab for each one inside a TabControl. The TabControl exposes a property called ItemsSource, however setting up the templates to control how to display your data is not quite as straight forward as you might think.

The example data we’re going to work with today are reviews for the movie Inception. First we need a class to represent a review.

/// <summary>
/// Class representing a single movie review.
/// </summary>
public class Review
{
  /// <summary>
  /// The name of the critic who provided the review.
  /// </summary>
  public string Critic { get; set; }

  /// <summary>
  /// A snippet of the critic’s full review.
  /// </summary>
  public string ReviewSnippet { get; set; }

  /// <summary>
  /// Letter grade representing the review.  A-F.
  /// </summary>
  public string LetterGrade { get; set; }
}

All right, now that we’ve got an object let’s populate the data. I’m pulling the reviews Yahoo! Movies.

public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();

    // Create some reviews.
    var reviews = new List<Review>
    {
      new Review()
      {
        Critic = "Wesley Morris",
        LetterGrade = "B",
        ReviewSnippet = "For better and worse, it weighs nothing, " +
        "which is not the same as saying it means nothing."
      },

      new Review()
      {
        Critic = "Roger Ebert",
        LetterGrade = "A-",
        ReviewSnippet = "Like the hero of that film, the viewer " +
        "of Inception is adrift in time and experience."
      },

      new Review()
      {
        Critic = "Michael Phillips",
        LetterGrade = "B",
        ReviewSnippet = "Nolan conjures up a fever dream."
      }
    };

    // Set the ItemsSource of the TabControl
    // to the collection of reviews.
    _myTabControl.ItemsSource = reviews;
  }
}

All I did here was copy and paste Yahoo’s review data into our new object. I then set the ItemsSource of the TabControl to the collection of reviews. The TabControl was added to my Window using XAML and the name was set to _myTabControl. If we compile and run it now, we won’t get anything very helpful.

TabControl with no templates

In order to display our data in a meaningful way, we’re going to have to specify two templates. One for the header (ItemTemplate) and one for the tab contents (ContentTemplate).

<Window x:Class="TabControlBinding.MainWindow"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       Title="MainWindow"
       Height="350"
       Width="525">
  <Grid>
    <TabControl x:Name="_myTabControl"
               Margin="10">

      <!– Header –>
      <TabControl.ItemTemplate>
        <DataTemplate>
          <!– Critic Name –>
          <TextBlock Text="{Binding Critic}" />
        </DataTemplate>
      </TabControl.ItemTemplate>

      <!– Content –>
      <TabControl.ContentTemplate>
        <DataTemplate>
          <Grid Margin="5">
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="Auto" />
              <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
              <RowDefinition Height="Auto" />
              <RowDefinition Height="5" />
              <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <!– Grade –>
            <TextBlock Text="Grade: "
                      TextAlignment="Right" />
            <TextBlock Text="{Binding LetterGrade}"
                      Grid.Column="1" />

            <!– Review Snippet –>
            <TextBlock Text="Review: "
                      TextAlignment="Right"
                      Grid.Row="2" />
            <TextBlock Text="{Binding ReviewSnippet}"
                      TextWrapping="Wrap"
                      Grid.Row="2"
                      Grid.Column="1" />

          </Grid>
        </DataTemplate>
      </TabControl.ContentTemplate>

    </TabControl>
  </Grid>
</Window>

Each tab’s header now contains the name of the critic who provided the review. The contents of each tab contain the letter grade and the snippet. When we run this code, we now get something that works a little better.

TabControl with templates

That wraps up this tutorial. You now know how to quickly and easily populate a TabControl from a collection and customize its look and feel. If you have any questions or comments, feel free to leave them below.

Create an Offline iPhone Web Application

Recently, I have been playing around with building web applications for the iPhone and really wanted to try make the experience as close to a native application as possible. One big way to make the experience much better is by caching the application so it can be used offline. So, that’s what I am going to show you how to do today. We are going to be using a new feature in HTML5 called a Cache Manifest file. This file will allow you to tell the browser to cache the application for offline use. If you combine this with HTML5 Web Storage you can really build some compelling experiences.

The application we are going to build today is really simple. It’s just a screen with some text on it. A motivator application of sorts. You can see a screen of it below. You can also check out the application. It’s intended to be viewed on an iPhone, that way you can test the offline functionality.

The html code for the application is very simple. I’m going to just throw it out here and explain the pieces after.

<!DOCTYPE HTML>
<html manifest="build.manifest">
<head>
<meta name="viewport" content="width=device-width">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="stylesheet" href="style.css">
<link rel="apple-touch-startup-image" href="startup.png">
<title>Make Stuff</title>
</head>
<body>
<div id="main">
  <h1>Build Something Cool<br/><br/>{ }</h1>
</div>
</body>
</html>

Starting from the top, we have the standard HTML5 doctype. The next line is where we have the root html element and we have attribute manifest which is where we tell the browser where to find our cache manifest file. The first line of the head tells the browser to resize the content to the width of the device, so for an iPhone this is going to be 320 pixels. The lines following that are mobile webkit specific meta tags which says the application is capable of a standalone application and that the status bar when running the application standalone should be black. We then link to our css and link to a mobile webkit specific item which is our startup screen for the standalone application.

The rest of the code should be familiar. We have a single div with some text. For reference the css follows.

body {
  font-family: Helvetica, Arial, sans-serif;
  background: #E82C0C;
  color: #F5F5F5;
}

h1 {
  font-size: 3em;
  text-transform: uppercase;
  text-align: center;
}

The main thing we want to talk about is the manifest file. The format for this file is very simple. You start by having the words CACHE MANIFEST and then list the files that you want to have cached. The file locations are relative to the location of the manifest file. For a large application this may be a lot of files, images, javascript, css, and more. However, this little application just has two files we are worried about – the index.html and style.css. The file ends up looking like the following.

CACHE MANIFEST

index.html
style.css

Now you probably think that is everything you need to do. But wait there is one more thing. In order to serve up the manifest file correctly you need to add a new mime type to your web server. The new mime type for .manifest files is text/cache-manifest. And that is everything you need.

As mentioned earlier you can test out the application and add it to your home screen by going to its dedicated page. If you have any issues or questions feel free to leave a comment or head on over to the forums.

How to Create and Populate a UITableView

It seems like every time I create an iOS application I use the UITableView. It’s a very common control found in a lot of applications, however it’s also one of the most difficult controls to use. Every time I use one I have to go out and find examples so I can remember what I’m supposed to do. Because of that, I decided to create a basic tutorial that wraps up the most common usage patterns for the UITableView.

I’m going to start with an empty Window-based application. If you’re new to iOS development, we’ve got a good starter tutorial that will help you get on your feet. Next I’m going to create a UIViewController subclass called MyTableViewController.

New File Dialog

Remember to modify the app delegate to display our new view.

(BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
   
    // Override point for customization after application launch.
 
  tableViewController = [[MyTableViewController alloc]
                         initWithNibName:@"MyTableViewController" bundle:nil];
  [window addSubview:tableViewController.view];
   
  [window makeKeyAndVisible];
   
  return YES;
}

Along with the view controller, a .xib file was also created. Let’s double-click that to bring up Interface Builder. The first thing we need to do is drag a Table View onto our new view.

Drag Table View

The Table View gets all its functionality through a delegate and a data source. The data source is called upon when it needs to know what data to display. The delegate is used to provide feedback – like when a selection is made. What we’re going to do is make our new view controller implement both of these. The first thing we need to do is make the connections in Interface Builder. With the Table View selected, view the “Connections Inspecter”. At the top of the outlets section you’ll see the two outlets I just mentioned. Grab those dots with your mouse and drag them to the Documents Window and drop them on the item named “File’s Owner”. This is what represents our MyTableViewController class.

Setting Outlets

We’re now done with Interface Builder – save the document and return to Xcode. We now need to tell our new class to implement these protocols. This will be done in the header – MyTableViewController.h.

#import <UIKit/UIKit.h>

@interface MyTableViewController :
  UIViewController <UITableViewDataSource, UITableViewDelegate> {

}

@end

That’s actually it for the header file – we can now move on to some implementation. If you built the project now you’d see some warnings for incomplete implementations. This is because we haven’t provided the needed functions to be a data source or delegate.

Let’s start with the data source. There are only two required methods to be a UITableViewDataSource. You have to provide the number of rows and provide cells to display. Let’s start with the number of rows.

(NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
  return 10;
}

What we’re creating is the simplest form of table – it contains one section with some rows. In this case, I’m telling the table it will have ten rows. The next thing we need to do, and by far the most complicated, is provide cells for the table to display. The reason this is so complicated is because cells can (and should) be reused in order to reduce memory and improve performance. I’ll just stick the code out there first and explain it afterwards.

(UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  // Identifier for retrieving reusable cells.
  static NSString *cellIdentifier = @"MyCellIdentifier";
 
  // Attempt to request the reusable cell.
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
 
  // No cell available – create one.
  if(cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                  reuseIdentifier:cellIdentifier];
  }
 
  // Set the text of the cell to the row index.
  cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];
 
  return cell;
}

Starting at the top and working our way down. The first thing we need to do is create a way to identify reusable cells. This is done through a simple static string. I then attempt to dequeue a reusable cell with that identifier. If one is not available, I create a new one. Here I’m initializing a cell with the default cell style and setting its reuse identifier to our static string. The last thing to do is simply set the text of the cell to something – in my case I’m using the row index. You should now be able to build and run this application.

iPhone Example

The last thing we need is some kind of notification when the user selects an item. This is done through the UITableViewDelegate protocol. We only need to implement one method for this functionality.

(void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 
  // Show an alert with the index selected.
  UIAlertView *alert = [[UIAlertView alloc]
                        initWithTitle:@"Item Selected"                        
                        message:[NSString stringWithFormat:@"Item %d", indexPath.row]                    
                        delegate:self      
                        cancelButtonTitle:@"OK"          
                        otherButtonTitles:nil];
        [alert show];
        [alert release];
}

Now, whenever an item is selected an alert will be displayed with the index of the row selected.

Selected Row

And there you have it. We’ve successfully created and populated a UITableView control. I have to say, of all the controls that display a list of data, this one is by far the hardest and most verbose to use. Now whenever you need to create a Table View, just remember you can come here and copy and paste all the boilerplate code – I know I will. You can download the complete source of this tutorial below. And as always, feel free to ask questions or leave comments.