0

I managed to add a contact but when I try and add an invoice I get an error message 'A validation exception occurred'. I would appreciate suggestions as to what is causing this error.

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        /// first create an instance of the Xero API
        var api = new Xero.Api.Example.Applications.Private.Core(false);

        Contact newContact = new Contact();
        newContact.Name = "Orac"; 
        Invoice newInvoice = new Invoice();
        newInvoice.Contact = new Contact();
        newInvoice.Contact = newContact;
        newInvoice.Date = System.DateTime.Now;
        newInvoice.DueDate = System.DateTime.Now.AddMonths(1);
        newInvoice.Status = Xero.Api.Core.Model.Status.InvoiceStatus.Authorised;
        newInvoice.Type = Xero.Api.Core.Model.Types.InvoiceType.AccountsReceivable;
        List<LineItem> lines = new List<LineItem>();
        LineItem li = new LineItem();
        li.LineAmount = Convert.ToDecimal("200.00");
        li.Quantity = Convert.ToDecimal("1.0000");
        li.ItemCode = "100";
        li.Description = "Webdev inv test";
        li.AccountCode = "200";
        li.UnitAmount = Convert.ToDecimal("50.00");
        lines.Add(li);
        newInvoice.LineItems = lines;

        // call the API to create the contact
        api.Invoices.Create(newInvoice);
        //api.Contacts.Create(newContact);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
John
  • 45
  • 6

2 Answers2

2

Retain the result of your creation request - e.g.

var result = api.Invoices.Create(newInvoice);

...and examine the Errors and Warnings properties of the result to determine what's wrong with your request.

rustyskates
  • 856
  • 4
  • 10
  • 1
    For this to work, summariseErrors must be set to false. It's true by default. – giraffe.guru May 31 '18 at 01:08
  • 1
    var createdInvoice = api.Invoices.SummarizeErrors(false).Create(newInvoice); if (createdInvoice.ValidationStatus == Xero.Api.Core.Model.Status.ValidationStatus.Error) { foreach (var message in createdInvoice.Errors) { Console.WriteLine("Validation Error: " + message.Message); } – John May 31 '18 at 08:49
2

The type of exception thrown is a ValidationException. Either catch that type specifically or cast your caught generic Exception, and inspect the ValidationErrors property

MJMortimer
  • 865
  • 5
  • 10