Loading XML Through XNA Content Pipeline

XNA is quite possibly one of the most robust game programming frameworks out there. You can do nearly anything with it, and one of the reasons it is so flexible is its “Content Pipeline”. But sometimes it can be a bit tricky to use this feature, requiring us to do bit more work. But in the end, it helps to use the Content Pipeline. Luckily today we are going over how to use it to load in some XML.

A quick google search will reveal that loading in XML with C# and XNA can be a bit more complicated that it seems. There are several ways to accomplish XML integration, all dependent on your needs. Today we are going to go over the simplest way to load XML in XNA using the fancy Content Pipeline.

For the best viewing, use full screen mode.

<!–

Get Adobe Flash player

<!–

Installing and Running Google Go on Mac OS X

A while ago Google gave us a brand new language, Go. In the last couple of years I really haven’t heard much about it, but I decided to finally install it and give it a try. This tutorial will guide you step-by-step on how to install Google Go and start writing your own applications.

Go’s website has very good instructions on how to install it, and this tutorial will take many steps directly from there. Their website has instructions for all the major platforms, however this article will be specific to Mac OS X running on a 64 bit Intel processor.

Google does not distribute the binaries, which means you’ll have to build it for your own platform.

Setup Environment Variables

When you build Go, the compiler is going to need to know a few things.

export GOROOT=$HOME/go
export GOARCH=amd64
export GOOS=darwin
export GOBIN=$HOME/go/bin

$GOROOT is the path to where you’ll download the Google Go source code. I left mine where Google suggested, which is $HOME/go (/Users/[username]/go).

$GOARCH is the architecture you’re building for. The options are amd64, 386, or arm. The name is slightly misleading, but amd64 works for all 64bit x86 processors, and is what you’ll want to choose for Inlet 64 bit processors.

$GOOS is the operating system. The options here are darwin (for Mac), freebsd, linux, and nacl.

$GOBIN is where the output from the build will be placed. You’ll have to create this folder before building Go.

Grabbing The Go Source

Go uses Mercurial for version control. I didn’t have Mercurial installed, so I had to install it with this command.

$ sudo easy_install mercurial

After you have Mercurial installed, fetch the repository to your Go root.

$ hg clone -r release https://go.googlecode.com/hg/ $GOROOT

Building Go

This step assumes you have gcc and a bunch of other crap installed. The simplest way to get these is to just install Xcode. If you’re a developer on a Mac, however, chances are you’ve already got it installed.

$ cd $GOROOT/src
$ ./all.bash

When the build is complete, you’ll see something that looks like this:

2 known bugs; 0 unexpected bugs

The known bugs are expected and the number may vary based on the current release of Go and your architecture.

Once this is done, a compiler and a linker has been placed in the bin folder. Time to add that folder to the $PATH environment variable.

$ export PATH=$HOME/go/bin:$PATH

Writing Some Go Code

With your favorite text editor, create a helloworld.go file and add some Go code to it.

package main

import "fmt"
import "time"

func main() {
        var currentTime = time.LocalTime()
        fmt.Printf("The current time is: %s\n", currentTime.String())
}

The compiler and linker will be called 8g and 8l. We need to now compile and link our application.

$ 8g helloworld.g
$ 8l helloworld.8

After it builds and links without errors, it’s time to run our program.

$ ./8.out

Which outputs:

The current time is: Mon Jun 14 22:47:08 EDT 2010

And there you have it. If you own a Mac and are interested in messing with Google Go, this tutorial should get you started. Go has a pretty good sized framework that should let you do a lot of interesting things. Google uses Go internally for production systems, which I guess gives it some credibility as a mature language. Hopefully Go can gain some mainstream momentum in the future, and I’ll definitely be watching it grow.

Installing and Running Google Go on Mac OS X

A while ago Google gave us a brand new language, Go. In the last couple of years I really haven’t heard much about it, but I decided to finally install it and give it a try. This tutorial will guide you step-by-step on how to install Google Go and start writing your own applications.

Go’s website has very good instructions on how to install it, and this tutorial will take many steps directly from there. Their website has instructions for all the major platforms, however this article will be specific to Mac OS X running on a 64 bit Intel processor.

Google does not distribute the binaries, which means you’ll have to build it for your own platform.

Setup Environment Variables

When you build Go, the compiler is going to need to know a few things.

export GOROOT=$HOME/go
export GOARCH=amd64
export GOOS=darwin
export GOBIN=$HOME/go/bin

$GOROOT is the path to where you’ll download the Google Go source code. I left mine where Google suggested, which is $HOME/go (/Users/[username]/go).

$GOARCH is the architecture you’re building for. The options are amd64, 386, or arm. The name is slightly misleading, but amd64 works for all 64bit x86 processors, and is what you’ll want to choose for Inlet 64 bit processors.

$GOOS is the operating system. The options here are darwin (for Mac), freebsd, linux, and nacl.

$GOBIN is where the output from the build will be placed. You’ll have to create this folder before building Go.

Grabbing The Go Source

Go uses Mercurial for version control. I didn’t have Mercurial installed, so I had to install it with this command.

$ sudo easy_install mercurial

After you have Mercurial installed, fetch the repository to your Go root.

$ hg clone -r release https://go.googlecode.com/hg/ $GOROOT

Building Go

This step assumes you have gcc and a bunch of other crap installed. The simplest way to get these is to just install Xcode. If you’re a developer on a Mac, however, chances are you’ve already got it installed.

$ cd $GOROOT/src
$ ./all.bash

When the build is complete, you’ll see something that looks like this:

2 known bugs; 0 unexpected bugs

The known bugs are expected and the number may vary based on the current release of Go and your architecture.

Once this is done, a compiler and a linker has been placed in the bin folder. Time to add that folder to the $PATH environment variable.

$ export PATH=$HOME/go/bin:$PATH

Writing Some Go Code

With your favorite text editor, create a helloworld.go file and add some Go code to it.

package main

import "fmt"
import "time"

func main() {
        var currentTime = time.LocalTime()
        fmt.Printf("The current time is: %s\n", currentTime.String())
}

The compiler and linker will be called 8g and 8l. We need to now compile and link our application.

$ 8g helloworld.g
$ 8l helloworld.8

After it builds and links without errors, it’s time to run our program.

$ ./8.out

Which outputs:

The current time is: Mon Jun 14 22:47:08 EDT 2010

And there you have it. If you own a Mac and are interested in messing with Google Go, this tutorial should get you started. Go has a pretty good sized framework that should let you do a lot of interesting things. Google uses Go internally for production systems, which I guess gives it some credibility as a mature language. Hopefully Go can gain some mainstream momentum in the future, and I’ll definitely be watching it grow.

Using Doc Raptor to create Excel Spreadsheets

Remember back many moons ago when we posted a previous tutorial about Excel document creation? Specifically, this one. It worked, but if you take a look at it again, that code was painful. And ugly. And required hooking up ruby with a Java library called JExcelAPI using RJB – which, really, is not something anyone actually wants to do. So today we are going to take a look at something else (that I think) is a lot nicer/cleaner for Excel document generation: a new web service specifically for document creation called Doc Raptor.

As a disclaimer, I am one of the people who wrote Doc Raptor – so I apologize if I come across as too excited about it. In all honesty, I think I’d be just as excited if someone else had created the service – because I really hated integrating and using that Java library in every app that needed to produce Excel documents.

Enough talk about that, let us dive in and see how Doc Raptor works. The example here today is going to be in Ruby (because that is what I write most of the time now), but since Doc Raptor is just a RESTful webservice, you can easily make it work with the language of your choice. The high level overview is that you create html tables, send them as a POST request to Doc Raptor, and get back an Excel document. Below, you can see the Ruby code necessary for such a request:

class Doc
  API_KEY = "YOUR_API_KEY_HERE"

  include HTTParty
  base_uri "https://docraptor.com"
 
  # :document_content => content, :name => "a doc",
  # :document_type => "xls", :test => false
  #
  # returns a string that is the document data
  def self.create(document_information)
    post("/docs", :body => {:doc => document_information},
                  :basic_auth => {:username => API_KEY})
  end
end

First off, you need to get a Doc Raptor API Key – which is easy to do, you can just go sign up for the free plan, and it will be right there on the dashboard:

Below that you see that we are including the module HTTParty. HTTParty is a ruby gem that makes dealing with http connections absurdly easy. Including the module makes it so that this Doc class can act as a nice encapsulation of communication with Doc Raptor – giving us handy methods like post. Right below the include line, you can see the call to base_uri. That is a method that we get by including HTTParty, and allows us to set what the base url we will be hitting against will be – in this case, it is “https://docraptor.com”.

Then we get to the meat of this class (although there really isn’t much to it) – the create method. This method takes the document information passed in (we will go over what is passed in in a moment), and does a POST request of that data plus the api key against “/docs” (which is really “https://docraptor.com/docs” – because of the setting of the base uri earlier). What is returned is just the response from Doc Raptor, which, if all went well, is the created document.

So what is passed into create? A hash of a couple parameters to send to Doc Raptor – :document_content, :document_type, :name, and :test. You can read about these parameters in detail in the Doc Raptor documentation, but I will go over them briefly here. :document_content is the most important – this is the string of html that Doc Raptor will use to create the document, and is what we will spend most of the rest of the tutorial creating. :document_type is used to tell Doc Raptor what type of document to create – it supports creating both Excel and PDF files – “xls” and “pdf”, respectively. In this tutorial, we are just creating Excel files, so this will be set to “xls”. :name is just a name for the document for your reference (shown on the Doc Raptor account dashboard with the date/time the document was created). And finally, :test sets if Doc Raptor creates this document in test mode – test mode allows you to create documents that don’t count against your monthly limit, but are watermarked, so it is great when figuring out how you want a document to look.

Ok, so that is a bunch of text covering how to use that create method, but who reads text? You want to see some code! So let us get to generating some content to create an Excel file from.

Since Doc Raptor takes html, we might as well use all the tools at our disposal in ruby that make creating html easy. I’m talking about haml. If you haven’t heard of haml, you should go take a look – it is a very clean and easy to use markup language that can be used to produce html. We are going to take some data and render it with a haml template, producing html that we can give to Doc Raptor. Below you can see the ruby code that does the rendering:

some_data = [2,4,1,6,3,5,18,22]

template = File.read(‘my_excel_template.haml’)
haml_engine = Haml::Engine.new(template)
rendered_template = haml_engine.render(Object.new, { :supplied_data => some_data })

We have an array of, literally, some data that we will be passing into the template. First, we open and read in the haml template (from a file called my_excel_template.haml (we will look at the contents of that file in a moment). Then we create a new haml renderer around that template. Finally, we render the template, and make the some_data variable available to be used inside the template as the variable supplied_data. The generated html is stored in the variable rendered_template.

Ok, so now we can take a look at this haml template. Haml is pretty easy to read even if you have never seen it before, but the folks at the haml website do a much better job explaining it than I ever could, so you should read through their tutorial if the markup below makes no sense.

%table{ :name => ‘My First Sheet’ }
  %tr
  %tr
    %td{ :colspan => 3,
         :style => "text-align:center;font-size:15pt;background-color:orange;" }
      Woo A Header Cell
  %tr
  %tr
    %td{ :colspan => 3, :style => "text-align:center;" }
      some subheader action
  %tr
  %tr{ :style => "background-color:#BBBBBB;border-top-style:thin;font-weight:bold;" }
    %td{ :style => "border-left-style:thin;" }
      My col data 1
    %td{ :style => "text-decoration:underline;" }
      My col data 2
    %td{ :style => "border-right-style:thin;" }
      My col data 3
  supplied_data.each do |value|
    %tr
      %td{ :style => "border-left-style:thin;" }
        = "Some text: #{value}"
      %td
        = value*value
      %td{ :style => "border-right-style:thin;" }
        Wheeee
  %tr{ :style => "border-top-style:thin;height:30;" }
    %td{ :style => "text-align:right;"}
      Sum:
    %td{ :style => "color:green;font-weight:bold;" }
      = "=SUM(B7:B#{supplied_data.count+6})"
    %td

Essentially, the code above is just describing an html table with some headers and then some rows of data generated by the data we passed in when rendering the template. So when this is rendered with that data, we get the html shown below:

<table name=‘My First Sheet’>
  <tr></tr>
  <tr>
    <td colspan=‘3’
        style=‘text-align:center;font-size:15pt;background-color:orange;’>
      Woo A Header Cell
    </td>
  </tr>
  <tr></tr>
  <tr>
    <td colspan=‘3’ style=‘text-align:center;’>
      some sub-header action
    </td>
  </tr>
  <tr></tr>
  <tr style=‘background-color:#BBBBBB;border-top-style:thin;font-weight:bold;’>
    <td style=‘border-left-style:thin;’>
      My col data 1
    </td>
    <td style=‘text-decoration:underline;’>
      My col data 2
    </td>
    <td style=‘border-right-style:thin;’>
      My col data 3
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 2
    </td>
    <td>
      4
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 4
    </td>
    <td>
      16
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 1
    </td>
    <td>
      1
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 6
    </td>
    <td>
      36
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 3
    </td>
    <td>
      9
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 5
    </td>
    <td>
      25
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 18
    </td>
    <td>
      324
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 22
    </td>
    <td>
      484
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr style=‘border-top-style:thin;height:30;’>
    <td style=‘text-align:right;’>
      Sum:
    </td>
    <td style=‘color:green;font-weight:bold;’>
      =SUM(B7:B14)
    </td>
    <td></td>
  </tr>
</table>

So this is some pretty standard html, and will in fact render as a table if you throw it in a browser. There are a couple things to point out, though. The name property on the table is used by Doc Raptor to set the name of the sheet inside Excel – so in this case we will get a sheet named “My First Sheet”. Doc Raptor will also pay attention to the any style attributes to the best of its abilities – you can read the full set of supported styles in their documentation.

Ok, time to take this html and send it off:

File.open("my_excel_file.xls", "w+") do |f|
  f.write Doc.create(:document_content => rendered_template,
                     :name             => "my_excel_file.xls",
                     :document_type    => "xls",
                     :test             => true)
end

We just set those parameters like we talked about earlier, call create, and write the response to a file. Nice and simple! The resulting spreadsheet for this example looks like the following:

Pretty sweet for just making html – and a lot nicer than trying to deal with awkward java libraries. Below is the ruby code all together:

require ‘rubygems’
require ‘httparty’
require ‘haml’

class Doc
  API_KEY = "YOUR_API_KEY_HERE"

  include HTTParty
  base_uri "https://docraptor.com"
 
  # :document_content => content, :name => "a doc",
  # :document_type => "xls", :test => false
  #
  # returns a string that is the document data
  def self.create(document_information)
    post("/docs", :body => {:doc => document_information},
                  :basic_auth => {:username => API_KEY})
  end
end

some_data = [2,4,1,6,3,5,18,22]

template = File.read(‘my_excel_template.haml’)
haml_engine = Haml::Engine.new(template)
rendered_template = haml_engine.render(Object.new, { :supplied_data => some_data })

File.open("my_excel_file.xls", "w+") do |f|
  f.write Doc.create(:document_content => rendered_template,
                     :name             => "my_excel_file.xls",
                     :document_type    => "xls",
                     :test             => true)
end

And that wraps up this introduction to Doc Raptor! If ruby isn’t your thing, you can find other language examples on the examples page. If you have any questions or comments, feel free to leave them below, and I will do my best to answer them.

Using Doc Raptor to create Excel Spreadsheets

Remember back many moons ago when we posted a previous tutorial about Excel document creation? Specifically, this one. It worked, but if you take a look at it again, that code was painful. And ugly. And required hooking up ruby with a Java library called JExcelAPI using RJB – which, really, is not something anyone actually wants to do. So today we are going to take a look at something else (that I think) is a lot nicer/cleaner for Excel document generation: a new web service specifically for document creation called Doc Raptor.

As a disclaimer, I am one of the people who wrote Doc Raptor – so I apologize if I come across as too excited about it. In all honesty, I think I’d be just as excited if someone else had created the service – because I really hated integrating and using that Java library in every app that needed to produce Excel documents.

Enough talk about that, let us dive in and see how Doc Raptor works. The example here today is going to be in Ruby (because that is what I write most of the time now), but since Doc Raptor is just a RESTful webservice, you can easily make it work with the language of your choice. The high level overview is that you create html tables, send them as a POST request to Doc Raptor, and get back an Excel document. Below, you can see the Ruby code necessary for such a request:

class Doc
  API_KEY = "YOUR_API_KEY_HERE"

  include HTTParty
  base_uri "https://docraptor.com"
 
  # :document_content => content, :name => "a doc",
  # :document_type => "xls", :test => false
  #
  # returns a string that is the document data
  def self.create(document_information)
    post("/docs", :body => {:doc => document_information},
                  :basic_auth => {:username => API_KEY})
  end
end

First off, you need to get a Doc Raptor API Key – which is easy to do, you can just go sign up for the free plan, and it will be right there on the dashboard:

Below that you see that we are including the module HTTParty. HTTParty is a ruby gem that makes dealing with http connections absurdly easy. Including the module makes it so that this Doc class can act as a nice encapsulation of communication with Doc Raptor – giving us handy methods like post. Right below the include line, you can see the call to base_uri. That is a method that we get by including HTTParty, and allows us to set what the base url we will be hitting against will be – in this case, it is “https://docraptor.com”.

Then we get to the meat of this class (although there really isn’t much to it) – the create method. This method takes the document information passed in (we will go over what is passed in in a moment), and does a POST request of that data plus the api key against “/docs” (which is really “https://docraptor.com/docs” – because of the setting of the base uri earlier). What is returned is just the response from Doc Raptor, which, if all went well, is the created document.

So what is passed into create? A hash of a couple parameters to send to Doc Raptor – :document_content, :document_type, :name, and :test. You can read about these parameters in detail in the Doc Raptor documentation, but I will go over them briefly here. :document_content is the most important – this is the string of html that Doc Raptor will use to create the document, and is what we will spend most of the rest of the tutorial creating. :document_type is used to tell Doc Raptor what type of document to create – it supports creating both Excel and PDF files – “xls” and “pdf”, respectively. In this tutorial, we are just creating Excel files, so this will be set to “xls”. :name is just a name for the document for your reference (shown on the Doc Raptor account dashboard with the date/time the document was created). And finally, :test sets if Doc Raptor creates this document in test mode – test mode allows you to create documents that don’t count against your monthly limit, but are watermarked, so it is great when figuring out how you want a document to look.

Ok, so that is a bunch of text covering how to use that create method, but who reads text? You want to see some code! So let us get to generating some content to create an Excel file from.

Since Doc Raptor takes html, we might as well use all the tools at our disposal in ruby that make creating html easy. I’m talking about haml. If you haven’t heard of haml, you should go take a look – it is a very clean and easy to use markup language that can be used to produce html. We are going to take some data and render it with a haml template, producing html that we can give to Doc Raptor. Below you can see the ruby code that does the rendering:

some_data = [2,4,1,6,3,5,18,22]

template = File.read(‘my_excel_template.haml’)
haml_engine = Haml::Engine.new(template)
rendered_template = haml_engine.render(Object.new, { :supplied_data => some_data })

We have an array of, literally, some data that we will be passing into the template. First, we open and read in the haml template (from a file called my_excel_template.haml (we will look at the contents of that file in a moment). Then we create a new haml renderer around that template. Finally, we render the template, and make the some_data variable available to be used inside the template as the variable supplied_data. The generated html is stored in the variable rendered_template.

Ok, so now we can take a look at this haml template. Haml is pretty easy to read even if you have never seen it before, but the folks at the haml website do a much better job explaining it than I ever could, so you should read through their tutorial if the markup below makes no sense.

%table{ :name => ‘My First Sheet’ }
  %tr
  %tr
    %td{ :colspan => 3,
         :style => "text-align:center;font-size:15pt;background-color:orange;" }
      Woo A Header Cell
  %tr
  %tr
    %td{ :colspan => 3, :style => "text-align:center;" }
      some subheader action
  %tr
  %tr{ :style => "background-color:#BBBBBB;border-top-style:thin;font-weight:bold;" }
    %td{ :style => "border-left-style:thin;" }
      My col data 1
    %td{ :style => "text-decoration:underline;" }
      My col data 2
    %td{ :style => "border-right-style:thin;" }
      My col data 3
  supplied_data.each do |value|
    %tr
      %td{ :style => "border-left-style:thin;" }
        = "Some text: #{value}"
      %td
        = value*value
      %td{ :style => "border-right-style:thin;" }
        Wheeee
  %tr{ :style => "border-top-style:thin;height:30;" }
    %td{ :style => "text-align:right;"}
      Sum:
    %td{ :style => "color:green;font-weight:bold;" }
      = "=SUM(B7:B#{supplied_data.count+6})"
    %td

Essentially, the code above is just describing an html table with some headers and then some rows of data generated by the data we passed in when rendering the template. So when this is rendered with that data, we get the html shown below:

<table name=‘My First Sheet’>
  <tr></tr>
  <tr>
    <td colspan=‘3’
        style=‘text-align:center;font-size:15pt;background-color:orange;’>
      Woo A Header Cell
    </td>
  </tr>
  <tr></tr>
  <tr>
    <td colspan=‘3’ style=‘text-align:center;’>
      some sub-header action
    </td>
  </tr>
  <tr></tr>
  <tr style=‘background-color:#BBBBBB;border-top-style:thin;font-weight:bold;’>
    <td style=‘border-left-style:thin;’>
      My col data 1
    </td>
    <td style=‘text-decoration:underline;’>
      My col data 2
    </td>
    <td style=‘border-right-style:thin;’>
      My col data 3
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 2
    </td>
    <td>
      4
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 4
    </td>
    <td>
      16
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 1
    </td>
    <td>
      1
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 6
    </td>
    <td>
      36
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 3
    </td>
    <td>
      9
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 5
    </td>
    <td>
      25
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 18
    </td>
    <td>
      324
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr>
    <td style=‘border-left-style:thin;’>
      Some text: 22
    </td>
    <td>
      484
    </td>
    <td style=‘border-right-style:thin;’>
      Wheeee
    </td>
  </tr>
  <tr style=‘border-top-style:thin;height:30;’>
    <td style=‘text-align:right;’>
      Sum:
    </td>
    <td style=‘color:green;font-weight:bold;’>
      =SUM(B7:B14)
    </td>
    <td></td>
  </tr>
</table>

So this is some pretty standard html, and will in fact render as a table if you throw it in a browser. There are a couple things to point out, though. The name property on the table is used by Doc Raptor to set the name of the sheet inside Excel – so in this case we will get a sheet named “My First Sheet”. Doc Raptor will also pay attention to the any style attributes to the best of its abilities – you can read the full set of supported styles in their documentation.

Ok, time to take this html and send it off:

File.open("my_excel_file.xls", "w+") do |f|
  f.write Doc.create(:document_content => rendered_template,
                     :name             => "my_excel_file.xls",
                     :document_type    => "xls",
                     :test             => true)
end

We just set those parameters like we talked about earlier, call create, and write the response to a file. Nice and simple! The resulting spreadsheet for this example looks like the following:

Pretty sweet for just making html – and a lot nicer than trying to deal with awkward java libraries. Below is the ruby code all together:

require ‘rubygems’
require ‘httparty’
require ‘haml’

class Doc
  API_KEY = "YOUR_API_KEY_HERE"

  include HTTParty
  base_uri "https://docraptor.com"
 
  # :document_content => content, :name => "a doc",
  # :document_type => "xls", :test => false
  #
  # returns a string that is the document data
  def self.create(document_information)
    post("/docs", :body => {:doc => document_information},
                  :basic_auth => {:username => API_KEY})
  end
end

some_data = [2,4,1,6,3,5,18,22]

template = File.read(‘my_excel_template.haml’)
haml_engine = Haml::Engine.new(template)
rendered_template = haml_engine.render(Object.new, { :supplied_data => some_data })

File.open("my_excel_file.xls", "w+") do |f|
  f.write Doc.create(:document_content => rendered_template,
                     :name             => "my_excel_file.xls",
                     :document_type    => "xls",
                     :test             => true)
end

And that wraps up this introduction to Doc Raptor! If ruby isn’t your thing, you can find other language examples on the examples page. If you have any questions or comments, feel free to leave them below, and I will do my best to answer them.

Creating a Roulette Wheel Using HTML5 Canvas

HTML5 is really hot all over the web right now so I figured I would drop some HTML5 knowledge on y’all. I have worked with Flash and Flex consistently for the last few years so I can easily drop and manipulate graphics in it, but I haven’t done much with HTML5. This lead me to try and challenge myself to recreate something I built in Flash in HTML5. That is what we are going to look at and learn to build in this tutorial.

A few things should be mentioned. First IE simply doesn’t implement the <canvas> tag which means it won’t work in IE, Google has released Explorer Canvas which fixes this to some extent. I, however, didn’t worry about adding that to this tutorial because this post is about creating the content. Also, there are some small things that don’t work in other browsers. Finally, Mobile Safari (iPhone, iPod Touch, and iPad) doesn’t implement text rendering correctly.

To get things rolling we’ll first put some simple html down. This includes the <canvas> tag which is what we’re using for this tutorial. The only other element we are going to use is an input button to spin our wheel. I also added a little bit of inline style to place the button.

<input type="button" value="spin" style="float:left;" />
<canvas id="canvas" width="500" height="500"></canvas>

The next thing we are going to do is begin drawing some stuff on to our canvas. This is going to be done in JavaScript in a function I named drawRouletteWheel. The basics of drawing on the <canvas> in 2D at least involve grabbing a drawing context and then drawing onto it. Sounds complicated doesn’t it. Let’s look at a little bit of code.

var colors = ["#B8D430", "#3AB745", "#029990", "#3501CB",
                 "#2E2C75", "#673A7E", "#CC0071", "#F80120",
                 "#F35B20", "#FB9A00", "#FFCC00", "#FEF200"];

var startAngle = 0;
var arc = Math.PI / 6;
var ctx;

function drawRouletteWheel() {
  var canvas = document.getElementById("canvas");
  if (canvas.getContext) {
    var outsideRadius = 200;
    var insideRadius = 125;
   
    ctx = canvas.getContext("2d");
    ctx.clearRect(0,0,500,500);
   
    ctx.strokeStyle = "black";
    ctx.lineWidth = 2;
   
    for(var i = 0; i < 12; i++) {
      var angle = startAngle + i * arc;
      ctx.fillStyle = colors[i];
     
      ctx.beginPath();
      ctx.arc(250, 250, outsideRadius, angle, angle + arc, false);
      ctx.arc(250, 250, insideRadius, angle + arc, angle, true);
      ctx.stroke();
      ctx.fill();
    }
  }
}

Okay, looking at the start of the function we grab a reference to our canvas object by id – nothing new here. Then we check to make sure the browser supports grabbing a drawing context, this is important to make sure we don’t throw errors in browsers that don’t support the features. Then we set a couple of variables for the inner and outer radius of our wheel. Now, we get into the meat. The first thing we do is grab a 2D drawing context by calling getContext. From here we clear the canvas, so we have a blank slate to draw onto. Then we set the stroke color and width which in this case is “black” and 2.

The next part takes a little bit of explaining, we are going to loop through 12 sections (the number of sides we are going to draw). For each section we determine the angle of where each section is going to start. The startAngle is a global variable in which we are going to use to animate the wheel, for now, it is set to 0. The following line sets the fill color by pulling a value from the global colors array. Drawing begins after that with starting a path drawing two arcs, using the arc(x, y, radius, startAngle, endAngle, anticlockwise) function. We then tell the context to stroke the path and fill the path, these will use the previously set parameters.

Now, we are going to add the restaurant text to our drawing code. Also, to finish off the drawing function we’ll add the nice little arrow at the top. The text drawing is done using the fillText(text, x, y [, maxWidth ]) function. Let’s take a look at the updated code.

var restaraunts = ["Wendy’s", "McDonalds", "Chick-fil-a", "Five Guys",
                       "Gold Star", "La Mexicana", "Chipotle", "Tazza Mia",
                       "Panera", "Just Crepes", "Arby’s", "Indian"];

function drawRouletteWheel() {
  var canvas = document.getElementById("canvas");
  if (canvas.getContext) {
    var outsideRadius = 200;
    var textRadius = 160;
    var insideRadius = 125;
   
    ctx = canvas.getContext("2d");
    ctx.clearRect(0,0,500,500);
   
   
    ctx.strokeStyle = "black";
    ctx.lineWidth = 2;
   
    ctx.font = ‘bold 12px Helvetica, Arial’;
   
    for(var i = 0; i < 12; i++) {
      var angle = startAngle + i * arc;
      ctx.fillStyle = colors[i];
     
      ctx.beginPath();
      ctx.arc(250, 250, outsideRadius, angle, angle + arc, false);
      ctx.arc(250, 250, insideRadius, angle + arc, angle, true);
      ctx.stroke();
      ctx.fill();
     
      ctx.save();
      ctx.shadowOffsetX = 1;
      ctx.shadowOffsetY = 1;
      ctx.shadowBlur    = 0;
      ctx.shadowColor   = "rgb(220,220,220)";
      ctx.fillStyle = "black";
      ctx.translate(250 + Math.cos(angle + arc / 2) * textRadius,
                    250 + Math.sin(angle + arc / 2) * textRadius);
      ctx.rotate(angle + arc / 2 + Math.PI / 2);
      var text = restaraunts[i];
      ctx.fillText(text, ctx.measureText(text).width / 2, 0);
      ctx.restore();
    }
   
    //Arrow
    ctx.fillStyle = "black";
    ctx.beginPath();
    ctx.moveTo(250 4, 250 (outsideRadius + 5));
    ctx.lineTo(250 + 4, 250 (outsideRadius + 5));
    ctx.lineTo(250 + 4, 250 (outsideRadius 5));
    ctx.lineTo(250 + 9, 250 (outsideRadius 5));
    ctx.lineTo(250 + 0, 250 (outsideRadius 13));
    ctx.lineTo(250 9, 250 (outsideRadius 5));
    ctx.lineTo(250 4, 250 (outsideRadius 5));
    ctx.lineTo(250 4, 250 (outsideRadius + 5));
    ctx.fill();
  }
}

Looking at the new text drawing we start by saving the current context state – this is going to allow us to rotate and translate the text without affecting everything else. We then set some shadow stuff, which will put a drop shadow on the text. Translating and rotating the text is tackled next, we first translate the text to the correct placement on the wheel and then rotate it. Drawing the text follows this but with the added effect of centering the text by measuring it and dividing that by 2 to offset it. You’ll notice we grab the restaurant name from a global array. Lastly we restore to our initial state we saved to, this makes sure the transformations do not affect later drawing. The arrow is even easier to explain, we just move to one corner and draw lines to create the shape and fill it with black.

Below I have the complete code for this demo. I’ll explain the spinning and animating code right after.

var colors = ["#B8D430", "#3AB745", "#029990", "#3501CB",
             "#2E2C75", "#673A7E", "#CC0071", "#F80120",
             "#F35B20", "#FB9A00", "#FFCC00", "#FEF200"];
var restaraunts = ["Wendy’s", "McDonalds", "Chick-fil-a", "Five Guys",
                   "Gold Star", "La Mexicana", "Chipotle", "Tazza Mia",
                   "Panera", "Just Crepes", "Arby’s", "Indian"];

var startAngle = 0;
var arc = Math.PI / 6;
var spinTimeout = null;

var spinArcStart = 10;
var spinTime = 0;
var spinTimeTotal = 0;

var ctx;
   
function drawRouletteWheel() {
  var canvas = document.getElementById("canvas");
  if (canvas.getContext) {
    var outsideRadius = 200;
    var textRadius = 160;
    var insideRadius = 125;
   
    ctx = canvas.getContext("2d");
    ctx.clearRect(0,0,500,500);
   
   
    ctx.strokeStyle = "black";
    ctx.lineWidth = 2;
   
    ctx.font = ‘bold 12px Helvetica, Arial’;
   
    for(var i = 0; i < 12; i++) {
      var angle = startAngle + i * arc;
      ctx.fillStyle = colors[i];
     
      ctx.beginPath();
      ctx.arc(250, 250, outsideRadius, angle, angle + arc, false);
      ctx.arc(250, 250, insideRadius, angle + arc, angle, true);
      ctx.stroke();
      ctx.fill();
     
      ctx.save();
      ctx.shadowOffsetX = 1;
      ctx.shadowOffsetY = 1;
      ctx.shadowBlur    = 0;
      ctx.shadowColor   = "rgb(220,220,220)";
      ctx.fillStyle = "black";
      ctx.translate(250 + Math.cos(angle + arc / 2) * textRadius,
                    250 + Math.sin(angle + arc / 2) * textRadius);
      ctx.rotate(angle + arc / 2 + Math.PI / 2);
      var text = restaraunts[i];
      ctx.fillText(text, ctx.measureText(text).width / 2, 0);
      ctx.restore();
    }
   
    //Arrow
    ctx.fillStyle = "black";
    ctx.beginPath();
    ctx.moveTo(250 4, 250 (outsideRadius + 5));
    ctx.lineTo(250 + 4, 250 (outsideRadius + 5));
    ctx.lineTo(250 + 4, 250 (outsideRadius 5));
    ctx.lineTo(250 + 9, 250 (outsideRadius 5));
    ctx.lineTo(250 + 0, 250 (outsideRadius 13));
    ctx.lineTo(250 9, 250 (outsideRadius 5));
    ctx.lineTo(250 4, 250 (outsideRadius 5));
    ctx.lineTo(250 4, 250 (outsideRadius + 5));
    ctx.fill();
  }
}
   
function spin() {
  spinAngleStart = Math.random() * 10 + 10;
  spinTime = 0;
  spinTimeTotal = Math.random() * 3 + 4 * 1000;
  rotateWheel();
}

function rotateWheel() {
  spinTime += 30;
  if(spinTime >= spinTimeTotal) {
    stopRotateWheel();
    return;
  }
  var spinAngle = spinAngleStart easeOut(spinTime, 0, spinAngleStart, spinTimeTotal);
  startAngle += (spinAngle * Math.PI / 180);
  drawRouletteWheel();
  spinTimeout = setTimeout(‘rotateWheel()’, 30);
}

function stopRotateWheel() {
  clearTimeout(spinTimeout);
  var degrees = startAngle * 180 / Math.PI + 90;
  var arcd = arc * 180 / Math.PI;
  var index = Math.floor((360 degrees % 360) / arcd);
  ctx.save();
  ctx.font = ‘bold 30px Helvetica, Arial’;
  var text = restaraunts[index]
  ctx.fillText(text, 250 ctx.measureText(text).width / 2, 250 + 10);
  ctx.restore();
}

function easeOut(t, b, c, d) {
  var ts = (t/=d)*t;
  var tc = ts*t;
  return b+c*(tc + 3*ts + 3*t);
}

drawRouletteWheel();

It’s a lot to take in but we’ll take it slow. At the bottom of the code you’ll see we call drawRouletteWheel, this is too draw the initial wheel when the page loads. We have to update the input button we put on the screen to now call our spin function, which handles spinning the wheel, of course. The updated input follows.

<input type="button" value="spin" onclick="spin();" style="float:left;" />

Taking a look at the spin function we set a couple global variables that decide how fast we are going to spin and how long we are going to spin. These have a little bit of randomness in them to make things more interesting. Lastly, we call rotateWheel.

The rotateWheel function updates the amount of time we have been spinning, checks to see if we should stop, updates spinning speed, draws the wheel, and then calls itself in 30 milliseconds. After checking the time we change the spinning angle, startAngle, this is done using an easing function to slow down the spinning. Then we call our drawing function and use setTimeout and keeps a reference to call our rotate again.

The last function we need look at is stopping the wheel, stopRotateWheel. This starts with clearing the timeout which will stop the code from rotating the wheel. Then we use some math to figure out what restaurant is at the top. Finally, we draw the large name of the of the selected restaurant in the middle of the wheel.

Well, that’s pretty much a wrap on this post. I really like how HTML5 and the canvas tag are coming along. Although it’s not quite ready for primetime production work yet. I look forward to the next couple years of web development.

If you have any questions on the tutorial or just want to bash on my coding skills feel free to drop a comment.

Taking a Dive into HTML5 – Web Storage

HTML5 is getting a lot of attention these days – especially when it comes to video. This tutorial is going to cover a feature added to HTML5 that I don’t think is getting enough attention – web storage.

Prior to web storage, most websites used cookies to store information on the client’s computer. Cookies, for the most part, work great for simple storage. They do, however, have one major drawback. If the user is visiting your site on two separate windows or tabs, information stored in cookies will be shared between them. To handle this case, the web storage in HTML5 has been split into two pieces: localStorage and sessionStorage. The first one works like cookies, saving information for an entire site (origin). The second one, sessionStorage, will store information for each origin but keep it isolated between windows or tabs.

Before we get started, I should note that not every browser supports web storage. Wikipedia is maintaining a pretty good list of HTML5 browser compatibility that should probably be consulted before using storage in a production environment.

Reading and Writing Values

Both mechanism use the same object as defined in the web storage spec, Storage. Let’s take a look at this interface.

interface Storage {
  readonly attribute unsigned long length;
  getter DOMString key(in unsigned long index);
  getter any getItem(in DOMString key);
  setter creator void setItem(in DOMString key, in any data);
  deleter void removeItem(in DOMString key);
  void clear();
};

Hats off the creators of this, as I don’t think there could have been a simpler interface for storing values. At its core, this is basically a dictionary mapping string keys to object values. For the most part, pretty much anything can be stored in here – as long as it can be cloned using the structured clone algorithm

Let’s take a look at how do use this, first using localStorage.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
   <head>
      <title></title>
      <script type="text/javascript">
         function load()
         {
          var value = localStorage.getItem("myKey");
         
          if(!value)
          {
            alert("No item found, adding to localStorage");
            localStorage.setItem("myKey", "myValue");
          }
          else
          {
            alert("Item found: " + value);
          }
         }
      </script>
   </head>
   <body onload="load()">
       
   </body>
</html>

In this example, if the value hasn’t been stored yet, you’ll receive this alert:

No item alert

The next time the page is loaded, you’ll now receive this alert:

Item found alert

As you can see, using localStorage is incredibly easy. This value will now be stored indefinitely on the client’s computer ready for me to retrieve whenever they visit my website again.

Using sessionStorage is just as easy. All we have to do is replace the object we’re using and we’re done.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
   <head>
      <title></title>
      <script type="text/javascript">
         function load()
         {
          var value = sessionStorage.getItem("myKey");
         
          if(!value)
          {
            alert("No item found, adding to sessionStorage");
            sessionStorage.setItem("myKey", "myValue");
          }
          else
          {
            alert("Item found: " + value);
          }
         }
      </script>
   </head>
   <body onload="load()">
       
   </body>
</html>

The code is nearly identical to the previous code, however this time, if you open the site in two different tabs, you’ll receive the “No item found” message for each tab. In the previous example, the value existed for every new tab or window created.

One thing to remember when dealing with HTML5 web storage is that it does not cross browsers. The spec does not outline where or how a browser must store the data. Therefore if the user visits your site in one browser one day, then in a different browser the next, you will not be able to see values that were stored by the other browser.

Listening for Changes

The HTML5 spec outlines an event that client’s can attach to in order to receive updates whenever a storage (local or session) changes. At this point in time, however, I wasn’t able to get it working in Chrome (6.0.401.1 dev). I was, however, able to get the following code working in Opera.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
   <head>
      <title></title>
      <script type="text/javascript">
         function load()
         {
         localStorage.clear();
          var value = localStorage.setItem("myKey", "myNewValue");
          alert(localStorage.getItem("myKey"));
         }
         
         function storageChanged(e)
         {
          alert("Storage changed.");
         }
      </script>
   </head>
   <body onstorage="storageChanged()" onload="load()" >
       
   </body>
</html>

In Opera, the storageChanged event will fire twice – once for when the localStorage is cleared, and again when the value is set.

Although we’re moving in the right direction, HTML5 still has a ways to go before it’s fully adopted. Web Storage has a great amount of potential in the future of web apps and I can wait to see what developers are able to do with it.