2016-08-26 40 views
-1

我正在修改我爲工作而編寫的幫助臺程序,並且希望重構我的代碼,以便在發送票證時它會嘗試在創建票證之前先發送電子郵件在我的數據庫中。當調用我的sendmail()方法時引發異常

但是,如果我在我的context.CreateTicket(ticket)方法之前調用我的SendMail(ticket)方法,我會得到一個空引用。異常,即使我事先聲明並初始化票證對象。

這是我爲我的NewTicket方法的代碼

private void CreateNewTicket() 
    { 
     //set search filter to currentuser 
     dS.Filter = "(&(objectClass=user)(anr=" + userName + "))"; 

     //find current user in the acrive director 
     SearchResult sR = dS.FindOne(); 

     var ticket = new HelpTicket 
     { 
      Title = title, 
      DescText = descText, 
      Employee = GetProp(sR, "Name"), 
      EmpEmail = GetProp(sR, "mail"), 
      DateSubmited = DateTime.Now, 
      // Urgency = selectedUrgency, 
      UrgentID = SelectedUrgency.UrgentID, 
      TypeID = SelectedProblemType.TypeID 

     }; 

     try 
     { 
      //if sendmail here it thorws the exception 
      //SendMail(ticket); 
      try { 
       context.CreateTicket(ticket); 
       //If I call context.createticket first it works 
       SendMail(ticket); 
       CloseDialog = true; 
      } 
      catch 
      (System.Exception ex) 
      { 
       MessageBox.Show("Error Submitting ticket: " + ex.Message,"Error Submitting Ticket",MessageBoxButton.OK,MessageBoxImage.Error); 
      } 

     } 
     catch (Exception ex1) 
     { 
      MessageBox.Show("Error Submitting ticket, please try again.\n" + ex1.Message,"Error Creating ticket",MessageBoxButton.OK,MessageBoxImage.Error); 
      CloseDialog = true; 
     } 

    } 

代碼爲Sendmail(票)

public override void SendMail(HelpTicket ticket) 
    { 
     Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application(); 

     Microsoft.Office.Interop.Outlook.MailItem mailMsg = 
     (Microsoft.Office.Interop.Outlook.MailItem)outlook.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); 
     Microsoft.Office.Interop.Outlook.Inspector oInspector = mailMsg.GetInspector; 
     mailMsg.To = "[email protected]"; 
     mailMsg.Subject = ticket.Title; 
     mailMsg.HTMLBody = "<b>Urgency: </b>" + ticket.Urgency.Description + "<br/>" + 
      "<b>Problem Type: </b>" + ticket.ProblemType.ProblemDesc + "<br/><hr/><br/>" + 
       ConvertToHtml(ticket.DescText); 
     mailMsg.Send(); 

    } 

如果您需要更多的代碼片段,讓我知道,我會後他們

回答

0

在SendMail中,您正在引用Ticket的對象屬性,但您是 而不是創建這些對象,或者您不顯示它。無論如何,根據您發佈 的代碼,只要您引用ticket.ProblemType.ProblemDesc和ticket.Urgency.Description ,您將獲得空引用異常。

+0

好的,這是有道理的,因爲在它進入CreateTicket()方法將新票發回給我的數據庫之前,一旦它返回到調用票然後有正確的鏈接到其他對象,緊迫性和ProblemType 。 我想我知道如何解決這個問題。感謝大腦碰撞! – PnkFld7892

相關問題