2011-10-05 34 views
0

我不確定這個應用程序正在發生什麼。它運作良好,然後有一天它停止工作。我試圖消除代碼中的單個元素,但是一旦我添加了幾個枚舉(請參閱下面的代碼),它就打破了 - 所以我刪除了它們,但是這並沒有解決問題。然後,我從一個全新的贏得服務(使用VS2010和VS2008)開始,添加類級別的變量,並在添加枚舉後再次啓動該服務。窗口服務拋出一個類型初始值設定錯誤

這是代碼,我想知道如果有人可以幫助我。對此,我真的非常感激。

using _Mail; 
using System; 
using System.Collections.Generic; 
using System.Configuration; 
using System.Diagnostics; 
using System.IO; 
using System.Runtime.InteropServices; 
using System.ServiceProcess; 
using System.Text; 
using System.Threading; 
using System.Net.Mail; 
using Microsoft.Office.Core; 
using Microsoft.Office.Interop.PowerPoint; 
using Microsoft.SharePoint; 

namespace Uploader 
{ 

public partial class _UploaderService : ServiceBase 
{ 
    private static string smtpServer = ConfigurationManager.AppSettings["smtpServer"]; 
    private static string sendTo = ConfigurationManager.AppSettings["sendTo"]; 
    private static string sendFrom = ConfigurationManager.AppSettings["sendFrom"]; 
    private static string portalURL = ConfigurationManager.AppSettings["portalURL"]; 
    private static string imageListFolder = ConfigurationManager.AppSettings["imageListFolder"]; 
    private static string remFolder = ConfigurationManager.AppSettings["remoteFolder"]; 
    private static string sourceFileName = ConfigurationManager.AppSettings["sourceFileName"]; 
    private static string remoteDriveLetter = ConfigurationManager.AppSettings["remoteDriveLetter"]; 
    private static string remoteShareName = ConfigurationManager.AppSettings["remoteShareName"]; 
    private static string userName = ConfigurationManager.AppSettings["userName"]; 
    private static string userPwd = ConfigurationManager.AppSettings["userPwd"]; 
    private static string statusMessage; 
    private static string[] files; 

    private static SPWeb _Web = new SPSite(portalURL).OpenWeb(); 
    private static NETRESOURCE res = new NETRESOURCE(); 

    public enum ResourceScope 
    { 
     RESOURCE_CONNECTED = 1, 
     RESOURCE_GLOBALNET, 
     RESOURCE_REMEMBERED, 
     RESOURCE_RECENT, 
     RESOURCE_CONTEXT 
    }; 
    public enum ResourceType 
    { 
     RESOURCETYPE_ANY, 
     RESOURCETYPE_DISK, 
     RESOURCETYPE_PRINT, 
     RESOURCETYPE_RESERVED 
    }; 
    public enum ResourceUsage 
    { 
     RESOURCEUSAGE_CONNECTABLE = 0x00000001, 
     RESOURCEUSAGE_CONTAINER = 0x00000002, 
     RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004, 
     RESOURCEUSAGE_SIBLING = 0x00000008, 
     RESOURCEUSAGE_ATTACHED = 0x00000010 
    }; 
    public enum ResourceDisplayType 
    { 
     RESOURCEDISPLAYTYPE_GENERIC, 
     RESOURCEDISPLAYTYPE_DOMAIN, 
     RESOURCEDISPLAYTYPE_SERVER, 
     RESOURCEDISPLAYTYPE_SHARE, 
     RESOURCEDISPLAYTYPE_FILE, 
     RESOURCEDISPLAYTYPE_GROUP, 
     RESOURCEDISPLAYTYPE_NETWORK, 
     RESOURCEDISPLAYTYPE_ROOT, 
     RESOURCEDISPLAYTYPE_SHAREADMIN, 
     RESOURCEDISPLAYTYPE_DIRECTORY, 
     RESOURCEDISPLAYTYPE_TREE, 
     RESOURCEDISPLAYTYPE_NDSCONTAINER 
    }; 
    [StructLayout(LayoutKind.Sequential)] 
    public struct NETRESOURCE 
    { 
     public ResourceScope dwScope; 
     public ResourceType dwType; 
     public ResourceDisplayType dwDisplayType; 
     public ResourceUsage dwUsage; 
     public string lpLocalName; 
     public string lpRemoteName; 
     public string lpComment; 
     public string lpProvider; 
    }; 

    [DllImport("mpr.dll")] 
    public static extern int WNetAddConnection2(ref NETRESOURCE 
    netResource, string password, string username, int flags); 

    public cisf_UploaderService() 
    { 
     InitializeComponent(); 
    } 

    protected override void OnStart(string[] args) 
    {    
     try 
     { 
      FileSystemWatcher fsWatcher = new FileSystemWatcher(); 
      fsWatcher.Created += new FileSystemEventHandler(fsw_Created); 

      DisconnectDrive(remoteDriveLetter); 
      res.dwType = ResourceType.RESOURCETYPE_DISK; 
      res.lpLocalName = remoteDriveLetter; 
      res.lpRemoteName = remoteShareName; 
      int stat = WNetAddConnection2(ref res, null, null, 0); 
      statusMessage += "Map Network Drive status - " + stat + "."; 

      //MapDrive(); 

      CleanUp(); 
      fsWatcher.Path = remFolder; 
      fsWatcher.Filter = sourceFileName; 
      fsWatcher.EnableRaisingEvents = true; 
     } 
     catch (Exception ex1) 
     { 
      WriteException(ex1,"Ex1"); 
     } 
    } 

    protected override void OnStop() 
    { 
    } 

    static void fsw_Created(object sender, FileSystemEventArgs e) 
    { 
     statusMessage += "\nNew PowerPoint file detected in directory."; 

     ConvetToJpegs(); 
     AcquireFiles(); 
     CleanUp(); 
     DisconnectDrive(remoteDriveLetter); 

     statusMessage += "\nOperation sucessfuly completed."; 

     EventLog.WriteEntry("Conversion Service Status", statusMessage, EventLogEntryType.Information); 

    } 

    protected static void ConvetToJpegs() 
    { 
     Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application(); 
     Presentation pptPresentation = null; 

     try 
     { 
      pptPresentation = app.Presentations.Open(remFolder + sourceFileName, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); 
      pptPresentation.SaveAs(remFolder + ".", PpSaveAsFileType.ppSaveAsJPG, MsoTriState.msoFalse); 

     } 
     catch (Exception ex2) 
     { 
      WriteException(ex2, "Ex2"); 
     } 
     finally 
     { 
      pptPresentation.Close(); 
      statusMessage += "\nFile conversion completed."; 
     } 
    } 

    protected static void AcquireFiles() 
    { 
     files = null; 

     try 
     { 
      files = Directory.GetFiles(remFolder, "*.jpg"); 
     } 
     catch (Exception ex3) 
     { 
      WriteException(ex3, "Ex3"); 
     } 
     finally 
     { 
      statusMessage += "\nFiles acquired."; 
      if (files.Length > 0) 
      { 
       DeleteOldSlides(); 
      } 
     } 
    } 

    protected static void DeleteOldSlides() 
    { 
     SPList imagesLibrary = _Web.Lists[imageListFolder]; 
     _Web.AllowUnsafeUpdates = true; 
     try 
     { 
      while (imagesLibrary.Items.Count > 1) 
      { 
       imagesLibrary.Items[imagesLibrary.Items.Count - 1].File.Delete(); 
      } 
     } 
     catch (Exception ex4) 
     { 
      WriteException(ex4, "Ex4"); 
     } 
     finally 
     { 
      statusMessage += "\nOld slides deleted."; 
      UploadToSharePoint(); 
     } 
    } 

    protected static void UploadToSharePoint() 
    { 
     _Web.AllowUnsafeUpdates = true; 

     FileStream fs = null; 
     string fileName = string.Empty; 

     try 
     { 
      foreach (string file in files) 
      { 

       fileName = file.Split(@"\".ToCharArray())[1].ToLower(); 
       fs = File.Open(file, FileMode.Open); 
       _Web.Files.Add(imageListFolder + "/" + fileName, fs, true); 
       fileName = string.Empty; 
       fs.Close(); 
      } 
     } 
     catch (Exception ex5) 
     { 
      WriteException(ex5, fileName); 
     } 
     finally 
     { 
      statusMessage += "\nFiles uploaded to SharePoint."; 
      _Web.AllowUnsafeUpdates = false; 
     } 
    } 

    protected static void CleanUp() 
    { 
     string[] path = Directory.GetFiles(remFolder, "*.jpg"); 
     string[] path1 = Directory.GetFiles(remFolder, "*.pptx"); 

     try 
     { 
      foreach (string tempfiles in path1) 
      { 
       if (path != null) 
       { 
        File.Delete(tempfiles); 
       } 
      } 
      foreach (string tempfiles in path) 
      { 
       if (path != null) 
       { 
        File.Delete(tempfiles); 
       } 
      } 
     } 
     catch (Exception ex6) 
     { 
      WriteException(ex6, "Ex6"); 
     } 
     finally 
     { 
      statusMessage += "\nFiles deleted from temporary directory " + remoteShareName ; 
     } 
    } 

    //public static bool MapDrive() 
    //{ 
    // bool ReturnValue = false; 
    // if (System.IO.Directory.Exists(remoteDriveLetter + ":\\")) 
    // { 
    //  DisconnectDrive(remoteDriveLetter); 
    // } 
    // System.Diagnostics.Process p = new System.Diagnostics.Process(); 
    // p.StartInfo.UseShellExecute = false; 
    // p.StartInfo.CreateNoWindow = true; 
    // p.StartInfo.RedirectStandardError = true; 
    // p.StartInfo.RedirectStandardOutput = true; 
    // p.StartInfo.FileName = "net.exe"; 
    // p.StartInfo.Arguments = " use " + remoteDriveLetter + ": " + remoteShareName + " " + userPwd + " /user:" + userName; 
    // p.Start(); 
    // p.WaitForExit(); 
    // string ErrorMessage = p.StandardError.ReadToEnd(); 
    // string OuputMessage = p.StandardOutput.ReadToEnd(); 
    // if (ErrorMessage.Length > 0) 
    // { 
    //  throw new Exception("Error:" + ErrorMessage); 
    // } else { ReturnValue = true; } return ReturnValue; } 

    protected static void DisconnectDrive(string DriveLetter) 
    { 
     Process p = new Process(); 

     p.StartInfo.UseShellExecute = false; 
     p.StartInfo.CreateNoWindow = true; 
     p.StartInfo.RedirectStandardError = true; 
     p.StartInfo.RedirectStandardOutput = true; 

     try 
     { 
      p.StartInfo.FileName = "net.exe"; 
      p.StartInfo.Arguments = " use " + "Z" + ": /DELETE"; 
      p.Start(); 
     } 
     catch (Exception ex7) 
     { 
      WriteException(ex7, "Ex7"); 
     } 
     finally 
     { 
      p.WaitForExit(); 
     } 
    } 

    public static void WriteException(Exception ex, string source) 
    { 
     string err = "Uploader Error" + 
        "\n\nError Message from method " + source + ": " + ex.Message.ToString() + 
        "\n\nStack Trace: " + ex.StackTrace.ToString() + "\n"; 
     EventLog.WriteEntry("Conversion Service", err, EventLogEntryType.Warning); 

     _Mail sendEmail = new _Mail(); 
     sendEmail.SMTPServer = smtpServer; 
     sendEmail.MailTo = sendTo; 
     sendEmail.MailFrom = sendFrom; 
     sendEmail.MailSubject = "Uploader Error"; 
     sendEmail.MailBody = err; 
     sendEmail.Send(); 
    }   
} 
} 
+2

什麼是確切的消息,有哪些呢InnerException說? –

+2

「Stoped working」不是很有用...是否拋出異常,如果有的話,哪些錯誤信息是什麼?你爲什麼不一行一行地調試,看看它在哪裏拋出異常? –

+0

@MarcGravell我總是忘記InnerException –

回答

0

類型初始值設定項錯誤意味着無法創建類型。這發生在CLR初始化所有靜態字段時調用構造函數之前。由於您的初始化做了超過調用私有構造或設置你打開自己高達難以調試的問題

在這種情況下,一個字面值它可能做的一個問題,您的AppSettings關鍵之一

例如

private static string smtpServer = ConfigurationManager.AppSettings["smtpServer"]; 
private static string sendTo = ConfigurationManager.AppSettings["sendTo"]; 
... 

這看起來可疑也。

private static SPWeb _Web = new SPSite(portalURL).OpenWeb(); 
private static NETRESOURCE res = new NETRESOURCE(); 

而是在構造函數中做你需要做的事情。您可能還需要增加一個輔助方法,這樣,您就可以提出一個更好的異常(或相反,你可以爲馬克礫石評論只看內部異常)

例如

private string safeGetAppSetting(string key) 
{ 

    try 
    { 
     return ConfigurationManager.AppSettings["smtpServer"]; 
    } 
    catch(ConfigurationErrorsException) 
    { 
     throw new InvalidOperationException(string.Format("key {0} is missing or misconfigured", key); 
    } 
} 




public cisf_UploaderService() 
{ 
    InitializeComponent(); 
    smtpServer = safeGetAppSetting("smtpServer"); 
} 

更新事後看來,將Debugger.Launch()添加到Program.Main()中,正如kzen提到的那樣可能是值得的。如果它不是本地開發機器,那麼在根上添加一些額外的日誌記錄可能也有幫助。

 try 
     { 
      ServiceBase[] ServicesToRun; 
      ServicesToRun = new ServiceBase[] 
      { 
       new SampleWindowsService() 
      }; 
      ServiceBase.Run(ServicesToRun); 
     } 
     catch (Exception ex) 
     { 
      string SourceName = "YourService.ExceptionLog"; 
      if (!EventLog.SourceExists(SourceName)) 
      { 
       EventLog.CreateEventSource(SourceName, "Application"); 
      } 

      EventLog eventLog = new EventLog(); 
      eventLog.Source = SourceName; 
      string message = ""; 
      if (ex.InnerException != null) 
       string message = string.Format("Exception: {0} \n\nStack: {1} \n\nInnerException: {2}", ex.Message, ex.StackTrace, ex.InnerException.Message); 
      else 
       string message = string.Format("Exception: {0} \n\nStack: {1}", ex.Message, ex.StackTrace); 
      eventLog.WriteEntry(message, EventLogEntryType.Error); 
     } 
+0

好吧,我是一名網絡開發人員,這是我的第一個Windows應用程序:那麼您如何到達這裏的內部異常。 – Risho

+0

它應與原始異常記錄,在事件日誌 –

+0

我一直在做不同的事情,但希望再次討論這個問題。我已經在構造函數中放置了這個延遲,因爲你建議在服務無法啓動的時候,bur仍然會收到同樣的錯誤。 「事件類型clr20r3,P1 slebbuploaderservice.exe,P2 1.0.0.0,P3 4e8cd395,P4 slebbuploaderservice,P5 1.0.0.0,P6 4e8cd395,P7 4,P8 7,P9 system.typeinitialization,P10 NIL」。 – Risho

0

Debugger.Launch();代碼的第一線,直到你找到什麼的代碼行拋出異常開始由線爲您服務,debugg線...

+2

通常我會同意這一點。可悲的是,類型初始化並不是超級確定性的。在調用'Debugger.Launch()'之前可能會發生異常,即使您將其放入'Program.Main() –

相關問題