Thursday, December 6, 2007

Create an object dynamically with CreateInstance using Reflection

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

You can instantiate an object dynamically using Reflection. For example, the boards in TruckWars are stored in Xml files. Each board has a list of creatures:

 

  <Creatures>
    <Creature type="TankUnit" boardPosition="1.5, 7.5" team="Hero" />
    <Creature type="PickupTruck" boardPosition="1.5, 2" team="Hero" />
    <Creature type="PushButtonStayDown" boardPosition="13.5, 1.5" />
    <Creature type="TankUnitEnemy" boardPosition="14.2, 7.5" team="Enemy1" />
  Creatures
>

 

You could use an xml reader to cycle through this, and at each creature node, dynamically create a creature object. The "trick" is to have a base type (like "CreatureBase") that all your objects inherit from. You then specify the type in the xml file, and use the CreateInstance() method to dynamically create an object (to my knowledge, this requires that the base type at least have an empty constructor):

 

        CreatureBase c = (CreatureBase)Assembly.GetExecutingAssembly().CreateInstance(CreatureNamespace + "." + strType);
        c.Position = strPositionSerializedFromXmlAttribute;
        c.Team = (Team)Enum.Parse(typeof(Team), strTeam, true);    //makes an enum
        c.Name = strName;

 

You can then serialize the xmlNode's attributes and use them to set properties on that object. Thanks to polymorphism, the object will act as the derived type (for example, it will call the derived type's overridden methods).

 

This technique is often used in enterprise architecture for extensibility. The core system creates the base class, but then you can override it and set some xml config file to use your derived type.

 

Wednesday, December 5, 2007

Deploying Silverlight Apps

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

Silverlight is awesome to deploy. As this forum thread describes, you basically just need your web server to setup the right mime type ("Extension should be .xaml and the Content Type should be application/xaml+xml". I also had ".dll --> application/x-msdownload" because some other blogs recommended it).

 

You can then just ftp the files from your silverlight project (ClientBin, files in the root folder, and any other directories), to your server.

 

After dealing with Winform, ASP.Net, and XNA deployment problems, I was floored that it just actually worked.

 

Because Silverlight runs on the client machine, it is the client's responsibility to have the right stuff installed. However, silverlight makes that really easy by rendering as a single-click download link if the client doesn't have it installed yet.

 

Also note that Silverlight is not a server technology like SQL2005 or ASP.Net. You don't even need an ASP.Net server to run Silverlight. (This is especially practical if you're a hobbyist on a budget, and your host company charges extra to asp-enable your site.).

Tuesday, December 4, 2007

Using Path.Combine instead of string concatenation

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

I often need to work with filePaths, such as getting an absolute file name given a directory and a fileName. One way for developers to do this is simply string concatenation. A lot of devs do this because it appears so simple. But the problem is that when passing in the directory as a string, you often don't know if it will end with a final slash or not - i.e "C:\Temp" or "C:\Temp\". Merely doing string concat will screw it up, you could get a non-existent file like "C:\Temp\\MyFile.txt".

 

A much better approach is to use System.IO.Path.Combine. This allows you to have a directory (with or without the slash), and the combine method if smart enough to handle it:


    public static string GetFileName(string strDir, string strName)
    {
      //return strDir + @"\" + strName;   //BAD
      return System.IO.Path.Combine(strDir, strName); //GOOD
    }

 

What's funny is that both options are just 1 line of code and take essentially the exact same amount of time to write. However, the first is very brittle, and could likely cost you tons of time tracking down an error because someone passed in a directory with or without that extra slash. The second just works.

Monday, December 3, 2007

Silverlight 1.1 global page error handler

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

When writing Silverlight TruckWars, I was trying to figure out how to create a global error handler for a page. Eventually I saw the WebApplication.Current.ApplicationUnhandledException event, which I could hook up like so:

 

    public void Page_Loaded(object o, EventArgs e)
    {
        //....
        WebApplication.Current.ApplicationUnhandledException +=
            new EventHandler
            (Current_ApplicationUnhandledException);
    }

 

    void Current_ApplicationUnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    {
      HandleError(e);
    }

 

Note that Silverlight handles errors differently than ASP.Net. In ASP, you get the yellow error page with a detail exception message (by default). However, in Silverlight, it just stops executing your code and returns to the caller, leading to weird behavior.

Sunday, December 2, 2007

10 Rules that Age of Empires Teaches about Development

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

I think that Age of Empires II (AoE) is arguably the best computer game of all time. A close second would be Civilization IV. I'm not much of a computer game player, so the best way for me to justify playing a game is that it's somehow educational. Smile Here are 10 rules, that Age of Empires clearly demonstrates, which also apply to software engineering:

  1. You need to invest in research: This means the occasional big investment, as well as many frequent upgrades as resources allow.  If you neglect your research, it won't matter if you have a hundred units - they'll all be obsolete and practically useless. It may even backfire because you'll still have to maintain them (via population limits or distracting your "medics" to get healed), which will prevent you from focusing on the new, important units that can actually win the game.

  2. You need the right tools: Don't even try taking down a castle with just stone-age sling shots. Often you need a combination of complementary units - i.e. you need to coordinate siege, cavalry, medics, etc... Likewise, software engineering needs the right tools - good luck with team development if you don't at least have a good source control system and a build server.

  3. Strike a problem while it's still small: Like in real life, problems grow in AoE. An enemy team gets bigger and stronger, resources dwindle, or the clock runs outs. This is why a common strategy is to rush your opponents while they're still small. (You may also be small at the moment, but you're still big enough to beat them now). In development, problems grow too - bad code propagates. Knock it out early before it comes back to bite you.

  4. Protect your home base: Don't rush out on some adventure and leave you home base defenseless. Likewise, in development, your core application is your home base, and it should be protected by a suite of automated unit tests. So if you get distracted with some other "adventure", at least your code still has some defense against bad additions that would break it.

  5. Not all units are equal: Although a foot-solder and a horse-archer are each just a single unit, one horse-archer could beat ten foot-solders. Furthermore, the horse-archer, who can shoot at range (like across a river), could accomplish things that a million foot-soldiers could never do. Likewise, in development, there are real "stars" - a star dev will produce not just more than 10x an average dev, they'll create things that an average dev won't even comprehend. Granted, sometimes a company's technical needs are simple enough that they don't need stars, but it's good to at least be aware of the discrepancy.

  6. Your plan can be limited by mental energy: You may have 50 units, but it doesn't matter if it's impossible to manage them. AoE is an arcade game, and you may make dumb decisions simply because there wasn't enough time to think out the perfect solution. I personally prefer a handful of powerful units that are easy to manage, as opposed to an army of weak units that just get plucked off because they're too hard to coordinate. Same applies to software engineering, but even more so. Most of what you do is limited by mental energy (code being hard to maintain, a purist algorithm taking too much thinking to figure out, etc...). Mental energy is as real a resource as gold.

  7. Don't rely on cheat codes: AoE has cheat codes. However,  don't depend on them because they could be disabled or make you miss the bigger picture. In software engineering, the equivalent is to use hacks - bad code that solves the immediate problem now, only to break tens times as much later.

  8. Expect the unexpected. In AoE, there are other teams actively working against you. The enemy may not attack your straight on (where all your defenses are), but may instead be creative and attack from the side, or ambush behind, or siege you, or something else. Likewise, in software engineering, there are constant business changes, miscommunications, developer bugs, new technologies, all causing unexpected things to happen.

  9. Recognize the common patterns and solutions: AoE has perhaps hundreds of units. With many different civs (each with their own unique unit), it's a lot to have a special plan for every single unit that you may encounter.  However, there are comparatively only a few categories for them - like infantry, ranged, cavalry, siege, naval units, etc... By looking at the common patterns (ranged units usually beat infantry, cavalry usually beats siege), you can abstract out the details and make a flexible plan. Same thing in software engineering - there are common design patterns and ways to abstract out complexity via domain-specific-languages. Be prepared to look at the high-level abstract issues, then drill down into the details.

  10. It should be fun: AoE is a good, old-fashioned-fun kind of computer game. It has huge replay value. Likewise, development should be fun, especially if you have the right process and schedule in place.
     

Wednesday, November 28, 2007

Have a child trigger a method in its parent

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

Often you'll want to have a child object trigger some method in its parent. For example, you'll click a user control, but want that to change something in the parent control.  .Net 2.0 makes it very easy to do this. In .Net 1.1 (at least to my knowledge), this required a bunch of steps. Now, you can just add two lines in the object (declare a delegate, and then create an instance of that), and then use just one line in that object's consumer to specify the method to-be-called. In this case, we create an object "MyObject", with an event to be

namespace AddEvent
{
  public class Program
  {
    static void Main(string[] args)
    {
      MyOject o = new MyOject();
      o.GotClickedHandler += ParentGotClickedHandler;
      o.DoStuff();  //Trigger the object for some reason (this could come from a UI event like clicking it)
    }

    public static bool ParentGotClickedHandler(int i)
    {
      //I'm in the parent, but was triggered from the child object.
      i = i * 2;
      Console.WriteLine(i);
      return true;
    }

  }

  public class MyOject
  {

    public delegate bool GotClickedDelegate(int i);
    public GotClickedDelegate GotClickedHandler;


    public void DoStuff()
    {
      //trigger event:
      //trigger an event, passing that data
      int i = DateTime.Now.Second;

      if (this.GotClickedHandler != null)
      {
        GotClickedHandler(i);
      }
    }
  }
}

Tuesday, November 27, 2007

Displaying different colored text to the console (just like MSBuild)

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

I really like how MSBuild displays different colored text to the console - red for errors, yellow for warnings, green for success, etc... It's just a nice perk.

You can easily do this too using Console.ForegroundColor. For example, the following code has a master method "_ConsoleWrite" that takes the text and a ConsoleColor. It then keeps track of the original color, writes the text in the new color, and restores the original. It's simple, but adds a nice touch to a console app.


    private static void _ConsoleWrite(string strText, ConsoleColor cWrite)
    {
      ConsoleColor cOriginal = Console.ForegroundColor;

      Console.ForegroundColor = cWrite;
      Console.WriteLine(strText);

      Console.ForegroundColor = cOriginal;
    }

 

    public static void ConsoleWriteNormal(string strText)
    {
      _ConsoleWrite(strText, ConsoleColor.Gray);
    }

    public static void ConsoleWriteError(string strText)
    {
      _ConsoleWrite(strText, ConsoleColor.Red);
    }

    public static void ConsoleWriteWarning(string strText)
    {
      _ConsoleWrite(strText, ConsoleColor.Yellow);
    }

    public static void ConsoleWriteSuccess(string strText)
    {
      _ConsoleWrite(strText, ConsoleColor.Green);
    }