2014-09-30 2 views
0

Я получаю сообщение об ошибке в моем apiPdfsharpController. Отчет, который я печатаю, вытягивает данные из класса Job. Класс задания извлекает данные из класса Customer. Данные класса клиента являются тем, что вызывает исключение. Я добавил ViewModel для задания, однако я не знаю, нужно ли это использовать здесь. если это так, я не знаю, как использовать его вместо самого класса работы.Как настроить PdfSharp Controller

Сообщение об исключении: Ссылка на объект не установлена ​​в экземпляр объекта.

StackTrace: на TexasExterior.Controllers.PdfController.Get (Nullable`1 ид) в C: \ Разработка \ TexasExterior \ TexasExterior \ Контроллеры \ PdfController.cs: линия 92

apiPdfController:

public string Get(int? id) // allow nullable parameter 
    { 
     if (!id.HasValue) // if null return an empty string 
     { 
      return string.Empty; 
     } 

     // your code : 

     apiJobController adapter = new apiJobController(); 
     Job job = new Job(); 
     job = adapter.GetJob(id); 
     if (job == null) 
     { 
      return string.Empty; 
     } 
     try 
     { 

      // Create a new PDF document 
      PdfDocument document = new PdfDocument(); 
      document.Info.Title = "Created with PDFsharp"; 

      // Create an empty page 
      PdfPage page = document.AddPage(); 
      page.Size = PageSize.Letter; 
      // Get an XGraphics object for drawing 
      XGraphics gfx = XGraphics.FromPdfPage(page); 
      XPen pen = new XPen(XColors.Black, Math.PI); 
      //XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always); 

      // Create a font 
      XFont HeadingFont = new XFont("Times New Roman", 20, XFontStyle.Bold); 
      XFont BodyFont = new XFont("Times New Roman", 12); 
      // Draw the text 


      gfx.DrawString("Date : ", BodyFont, XBrushes.Black, 
       new XRect(127, 120, page.Width, page.Height), 
       XStringFormats.TopLeft); 

      gfx.DrawString(job.JobContractDate.ToString(), BodyFont, XBrushes.Black, 
       new XRect(160, 120, page.Width, page.Height), 
       XStringFormats.TopLeft); 

      gfx.DrawString("Job Number : ", BodyFont, XBrushes.Black, 
       new XRect(90, 140, page.Width, page.Height), 
       XStringFormats.TopLeft); 

      gfx.DrawString(job.JobNumber.ToString(), BodyFont, XBrushes.Black, 
      new XRect(160, 140, page.Width, page.Height), 
      XStringFormats.TopLeft); 

      gfx.DrawString("Job Name", BodyFont, XBrushes.Black, 
       new XRect(100, 160, page.Width, page.Height), 
       XStringFormats.TopLeft); 

      gfx.DrawString(job.JobName, BodyFont, XBrushes.Black, 
      new XRect(160, 160, page.Width, page.Height), 
      XStringFormats.TopLeft); 

      gfx.DrawString("Customer : ", BodyFont, XBrushes.Black, 
       new XRect(102, 180, page.Width, page.Height), 
       XStringFormats.TopLeft); 

      gfx.DrawString(job.Customer.CustomerName, BodyFont, XBrushes.Black, 
       new XRect(160, 180, page.Width, page.Height), 
       XStringFormats.TopLeft); 

      gfx.DrawString(job.Customer.CustomerAddress, BodyFont, XBrushes.Black, 
       new XRect(160, 195, page.Width, page.Height), 
       XStringFormats.TopLeft); 

      gfx.DrawString(job.Customer.CustomerCity + job.Customer.CustomerState + job.Customer.CustomerZipcode.ToString(), BodyFont, XBrushes.Black, 
       new XRect(160, 210, page.Width, page.Height), 
       XStringFormats.TopLeft); 




    var dt = DateTime.Now.ToString("f").Replace('/', '-').Replace(':', '-'); 
      var filename = string.Format("{0}--{1}.pdf", job.JobName, dt); 
      string path = Path.Combine(HttpContext.Current.Server.MapPath("~/JobSetupPdfs/"), Path.GetFileName(filename)); 
      document.Save(path); 

      // ...and start a viewer. 
      Process.Start(path); 
     } 
     catch (Exception ex) 
     { 
      Debug.Print(ex.ToString()); 
     } 
     return string.Empty; 

JobViewModel

public class JobViewModel 
{ 
    public int JobId { get; set; } 
    public int JobNumber { get; set; } 
    public string JobName { get; set; } 
    public string JobDescription { get; set; } 
    public int JobOriginalContract { get; set; } 
    public DateTime? JobContractDate { get; set; } 
    public DateTime? JobBillingDate { get; set; } 
    public int JobTotalCO { get; set; } 
    public int JobRevisedContract { get; set; } 
    public int JobOriginalBudget { get; set; } 
    public string JobBillingForm { get; set; } 
    public string JobTESPM { get; set; } 
    public string JobTESSuperintendent { get; set; } 
    public string JobStatus { get; set; } 
    public string JobMoreShit { get; set; } 
    public bool JobTaxExempt { get; set; } 
    public bool JobCertPayroll { get; set; } 
    public int JobCost { get; set; } 
    public int JobRemainingBudget { get; set; } 
    public int JobProfit { get; set; } 
    public int JobPercentage { get; set; } 
    public int JobTotalBilled { get; set; } 
    public int JobBalanceToBill { get; set; } 
    public int JobPaidToDate { get; set; } 
    public int JobBalanceDue { get; set; } 
    public string JobAddress { get; set; } 
    public string JobCity { get; set; } 
    public string JobState { get; set; } 
    public int JobZipcode { get; set; } 
    public string JobCounty { get; set; } 
    public Int64 JobPhoneNumber { get; set; } 
    public Int64 JobFaxNumber { get; set; } 
    public bool JobIsHidden { get; set; } 

    public int JobRetainage { get; set; } 
    public int JobMinWage { get; set; } 
    public string JobInsProgram { get; set; } 

    public int CustomerId { get; set; } 

    //public int? GeoAreaId { get; set; } 

    //public int? JobClassId { get; set; } 

    //public int? JobTypeId { get; set; } 

} 

apiJobController

// GET api/<controller>/5 
    public Job GetJob(int? id) 
    { 
     using (var context = new ApplicationDbContext()) 
     { 
      Job model = new Job(); 
      model = context.Jobs.Where(j => j.JobId == id).FirstOrDefault(); 
      return model; 
     } 

    } 

JobClass

public class Job 
{ 
    public int JobId { get; set; } 
    public int JobNumber { get; set; } 
    public string JobName { get; set; } 
    public string JobDescription { get; set; } 
    public int JobOriginalContract { get; set; } 
    public DateTime? JobContractDate { get; set; } 
    public DateTime? JobBillingDate { get; set; } 
    public int JobTotalCO { get; set; } 
    public int JobRevisedContract { get; set; } 
    public int JobOriginalBudget { get; set; } 
    public string JobBillingForm { get; set; } 
    public string JobTESPM { get; set; } 
    public string JobTESSuperintendent { get; set; } 
    public string JobStatus { get; set; } 
    public string JobMoreShit { get; set; } 
    public bool JobTaxExempt { get; set; } 
    public bool JobCertPayroll { get; set; } 
    public int JobCost { get; set; } 
    public int JobRemainingBudget { get; set; } 
    public int JobProfit { get; set; } 
    public int JobPercentage { get; set; } 
    public int JobTotalBilled { get; set; } 
    public int JobBalanceToBill { get; set; } 
    public int JobPaidToDate { get; set; } 
    public int JobBalanceDue { get; set; } 
    public string JobAddress { get; set; } 
    public string JobCity { get; set; } 
    public string JobState { get; set; } 
    public int JobZipcode { get; set; } 
    public string JobCounty { get; set; } 
    public Int64 JobPhoneNumber { get; set; } 
    public Int64 JobFaxNumber { get; set; } 
    public bool JobIsHidden { get; set; } 

    public int JobRetainage { get; set; } 
    public int JobMinWage { get; set; } 
    public string JobInsProgram { get; set; } 

    public int CustomerId { get; set; } 
    public virtual Customer Customer { get; set; } 

    //public int? GeoAreaId { get; set; } 
    //public virtual GeoArea GeoArea { get; set; } 

    //public int? JobClassId { get; set; } 
    //public virtual JobClass JobClass { get; set; } 

    //public int? JobTypeId { get; set; } 
    //public virtual JobType JobType { get; set; } 

    public virtual ICollection<ChangeOrder> ChangeOrders { get; set; } 

} 

Update Угловая контроллер

$scope.EmailPdf = function() { 

    var id = $scope.currentItem.JobId 
    $http.get('/api/Pdf/' + id).success(function() { 
     $scope.PrintPreviewModal(); 
    }); 
} 

Посмотреть

        <label>Number:</label> 
            <input ng-model="currentItem.JobNumber" type="text" name="JobNumber"> 
            <input ng-hide="true" ng-model="currentItem.JobContractDate" type="text" /> 
            <label>Customer:</label> 
            <input stype="text" ng-model="currentItem.Customer.CustomerName" 
              typeahead="customer.CustomerName for customer in customerArray | filter:$viewValue" 
              placeholder="Enter Customer" typeahead-on-select="selectEditCustomer($item)"> 
           </div> 
           <div class="inline-fields"> 
            <label>Status:</label> 
            <select ng-model="currentItem.JobStatus"> 
             <option value="" selected="selected">Select</option> 
             <option value="Active">Active</option> 
             <option value="InActive">InActive</option> 
             <option value="Complete">Complete</option> 
            </select> 
            <label>Address:</label> 
            <input disabled style="width:200px" ng-model="currentItem.Customer.CustomerAddress" type="text"> 
           </div> 
           <div class="inline-fields"> 
            <label">Name:</label> 
            <inputng-model="currentItem.JobName" type="text"> 
            <label>City:</label> 
            <input disabled style="width: 93px" ng-model="currentItem.Customer.CustomerCity" type="text"> 

            <label>St:</label> 
            <input disabled style="width: 30px" ng-model="currentItem.Customer.CustomerState" type="text"> 

            <label>Zip:</label> 
            <input disabled style="width: 44px" ng-model="currentItem.Customer.CustomerZipcode" type="text"> 
           </div> 
<inputng-click="EmailPdf(currentItem)" type="button" value="Email" /> 
+1

Это говорит ошибка на линии 92, которая является линией 92? – DavidG

+0

gfx.DrawString (job.Customer.CustomerName, BodyFont, XBrushes.Black, – texas697

+0

Я делаю ставку 'job.Customer' равно нулю. – DavidG

ответ

0

Проблема заключается в том, что ваш Job объект имеет нулевое Customer имущество. Измените функцию GetJob, чтобы получить его, как это:

model = context 
      .Jobs 
      .Include("Customer") //This is the important addition 
      .Where(j => j.JobId == id) 
      .First(); 
Смежные вопросы