I'm interested in any common routine/procedures/methods that you might use in you Program.cs when creating a .NET project. For instance I commonly use the following code in my desktop applications to allow easy upgrades, single instance execution and friendly and simple reporting of uncaught system application errors.
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace NameoftheAssembly
{
internal static class Program
{
/// <summary>
/// The main entry point for the application. Modified to check for another running instance on the same computer and to catch and report any errors not explicitly checked for.
/// </summary>
[STAThread]
private static void Main()
{
//for upgrading and installing newer versions
string[] arguments = Environment.GetCommandLineArgs();
if (arguments.GetUpperBound(0) > 0)
{
foreach (string argument in arguments)
{
if (argument.Split('=')[0].ToLower().Equals("/u"))
{
string guid = argument.Split('=')[1];
string path = Environment.GetFolderPath(Environment.SpecialFolder.System);
var si = new ProcessStartInfo(path + "\\msiexec.exe", "/x" + guid);
Process.Start(si);
Application.Exit();
}
}
//end of upgrade
}
else
{
bool onlyInstance = false;
var mutex = new Mutex(true, Application.ProductName, out onlyInstance);
if (!onlyInstance)
{
MessageBox.Show("Another copy of this running");
return;
}
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.ThreadException += ApplicationThreadException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
var ex = (Exception) e.ExceptionObject;
MessageBox.Show("Whoops! Please contact the developers with the following"
+ " information:\n\n" + ex.Message + ex.StackTrace,
" Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
catch (Exception)
{
//do nothing - Another Exception! Wow not a good thing.
}
finally
{
Application.Exit();
}
}
public static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
{
try
{
MessageBox.Show("Whoops! Please contact the developers with the following"
+ " information:\n\n" + e.Exception.Message + e.Exception.StackTrace,
" Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
catch (Exception)
{
//do nothing - Another Exception! Wow not a good thing.
}
}
}
}
I find these routines to be very helpful. What methods have you found helpful in Program.cs?