Sunday, February 13, 2005

Tips for making machine-independent code

[This was originally posted at]

The code you write as a developer will  be run on other people's machines. Therefore while it's great that it runs on your local machine, people (such as your manager and other developers) will come knocking on your door if your code doesn't also run on their machines. There are a couple tips I've found useful for writing machine-independent code:

Never hard-code absolute file paths.

Physical paths change from machine to machine. The harddrive letter may change (your machine may be "C", but perhaps a build server will be something else like "D". Developers, or even external tools, may also run the code in different directories. Hard-coding these absolute paths in the code itself will therefore ensure errors. There are a couple tips to avoid hard-coding the paths:

  1. Use relative paths where appropriate.
  2. Use IO.Path.GetTempPath() as the temporary directory.
  3. When running from batch scripts, use the %cd% to get root directory as opposed to hard-coding the directory. Also, use environmental variables for common folders such as %windir% and %programFiles%.
  4. Make an appSetting in the app.config/web.config to store the directory.

Write-File methods create the necessary directories.

Consider having your write-file method create the necessary directory. For example, if you're trying to write out to "C:\Projects\myFile.txt", but the "Projects" folder does not exist, the write will fail. There is a pro and con to this:

  • Pro: Your files paths will automatically be created if they haven't been initialized, preventing a crash.
  • Con: Could pose a security risk - you may want to lock down the application such that it does not have security permissions to create its own directories. A hacker could possible exploit creating an unintended directory.

If you opt not to have your write-methods create their own directories, then at least have a initialization script that creates the appropriate directories.

Use Embedded Resources

I discussed the benefits of embedded resources in my previous post. The main benefit for machine independent code is that embedded resources are contained within the DLL, ensuring that you (1) don't need to worry about the file path of each resource, and (2) only need to transfer 1 file (the DLL) from the bin instead of all the source resource files. Two particularly useful methods here would be:

  • GetEmbeddedResourceContent --> (returns string of resource content given assembly and resource name)
  • CreateFileFromEmbeddedResource (makes copy of the resource and returns file path)

Make sure that your code runs on the development build

The build server contains the official version of your code. If your code isn't even flexible enough to run on the build server, then it is definitely "broken".

No comments:

Post a Comment