Sunday, October 21, 2007

Silverlight: Read xml file in FireFox (solve "Data at the root level is invalid")

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/silverlight_read_xml_file_in_firefox_solve_data_at_the_ro.htm]

Any app eventually needs to read data; and it's very likely that for Silverlight, that data will be XML files on your web server. For example, in the real-time strategy TruckWars game, each level is stored as an XML file (named 1.xml, 2.xml, etc...). The Silverlightquickstart tutorials describe how to load an Xml file into an XmlReader (there is no XmLDocument for silverlight yet). While this works great in IE, it actually has a problem in FireFox. FF tries to read the xml file, but it starts with three extra bits used for reading the encoding type. These three extra bits screw up the XmlReader, and you get the error:

 

"Data at the root level is invalid. Line 1, position 1."

 

This has something to do with theunicode.GetPreamble().

 

Practically, there's probably some way to overload the reader class, or set something on the Xml file. But I couldn't figure that out. I tried several things:

  1. Use reader.ReadToFollowing("myNode"); But those first few bytes prevent me from reading anything.

  2. I tried removing , but no luck

  3. Based on anMSDN forum, I tried removing this first line:

  4. In the StreamReader class, I set the detectEncodingFromByteOrderMarks constructor property (trying both true and false), but no luck.

  5. I tried modifying the Xml Reader to directly get from URI. However, I got the error: "Support for http:// URIs is not yet implemented."

  6. I tried overloading the XmlReader with XmlReaderSettings (and setting IgnoreProcessingInstructions )

  7. I tried reading the first three bytes of stream to "skim off" the problem characters, but it still had the same problem

So, none of those attempts worked. Eventually, I got a work-around. I would read the entire xml file into a string, and then skip the first problem characters until I go to the "

    public static XmlReader CreateXmlReader(string strRelativePath)    {      HttpWebResponse response = null;      StreamReader sr = null;      try      {        //first create standard stream:        Uri u = new Uri(strRelativePath, UriKind.Relative);        HttpWebRequest request = new BrowserHttpWebRequest(u);        response = request.GetResponse();        Stream content = response.GetResponseStream();        sr = new StreamReader(content);        string s2 = sr.ReadToEnd();        //Skim off unicode.GetPreamble()        //In firefox, this would be first three bytes for UTF8        int intIndex = s2.IndexOf(");        s2 = s2.Substring(intIndex);        StringReader sr2 = new StringReader(s2);        return XmlReader.Create(sr2);      }      catch (Exception ex)      {        throw;  //Wrap in try catch for now. Will add better error-handling later.      }    }

This solved my problem, worked in both FireFox and IE, an performed well enough for my needs.

Wednesday, October 17, 2007

Silverlight - Truck Wars Strategy Game v2.0

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/silverlight__truck_wars_strategy_game.htm]

Release 2.0 - Migrated to SL2

Microsoft has officially released Silverlight 2.0, and there are more breaking changes. I haven't updated TruckWars yet (it's gone through Alpha 1.1, Beta 1, Beta 2... running out of gas). Here's a screen shot of what it looked like. I hope to migrate sometime in the future, perhaps even adding dynamic scripting for the objects.

 

truckwars_screenshot_1_2.jpeg


Release 2.0 - Migrated to SL2 Beta 2

I started working on TruckWars as a way to learn Silverlight back in the Alpha last year. There have since been two more betas (with plenty ofbreaking changes), but I've finally migrated it.

 

Things of note - Beta 1 started supporting buttons, which obviously simplified things. For example, it helped me remove keyboard input. It also had some subtle changes that affected the gameplay. Also, there still is no dropdown. Before I was using an HTML dropdown to select the levels. Rather than jump through hoops, I just ceded the dropdown part until the next release.

 

Because the code has been migrated from an alpha, to a beta, to another beta, it's becoming pretty screwy. Not the best, most agile code out there, but good for a demo of what cool stuff Silverlight can do.


NOTE: You need to view this page in a browser in order to see the game; it doesn't show up in most RSS feeders.

 

Release 1.3: Now Open-Sourced

TruckWars is a simple SilverLight real-time-strategy game. You control the green units. You select a unit by left-clicking it. You move a unit by drag and drop. You attack an enemy unit by moving your unit into the enemy unit's space. The goal is to push all the green buttons down.TruckWars is now open-sourced at CodePlex. It's also on the Silverlight Gallery.

Release 1.1

This is a simple SilverLight real-time-strategy game. You control the green units. You select a unit by left-clicking it. You move a unit by drag and drop. You attack an enemy unit by moving your unit into the enemy unit's space. The goal is to push the numbered crates onto the pink "Victory" tiles, and then hit the green semi-circle button. You can see more info on the release notes.

Release 1.0

I converted the XNA game to Silverlight. This is a simple SilverLight real-time-strategy game. You control the green units. You select a unit by left-clicking it. You move a unit by drag and drop. You attack an enemy unit by moving your unit into the enemy unit's space. (SilverLight only allows a left click). Currently only the tanks can attack. The ambulance and pickup truck don't do anything yet. The goal is to push the numbered crates onto the pink "Victory" tiles, and then hit the green semi-circle button. Select the game (to activate it), and then click "spacebar" to start. Obviously this is just a simple test of SilverLight, and I'm open to suggestions. I'm going to explain the code in the next several posts. I was inspired by my son's love of trucks to use the truck theme. I was definitely helped by Bill Reiss's good Silverlight Tutorials.

Tuesday, October 16, 2007

XNA Real-Time-Strategy Game (with source code)

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/xna_realtimestrategy_game_with_source_code.htm]

I mentioned in my last post about XNA that I've created a sample game, complete with full source code.

 

 

You control the green tank by using the mouse. Left moves, right fires. The goal is to push the numbered crates onto the pink "Victory" tiles, and then hit the green semi-circle button. This demonstrates several things:

  • Collisions - this uses a simply polygon collision detection. It also handles heights - a fireball hovers, so it can pass over the water, but the tanks cannot.

  • User input - collecting mouse input (position, left, right buttons)

  • Animation - the water animates

  • Multiple creatures of different sizes. The green bushes (the square things) increase in size as your tank gets closer.

  • Interacting objects - you can push crates, fire at other units, hit the push button, and collect a powerup to increase your firing rate.

  • Messages

  • Opacity

  • A dashboard section on the button for user information

  • The ability to pause the game - which freezes everything (including the game clock).

Note that all the graphics were made with MSPaint.

 

The code is pretty sloppy, as it was just a toy project and my main point was to explore XNA. There's a ton that could be improved about it.

 

Obviously it's just a cute sample. Especially as XNA can handle scrolling, 3D games, and a lot more, this only skims the surface.

 

One point of note is unit-testing. There is a lot of complex code (movement algorithms, models, collisions, interactions, etc...) that should ideally be tested. However Visual C# express doesn't support unit-testing. So, I made the core DLL be referenced in another solution, which can then test it.

 

Next up: re-writing this in Silverlight. I'll go into more of the details there.

Monday, October 15, 2007

XNA Game Development

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/xna_game_development.htm]

XNA is a Microsoft platform for easily creating games. These can run on Windows, and even the XBox.

 

Essentially, XNA handles the difficult part of image rendering, and provides the developer a simple API. Bill Reiss provides some excellent tutorials to get you started.

 

An XNA project has the Game class, which provides three main methods;

  1. Initialize - sets everything up

  2. Update - updates the models based on a game clock

  3. Draw - renders images to the screen based on the game clock, and what you updated.

This is a very intuitive API which makes it easy to make simple games, especially 2D classics.

 

What I find interesting about XNA is that many developers got their start by trying to program simple computer games. However, back in the 80s or 90s, the bar was high because it's relatively difficult to do the image rendering, especially something fast enough for a real game. Many more developers can do the algorithms and simple logic than can do the rendering. Even with Windows GDI+, it just wasn't fast enough. But XNA actually works fast enough to make it worth while.

 

XNA games can also bedeployed to other Windows machines, you "just" need to install: (1) .net 2.0 redistributable, (2) XNA redistributable, (3) Direct X. It's motivating to be able to share your work with others.

 

In the next upcoming posts, I'll provide an XNA sample game I created, and compare it to Silverlight.

Wednesday, October 3, 2007

Five hours for one line of code

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/five_hours_for_one_line_of_code.htm]

The other day I spent five hours to write a single line of code. This has happened before, and it always makes me think "why?" To the non-developer it could sound crazy, I've heard many say things like: "it was just one line; you should be writing 100 line of code per hour to justify our budget."

 

The issues involved are:

  1. The developer is working on a legacy sub-system that they had never seen before (perhaps the original creators are no longer available, and you need to dig through their work)

  2. That sub-system is written in a different language

  3. The sub-system itself was complicated

  4. The line to be added was an undocumented feature

  5. It took very long to test each change

  6. This was a mission-critical feature, so it needed to work perfectly

You add those all together, and it's easy to see it the other way - "Wow, I'm glad we got that handled in only half a day".

 

Also, this is a rare case. A developer can write many lines of new code per day.

 

I think it touches on a bigger issue - just because the end result is simple doesn't mean that finding that result is simple too. For example, the total population for the US at a given moment is a specific number (somewhere around 300 million, off the top of my head). However, to find that exact number requires a huge bureaucracy and coordination among many civil organizations (like hospitals and immigration offices).

 

It something that any developer could come across, and should therefore be prepared to explain to their managers if needed.

 

Sunday, September 23, 2007

The problem with "I'll just wait until school to learn to program"

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/the_problem_with_ill_just_wait_until_school_to_learn_to_pr.htm]

I often run across young people who are interested in computers and programming. When I ask why they don't try to learn to program, many of them shrug it off as "I'll just wait until I take the programming class at school". If you're actually interested in programming, this is a very, very, bad idea. Here's why:

  1. It encourages you to become reactive, i.e. "I'll wait for someone to show me before I proactively learn it for myself". With how fast technology moves, and the need to constantly solve new problems, you can't afford a reactive mindset.

  2. Classes normally only cover established (i.e. older) technology

  3. Classes normally provide a bunch of extra theory that you may not need in the real world.

  4. There is just so much that a class won't teach you - Classes have a predefined curriculum, and often discourage you from exploring an interesting topic in more depth (most classes eventually become about getting a good grade on the tests, and if a topic isn't on the test, why "waste" your time studying it, at the expense of another topic that will be on the test.

  5. The good programmers will already be looking at the technology that isn't covered by classes. So if you wait for classes, and then only cover what's in classes, you'll always be behind the good programmers.

  6. Lack of emotional investment - you'll always be more interested in your own pet projects than some arbitrary school assignment. Practically, you'll learn and remember something far better if you have an emotional investment in it. Therefore you'll probably better understand the concepts if you apply them to your own pet projects.

For an aspiring developer, waiting to learn programming until you take it in school is like an aspiring athlete saying "I love basketball, but I'll wait to start playing once they show us how in gym class". Of course it's silly. Especially now with the internet, and free development tools, there's just no reason for a young, aspiring developer to sit-around for the schools to show them how to program.

Thursday, September 20, 2007

Free Development Tools

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/free_development_tools.htm]

A lot of programmers get their start as young hobbyists. However, young hobbyists often don't have the money to buy expensive development tools.

Fortunately, in .Net, you can get most of the core development tools for free.

  • Microsoft provides express editions for its platform. They're more limited than the commercial products, but they get you started.

  • Even a hobbyist should still have source control (note that this isn't .Net specific, you could use it to manage any files)

    • A free, open-source, source control system (which is way better than VSS) is Subversion.

    • Even if you are the sole developer, source control still is invaluable:

      • It lets you keep track of all your changes, giving you the confidence to experiment with big changes because you know you can just roll back. This is much better than copying your entire project each time you do something big.

      • It lets you view the entire revision history of your code

  • There are tons of free helper-tools, like NUnit for unit tests, FxCop for static code analysis, and more. Scott Hanselman does a great job of summarizing these.

Given that the knowledge is free (via millions of internet tutorials, blogs, and reference guides), and the tools are free, all you need is a computer and motivation, and even the young hobbyist can become a great developer.


Living in Chicago and interested in working for a great company? Check out the careers at Paylocity.