Saturday, May 27, 2006

Continually learning better coding methods

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

Coding requires constant learning. Here are some ideas to help with that:

1 - Be prepared to spend not just time, but mental energy.

2 - Find ways to get input:

  • Other Opinions:
    • Code Reviews - both having people look at your code, and looking at other's code.
    • Read blogs
    • Read articles
    • Read the documentation. If you're using a collection, read the documentation to see how it suggests enumerating through or referencing it's items.
  • Experiment on your own code
  • Reflect back on your code
  • Ask yourself, "does this make sense?". If your own code doesn't make sense to you, it probably won't make sense to others.
  • Make sure that you're not re-inventing the wheel. Look for resuable components.

3 - Make the intent of your code clear so that others can help. If Bob doesn't know what you're trying to do, Bob can't easily help you.

  • Use smaller methods
  • Add helpful comments that explain intent, not just repeat the steps that the code is doing
  • Abstract out context and dependencies such that it's easier for people to understand what you really want.

There's obviously a lot more to say on this, I'll make some follow-up posts.

Thursday, May 18, 2006

How to send the Console output to a string

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

Sometimes when writing a tool or automated process, you want to read in the console output and send it to a string. From there, you can do whatever you want to it, such as parse for info. For example, a third-party tool (not necessarily even built with .Net) may display result information to the console, and you may want that info as part of some bigger process. The classes to do this reside in System.Diagnostics.


    public static string GetConsoleOutput(string strFileName, string strArguments)
    {

      ProcessStartInfo psi = new ProcessStartInfo();
      StringBuilder sb = new StringBuilder();
      try
      {
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        //Need to include this for Executable version (appears not to be needed if UseShellExecute=true)
        psi.CreateNoWindow = true;   
        psi.FileName = strFileName;
        psi.Arguments = strArguments;
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;

        Process p = Process.Start(psi);

        sb.Append(p.StandardOutput.ReadToEnd());
        sb.Append(p.StandardError.ReadToEnd());

        p.WaitForExit();

      }
      catch (Exception ex)
      {
        sb.Append("\r\nPROCESS_ERROR:" + ex.ToString()); ;
      }
      return sb.ToString();

    }