Sono interessato a routine/procedure/metodi comuni che potresti utilizzare in Program.cs durante la creazione di un progetto .NET. Ad esempio, utilizzo comunemente il seguente codice nelle mie applicazioni desktop per consentire aggiornamenti semplici, esecuzione di singole istanze e reporting semplice e amichevole degli errori delle applicazioni di sistema non rilevati.Quali routine comuni inserisci in Program.cs per C#
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.
}
}
}
}
Trovo queste routine per essere molto utile. Quali metodi hai trovato utili in Program.cs?
Trovo abbastanza orribile il fatto che si stiano lasciando cadere altre eccezioni sul pavimento. –
Non penso che lascerà altre eccezioni sul pavimento. Le uniche eccezioni che egli ignora sono quelle causate quando mostra effettivamente un messaggio di errore all'utente, cioè la chiamata a MessageBox.Show(). –