2009-11-03 29 views
8

我對創建.NET項目時可能在Program.cs中使用的任何常用例程/過程/方法感興趣。例如,我通常在我的桌面應用程序中使用以下代碼,以允許輕鬆升級,單實例執行以及未捕獲的系統應用程序錯誤的友好和簡單的報告。你在Program.cs中爲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. 
       } 
      } 
     } 
    } 

我發現這些程序是非常有幫助的。你發現什麼方法對Program.cs有幫助?

+0

我覺得這很可怕,你只是放棄了任何額外的例外。 – 2009-11-03 14:48:45

+3

我不認爲他會在場上拋出額外的例外。他忽略的唯一例外是當他實際向用戶顯示錯誤消息時引發的異常,即對MessageBox.Show()的調用。 – 2009-11-03 15:09:17

回答

5

我儘量避免在Program.cs文件中添加任何重要內容。我爲一個簡單的控制檯應用程序編寫的任何內容都可能會被移到一個類庫中,因此我將爲實際的程序邏輯構建一個單獨的類。

這就是說,有就是我反覆使用一些通用的代碼。最主要的是使用Trace類來處理控制檯輸出,因此我不必在應用程序本身中更改任何重要的代碼,以便在不可避免地過渡到類庫或gui應用程序時將其重定向到日誌文件或其他位置發生:

using System; 
using System.Diagnostics; 

public static void Main(string[] args) 
{ 
    Trace.Listeners.Add(new ConsoleTraceListener()); 
    Trace.WriteLine("Program Started - " + DateTime.Now.ToString());Trace.WriteLine(""); 

    //Call into a separate class or method for the actual program logic 
    DoSomething(); //I'll use Trace for output in here rather than Console 

    Trace.WriteLine("");Trace.WriteLine("Program Finished - " + DateTime.Now.ToString()); 

    Console.Write("Press a key to exit..."); 
    Console.ReadKey(true); 
    Console.WriteLine(); 
} 
+0

這是一個好主意! – Rick 2009-11-03 15:15:45

1

我通常有一個調用另一個函數(例如啓動)一個非常小的主要功能 - 這樣一來,如果某些組件丟失,開始不能即時編譯,我能趕上TypeLoadException並顯示一個人 - 可讀的錯誤信息。

2

對於參數解析,該Novell Options類是我見過的最好的(通過"Best way to parse command line arguments in C#")。我也爲adapted it交互式控制檯應用程序,不只是運行和退出的程序。

這裏的期權類的例子:

static void Main(string[] args) 
{ 
    var p = new new OptionSet() 
     .Add ("v|verbose", v=> setVerbose()) 
     .Add ("h|?|help", v=> showHelp()) 
     .Add ("n|name=", v=> showName(v)); 

    p.Parse (args); 
} 
1

我們通常使用主要用於基本的命令行解析,防撞處理設置,許可檢查,並主要形式的創作(假設它是一個Windows應用程序,而不是控制檯應用程序)。

然而,大部分功能是由主只是實例化和調用其它對象處理。

0

唯一的代碼,我肯定,但到節目是我的異常處理程序:

在開始:

#If Not Debug Then 
     AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf Me.Application_UnhandledException 
     AddHandler Application.ThreadException, AddressOf Me.Application_ThreadException 
#End If 

Private Sub Application_UnhandledException(ByVal sender As Object, ByVal e As System.UnhandledExceptionEventArgs) 
    Me.UnhandledExceptionLog(TryCast(e.ExceptionObject, Exception).Message, New StackTrace(TryCast(e.ExceptionObject, Exception), True), e.ExceptionObject) 
End Sub 
Private Sub Application_ThreadException(ByVal sender As Object, ByVal e As System.Threading.ThreadExceptionEventArgs) 
    Me.UnhandledExceptionLog(e.Exception.Source & Environment.NewLine & e.Exception.Message & Environment.NewLine & e.Exception.StackTrace, New StackTrace(e.Exception, True), e.Exception) 
End Sub 

Public Sub UnhandledExceptionLog(ByVal message As String, ByVal stack As StackTrace, ByVal ex As Object) 
    ' write the exception details to a log and inform the user the he screwed something ;) ' 
End Sub 

這將抓住每一個例外,我錯過了和意志把它寫到我自己的日誌中(向客戶詢問所述的錯誤信息實際上不是最明智的事情......)。

Bobby

相關問題