Capturing standard output from console app

Here's code that redirects output from my Proofreading Tracker console app:

using System;
using System.Diagnostics;

sealed class TestRedirStdOutput
{
    public static void Main()
    {
        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.Arguments = "titles";
        p.StartInfo.FileName = "prt.exe";
        p.Start();

        // To avoid deadlocks, always read the output stream first and then wait.
        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();

        Console.WriteLine(" Captured this output:\n");
        Console.WriteLine(output + "\n");
        Console.WriteLine(" Press any key to exit...");
        Console.ReadLine();
    }
}

Prevent Multiple Instances of .NET App

Sometimes there are good reasons not to allow any copies of your app to be executing alongside one another. We only want a single instance of the app running on any given machine.

The links below connect to downloadable examples of implementing a mutex lock in .NET applications.

Download the Console app example.

Below is the complete code from Program.cs of a WinForms C# app that shows usage of a mutex to prevent multiple instances:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;

namespace ProofreadingTracker
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            string mutexName = "Local\\" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            using (Mutex mutex = new Mutex(false, mutexName))
            {
                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show("There is an instance of this application already running!", "Proofreading Tracker");
                    return;
                }
                else
                {
                    GC.Collect();
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());

                }
            }
        }
    }
}

Get Command Line Arguments

Shows how to get what was typed at the command line. This is a bit different than getting args passed into console app via Main method's string[] args.

Download example.

Listing:

using System;

sealed class ConsoleArgsDemo
{
    public static void Main()
    {
        string[] args = Environment.GetCommandLineArgs();
        Console.WriteLine(" GetCommandLineArgs(): {0}", String.Join(", ", args));
        switch (args.Length)
        {
            case 0:
                //won't ever be reached
                Console.WriteLine(" Nothing entered on command line.");
                break;
            case 1:
                Console.WriteLine(" One word was typed on the command line: {0}", args[0]);
                break;
            case 2:
                Console.WriteLine(" Two words entered on command line: {0}, {1}.", args[0], args[1]);
                break;
        }
    }
}

Checking if Object has particular Method

Checking if an object has a particular method:

Download example.

Listing:

    public static class MethodChecker
    {
        public static bool HasMethod(this object objectToCheck, string methodName)
        {
            /* USAGE:
            if (!MethodChecker.HasMethod(c, "attack_roll"))
            {
                ConsoleIO.conShow("Too bad " + c.A_Descriptor + " doesn't get an attack roll...\n");
            }
           */
            try
            {
                var type = objectToCheck.GetType();
                return type.GetMethod(methodName) != null;
            }
            catch (AmbiguousMatchException)
            {
                // ambiguous means there is more than one result,
                // which means: a method with that name does exist
                return true;
            }
        }
    }

And here is an example of a program demonstrating use of this MethodChecker:

using System;
using System.Reflection;

public class MethodCheckerExample
{
    public static void Main()
    {
        Doggy scruffy = new Doggy();

        if (MethodChecker.HasMethod(scruffy, "Bark"))
        {
            Console.WriteLine(" Doggy instance \"scruffy\" has method Bark().");
        }

        if (!MethodChecker.HasMethod(scruffy, "Poop"))
        {
            Console.WriteLine(" Doggy instance \"scruffy\" does NOT have method Poop().");
        }
    }

    class Doggy
    {
        public void Bark()
        {
            Console.WriteLine("Woof, woof!");
        }
    }
}

public static class MethodChecker
{
    public static bool HasMethod(this object objectToCheck, string methodName)
    {
        /* USAGE:
        if (!MethodChecker.HasMethod(c, "attack_roll"))
        {
            ConsoleIO.conShow("Too bad " + c.A_Descriptor + " doesn't get an attack roll...\n");
        }
       */
        try
        {
            var type = objectToCheck.GetType();
            return type.GetMethod(methodName) != null;
        }
        catch (AmbiguousMatchException)
        {
            // ambiguous means there is more than one result,
            // which means: a method with that name does exist
            return true;
        }
    }
}

Using a Struct "Globally"

Making a structure instance available all throughout your top-level class:

Download example forthcoming.

Listing:

public class MyClass
{
    /*public const ***
      public static whateverVar 
    make SURE your public stat var of type MyStruct is declared here,
    then initialize it in Main()
    */

    MyStruct struct;

    public static void Main()
    {
    //init public static vars... 
    struct = GetDataForStructInit();
           
    }

    private static MyStruct GetDataForStructInit()
    {
        MyStruct ms;
    //read data from file or whatever, then initialize with constructor
    ms = new MyStruct(data1, data2, data3, data4);        
        return ms;
    }
  
   
      public struct MyStruct
    {
        public int x;
        public int y;
        public string v;
        public bool b;

        public MyStruct(int h, int m, string p, bool q)
        {
            x = h;
            y = m;
            v = p;
            b = q;           
        }
    }
}

Object Serialization and Deserialization

Here's a link with downloadable examples:

http://kyrathasoft.com/errata/serialize_deserialize.htm

And here's the code snippets:

Serialization:

FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);

try {

   BinaryFormatter bFormatter = new BinaryFormatter();
   bFormatter.Serialize(fs, myObject);
                         
} catch (Exception exception) {

    MessageBox.Show(exception.Message);

} finally {

    if (fs != null) {
        fs.Close();
    }
}

Deserialization:

FileStream fs = new FileStream(savePath, FileMode.Open, FileAccess.Read, FileShare.None);

try {
    BinaryFormatter bFormatter = new BinaryFormatter();
    myObject = (myObject)bFormatter.Deserialize(fs);           
} catch (Exception exception) {
    MessageBox.Show(exception.Message);                    
} finally {
    if (fs != null) {
        fs.Close();
    }
}