public void it_can_UpdateOrCreate_a_model_that_represents_a_valid_endpoint() { var integrationProxy = new Stubs.StubIntegrationProxy(); Repository repository = new Repository(integrationProxy); repository.UpdateOrCreate(new Invoice()); Assert.AreEqual("Invoice", integrationProxy.LastEndpointName); }
private static void TestCreatingAndUpdatingContacts(Repository repository) { // Make a PUT call to the API - add a dummy contact var contact = new Contact { Name = TestContactName }; contact = repository.UpdateOrCreate(contact); Console.WriteLine(string.Format("The contact '{0}' was created with id: {1}", contact.Name, contact.ContactID)); Console.WriteLine(string.Format("The validation status was: {0}", contact.ValidationStatus)); // Try to update the contact that's just been created, but this time use a POST method contact.EmailAddress = string.Format("{0}@nowhere.com", contact.Name.ToLower().Replace(" ", ".")); contact = repository.UpdateOrCreate(contact); Console.WriteLine(string.Format("The contact '{0}' was updated with email address: {1}", contact.Name, contact.EmailAddress)); // Get the contact by it's Id... var reReadContact = repository.Contacts.First(c => c.ContactID == contact.ContactID); Console.WriteLine(string.Format("The contact '{0}' was re-read using it's ContactID: {1}", reReadContact.Name, reReadContact.ContactID)); }
//this Method Update XERO Invoice Status given by Guid public XeroApi.Model.Invoice UpdtateInvoice(Repository repos, String strGuid, String[] arrOrderItems, int PaymentTerms, Decimal deDeliveryCharges, String PROMO) { if (repos == null) { return(null); } String[] arrLineItem; //create Line Itmes XeroApi.Model.LineItems LItems = new LineItems(); //Xero Model LineItem XeroApi.Model.LineItem lItem; /*Invoice Line Items Creation*/ #region Invoice LineItems for (int i = 0; i < arrOrderItems.Length; i++) { if (!String.IsNullOrEmpty(arrOrderItems[i])) { arrLineItem = arrOrderItems[i].Split(','); if (i == 0) { lItem = new XeroApi.Model.LineItem { Description = arrLineItem[1], ItemCode = arrLineItem[2], UnitAmount = Convert.ToDecimal(arrLineItem[5]), Quantity = Int32.Parse(arrLineItem[4]), TaxType = "OUTPUT" }; lItem.AccountCode = "200"; LItems.Add(lItem); } if (i != 0) { lItem = new XeroApi.Model.LineItem { Description = arrLineItem[2], ItemCode = arrLineItem[3], UnitAmount = Convert.ToDecimal(arrLineItem[6]), Quantity = Int32.Parse(arrLineItem[5]), TaxType = "OUTPUT" }; lItem.AccountCode = "200"; LItems.Add(lItem); } } } //Delivery Handling item Adding here lItem = new XeroApi.Model.LineItem { Description = "Delivery & Handling, D & H", UnitAmount = Convert.ToDecimal(deDeliveryCharges) }; lItem.AccountCode = "200"; LItems.Add(lItem); #endregion /*End Invoice Line Items Creation*/ #region Promotional Item Creation if (!String.IsNullOrEmpty(PROMO)) { String[] ProItems = PROMO.Split('|'); String[] ProItem; for (int i = 0; i < ProItems.Length; i++) { if (!String.IsNullOrEmpty(ProItems[i])) { ProItem = ProItems[i].Split(','); if (i == 0) { float ShippingCost; decimal amount = 0; //Add a line for promotional Item lItem = new XeroApi.Model.LineItem { Description = ProItem[0].ToString(), UnitAmount = Convert.ToDecimal(amount), Quantity = Int32.Parse(ProItem[2]) }; lItem.AccountCode = "200"; LItems.Add(lItem); } if (i != 0) { float ShipCost; decimal amount = 0; //Add a line for promotional Item lItem = new XeroApi.Model.LineItem { Description = ProItem[1].ToString(), UnitAmount = Convert.ToDecimal(amount), Quantity = Int32.Parse(ProItem[3]) }; lItem.AccountCode = "200"; LItems.Add(lItem); } } } } #endregion Promotional Item Creation XeroApi.Model.Invoice deltoneInvoice = new XeroApi.Model.Invoice { Type = "ACCREC", InvoiceID = new Guid(strGuid), LineItems = LItems, LineAmountTypes = XeroApi.Model.LineAmountType.Inclusive, Status = "AUTHORISED" }; var updatedInvoice = repos.UpdateOrCreate(deltoneInvoice); if (updatedInvoice.ValidationStatus == XeroApi.Model.ValidationStatus.ERROR) { foreach (var message in updatedInvoice.ValidationErrors) { Console.WriteLine("Validation Error: " + message.Message); } return(null); } return((XeroApi.Model.Invoice)updatedInvoice); }
//End Function Create Dletone Contacty in Xero System /*This method Update the Deltone Contact in the Xero System*/ public XeroApi.Model.Contact UpdateContact(Repository repos, String strGuid, String strCompnayName, String strFirstName, String strLastName, String strDefaultAreadCode, String strDefaultCountryCode, String strDefaultNumber, String strFaxAreaCode, String strFaxCountryCode, String strFaxNumber, String strMobileAreaCode, String strMobileCountryCode, String strMobileNumber, String strEmail, String strStreetAddressLine1, String strStreetCity, String strSteetCountry, String strStreetPostalCode, String strStreetRegion, String strPostalAddressLine1, String strPostalCity, String strPostalCountry, String strPostalCode, String strPostalRegion) { XeroApi.Model.Contact DeltoneContact = new XeroApi.Model.Contact(); try { DeltoneContact.Name = strCompnayName; //Company Name DeltoneContact.FirstName = strFirstName; //First Name of the Compnay Contact DeltoneContact.LastName = strLastName; //Last name of the Compnay Contact DeltoneContact.EmailAddress = strEmail; //Email of the Company Contact DeltoneContact.ContactStatus = "ACTIVE"; //(ACTIVE,ARCHIVED) DeltoneContact.IsCustomer = true; DeltoneContact.ContactID = new Guid(strGuid); //Define Default Phone Number XeroApi.Model.Phone Default_phone = new XeroApi.Model.Phone(); Default_phone.PhoneType = "DEFAULT"; Default_phone.PhoneAreaCode = strDefaultAreadCode; Default_phone.PhoneCountryCode = strDefaultCountryCode; Default_phone.PhoneNumber = strDefaultNumber; //Define Mobile phone Number XeroApi.Model.Phone Mobile = new XeroApi.Model.Phone(); Mobile.PhoneType = "MOBILE"; Mobile.PhoneAreaCode = strMobileAreaCode; Mobile.PhoneCountryCode = strMobileCountryCode; Mobile.PhoneNumber = strMobileNumber; //Define Fax Number XeroApi.Model.Phones deltonePhones = new XeroApi.Model.Phones(); deltonePhones.Add(Default_phone); deltonePhones.Add(Mobile); DeltoneContact.Phones = deltonePhones; //Define Street Address here XeroApi.Model.Addresses deltone_Address = new Addresses(); XeroApi.Model.Address street_Address = new XeroApi.Model.Address(); street_Address.AddressType = "STREET"; street_Address.AddressLine1 = strStreetAddressLine1; street_Address.City = strStreetCity; street_Address.Country = strSteetCountry; street_Address.PostalCode = strStreetPostalCode; street_Address.Region = strStreetPostalCode; //Define Postal Address here XeroApi.Model.Address postal_Address = new XeroApi.Model.Address(); postal_Address.AddressType = "POBOX"; postal_Address.AddressLine1 = strPostalAddressLine1; postal_Address.City = strPostalCity; postal_Address.Country = strPostalCountry; postal_Address.PostalCode = strPostalCode; postal_Address.Region = strPostalRegion; deltone_Address.Add(street_Address); deltone_Address.Add(postal_Address); DeltoneContact.Addresses = deltone_Address; var createdContact = repos.UpdateOrCreate(DeltoneContact); //Check wether Validation Errors Exsists or Not if (createdContact.ValidationStatus == XeroApi.Model.ValidationStatus.ERROR) { foreach (var message in createdContact.ValidationErrors) { Console.WriteLine("Validation Error: " + message.Message); } return(null); } return((XeroApi.Model.Contact)createdContact); } catch (Exception ex) { ex.StackTrace.ToString(); return(null); } }
static void ExerciseOrganisation(Repository repository) { if (repository == null) { return; } // Make a call to api.xero.com to check that we can use the access token. Organisation organisation = repository.Organisation; Console.WriteLine(string.Format("You have been authorised against organisation: {0}", organisation.Name)); // Make a PUT call to the API - add a dummy contact Console.WriteLine("Please enter the name of a new contact to add to Xero"); string contactName = Console.ReadLine(); if (string.IsNullOrEmpty(contactName)) { return; } Contact contact = new Contact { Name = contactName }; contact = repository.UpdateOrCreate(contact); Console.WriteLine(string.Format("The contact '{0}' was created with id: {1}", contact.Name, contact.ContactID)); Console.WriteLine(string.Format("The validation status was: {0}", contact.ValidationStatus)); // Try to update the contact that's just been created, but this time use a POST method contact.EmailAddress = string.Format("{0}@nowhere.com", contact.Name.ToLower().Replace(" ", ".")); contact = repository.UpdateOrCreate(contact); Console.WriteLine(string.Format("The contact '{0}' was updated with email address: {1}", contact.Name, contact.EmailAddress)); // Get the contact by it's Id... var reReadContact = repository.Contacts.First(c => c.ContactID == contact.ContactID); Console.WriteLine(string.Format("The contact '{0}' was re-read using it's ContactID: {1}", reReadContact.Name, reReadContact.ContactID)); // Construct a linq expression to call 'GET Contacts'... int invoiceCount = repository.Contacts .Where(c => c.UpdatedDateUTC >= DateTime.UtcNow.AddMonths(-1)) .Count(); Console.WriteLine(string.Format("There were {0} contacts created or updated in the last month.", invoiceCount)); // Construct a linq expression to call 'GET Contacts'... var customers = repository.Contacts.Where(c => c.IsCustomer == true).ToList(); Console.WriteLine(string.Format("There are {0} contacts that are customers.", customers.Count)); if (customers.Any(c => !c.IsCustomer)) { Console.WriteLine("Filtering contacts on the IsCustomer flag didn't work!"); } // Try out the 'Single' linq method (http://answers.xero.com/developer/question/36501/) var organisation2 = repository.Organisations.Single(); // Find out how many bank accounts are defined for the organisation... var bankAccounts = repository.Accounts .Where(account => account.Type == "BANK") .OrderBy(account => account.Name) .ToList(); Console.WriteLine(string.Format("There were {0} bank accounts in this organisation.", bankAccounts.Count())); foreach (var bankAaccount in bankAccounts) { Console.WriteLine(string.Format("Bank Account Name:{0} Code:{1} Number:{2}", bankAaccount.Name, bankAaccount.Code, bankAaccount.BankAccountNumber)); } // Get the tracking categories in this org IQueryable<TrackingCategory> trackingCategories = repository.TrackingCategories; foreach (var trackingCategory in trackingCategories) { Console.WriteLine(string.Format("Tracking Category: {0}", trackingCategory.Name)); foreach (var trackingOption in trackingCategory.Options) { Console.WriteLine(string.Format(" Option: {0}", trackingOption.Name)); } } // Try the linq syntax to select items with sales details.. var itemQuery = from item in repository.Items where item.SalesDetails != null select item; var itemList = itemQuery.ToList(); Console.WriteLine("There are {0} inventory items", itemList.Count); foreach (var item in itemList) { Console.WriteLine(string.Format(" Item {0} is sold at price: {1} {2}", item.Description, item.SalesDetails.UnitPrice, organisation.BaseCurrency)); } // Try and create an invoice - but using incorrect data. This should hopefully be rejected by the Xero API Invoice invoiceToCreate = new Invoice { Contact = contact, Type = "ACCREC", Date = DateTime.Today, LineItems = new LineItems { new LineItem { AccountCode = "200", Description = "Blue Widget", UnitAmount = 10m, TaxAmount = 2m, LineAmount = 12m } } }; Console.WriteLine("Creating an invoice that should cause a validation error..."); var createdInvoice = repository.Create(invoiceToCreate); if (createdInvoice.ValidationStatus == ValidationStatus.ERROR) { foreach (var message in createdInvoice.ValidationErrors) { Console.WriteLine("Validation Error: " + message.Message); } } // Download a PDF of the first AR invoice in the system Invoice firstInvoice = repository.Invoices.First(invoice => invoice.Type == "ACCREC"); // Test the FindById to see if we can re-fetch the invoice WITH the line items this time firstInvoice = repository.FindById<Invoice>(firstInvoice.InvoiceID); if (firstInvoice != null) { Console.WriteLine(string.Format("Downloading the PDF of invoice {0}...", firstInvoice.InvoiceNumber)); byte[] invoicePdf = repository.FindById<Invoice>(firstInvoice.InvoiceID.ToString(), MimeTypes.ApplicationPdf); string invoicePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), firstInvoice.InvoiceNumber + ".pdf"); FileInfo file = new FileInfo(invoicePath); if (file.Exists) { file.Delete(); } using (FileStream fs = file.OpenWrite()) { fs.Write(invoicePdf, 0, invoicePdf.Length); } Console.WriteLine("PDF for invoice '{0}' has been saved to:", firstInvoice.InvoiceNumber); Console.WriteLine(invoicePath); // This commented-out line of code will try and start a PDF viewer to view the invoice PDF. //Process.Start(invoicePath); } // Find all invoices that were against the same contact as the first AR invoice that we've just found (http://answers.xero.com/developer/question/36911/) if (firstInvoice != null) { Console.WriteLine("Getting a list of all invoice created for {0}", firstInvoice.Contact.Name); Guid contactId = firstInvoice.Contact.ContactID; var invoicesForContact = repository.Invoices.Where(invoice => invoice.Contact.ContactID == contactId).ToList(); Console.WriteLine("There are {0} invoices raised for {1}", invoicesForContact.Count, firstInvoice.Contact.Name); foreach (var invoiceForContact in invoicesForContact) { Console.WriteLine("Invoice {0} was raised against {1} on {2} for {3}{4}", invoiceForContact.InvoiceNumber, invoiceForContact.Contact.Name, invoiceForContact.Date, invoiceForContact.Total, invoiceForContact.CurrencyCode); } } // Find the subscriber for this organisation User subscriber = repository.Users.FirstOrDefault(user => user.IsSubscriber == true); if (subscriber == null) { Console.WriteLine("There is no subscriber for this organisation. Maybe a demo organisation? Maybe this endpoint hasn't been released yet?"); } else { Console.WriteLine("The subscriber for this organisation is " + subscriber.FullName); // Create a receipt Receipt receipt = new Receipt { Contact = new Contact { Name = "Mojo Coffee" }, User = subscriber, Date = DateTime.Today.Date, LineAmountTypes = LineAmountType.Inclusive, LineItems = new LineItems { new LineItem { Description = "Flat White", Quantity = 1m, AccountCode = "429", UnitAmount = 3.8m }, new LineItem { Description = "Mocha", Quantity = 1m, AccountCode = "429", UnitAmount = 4.2m } } }; // Save the receipt to Xero receipt = repository.Create(receipt); Console.WriteLine("Receipt {0} was created for {1} for user {2}", receipt.ReceiptID, receipt.Contact.Name, receipt.User.FullName); // Upload an attachment against the newly creacted receipt FileInfo attachmentFileInfo = new FileInfo(@".\Attachments\Receipt.png"); if (!attachmentFileInfo.Exists) { Console.WriteLine("The Receipt.png file cannot be loaded from disk!" + subscriber.FullName); return; } // Upload the attachment against the receipt Console.WriteLine("Attaching file {0} to Receipt {1}...", attachmentFileInfo.Name, receipt.ReceiptID); repository.Attachments.UpdateOrCreate(receipt, attachmentFileInfo); // Fetch the attachment that was just uploaded Attachment attachment = repository.Attachments.GetAttachmentFor(receipt); if (attachment.ContentLength != attachmentFileInfo.Length) { Console.WriteLine("The uploaded attachment filesize {0} does not match the original filesize {1}", attachment.ContentLength, attachmentFileInfo.Length); } else if (attachment.Filename != attachmentFileInfo.Name) { Console.WriteLine("The uploaded attachment filename '{0}' does not match the original filename '{1}'", attachment.Filename, attachmentFileInfo.Name); } else { Console.WriteLine("Attachment succesfully uploaded!"); } } // Get a list of all expense claims Console.WriteLine("Getting a list of all submitted expense claims..."); foreach (var expenseClaim in repository.ExpenseClaims.Where(expenseClaim => expenseClaim.Status != "CURRENT")) { Console.WriteLine("Expense claim {0} for user {1} for amount {2} with status {3}", expenseClaim.ExpenseClaimID, expenseClaim.User.EmailAddress, expenseClaim.Total, expenseClaim.Status); } // Get a trial balance report (as per http://answers.xero.com/developer/question/36201/) Console.WriteLine("Running Trial Balance Report..."); Report trialBalance = repository.Reports.RunDynamicReport(new TrialBalanceReport()); if (trialBalance != null) { foreach (var reportTitle in trialBalance.ReportTitles) { Console.WriteLine("\t" + reportTitle); } foreach (var reportRow in trialBalance.Rows) { Console.WriteLine(" " + reportRow.Title); if (reportRow.Rows != null) { foreach (var subRow in reportRow.Rows) { Console.Write(" Row: " + subRow.RowType); foreach (var cell in subRow.Cells) { Console.Write(cell.Value + ", "); } Console.WriteLine(); } } } } Console.WriteLine("All done!"); }
private static void TestAlteringTrackingAndAccountForApprovedInvoiceWithPayments( Repository repository ) { return; string invoiceId = "8dc3aeda-dab1-41a3-aa9a-0d9df02ae308"; Account salesAccount = repository.Accounts.First( w => w.Code == "200" ); Account otherRevenueAccount = repository.Accounts.First( w => w.Code == "260" ); List<TrackingCategory> trackingCategories = repository.TrackingCategories.ToList( ); Invoice approvalInvoice = repository.Invoices.First( f => f.InvoiceID == new Guid( invoiceId ) ); LineItem firstLine = approvalInvoice.LineItems.First( ); Console.WriteLine( "Current account is: {0}", firstLine.AccountCode ); Console.WriteLine( "Current tracking option is: {0}", firstLine.Tracking.Any( ) ? firstLine.Tracking.First( ).Name : " - " ); firstLine.AccountCode = firstLine.AccountCode == salesAccount.Code ? otherRevenueAccount.Code : salesAccount.Code; Invoice result = repository.UpdateOrCreate( approvalInvoice ); if ( result.ValidationErrors.Any( ) ) { Console.WriteLine( "Something went wrong: {0}", result.ValidationErrors.First( ).Message ); } else { Console.WriteLine( "Updated account is: {0}", firstLine.AccountCode ); Console.WriteLine( "Updated tracking option is: {0}", firstLine.Tracking.Any( ) ? firstLine.Tracking.First( ).Name : " - " ); } }
private static void TestCreatingInvoiceAsSubmittedForApproval( Repository repository ) { // Try and create an invoice - but using incorrect data. This should hopefully be rejected by the Xero API Invoice invoiceToCreate = new Invoice { Contact = new Contact { Name = TestContactName }, Type = "ACCREC", Date = DateTime.Today, Status = "SUBMITTED", LineItems = new LineItems { new LineItem { AccountCode = "200", Description = "Blue Widget", UnitAmount = 10, Quantity = 1 } }, DueDate = DateTime.Now }; Console.WriteLine( "Creating an invoice as submitted..." ); var createdInvoice = repository.Create( invoiceToCreate ); if ( createdInvoice.ValidationStatus == ValidationStatus.ERROR ) { foreach ( var message in createdInvoice.ValidationErrors ) { Console.WriteLine( "Validation Error: " + message.Message ); } } else { // Now try to approve it. Console.WriteLine( "Approving submitted invoice" ); createdInvoice.Status = "AUTHORISED"; createdInvoice = repository.UpdateOrCreate( createdInvoice ); } }
private static void TestAlteringAwaitingApprovalInvoice( Repository repository ) { return; string invoiceId = "4e59465a-d106-4f13-a9e7-8729fb8842d5"; Invoice awaitingApprovalInvoice = repository.Invoices.First( f => f.InvoiceID == new Guid( invoiceId ) ); LineItem firstLine = awaitingApprovalInvoice.LineItems.First( ); Console.WriteLine( "Current invoice total: {0}", awaitingApprovalInvoice.Total ); awaitingApprovalInvoice.LineItems.Add( new LineItem( ) { Description = "Alter is successful!!!", AccountCode = firstLine.AccountCode, Quantity = 1, UnitAmount = 10, TaxType = firstLine.TaxType } ); Invoice result = repository.UpdateOrCreate( awaitingApprovalInvoice ); if ( result.ValidationErrors.Any( ) ) { Console.WriteLine( "Something went wrong: {0}", result.ValidationErrors.First( ).Message ); } else { Console.WriteLine( "No errors, the invoice total is now: {0}", result.Total ); } }
private static void TestAlteringApprovedInvoiceWithNoPaymentsOrAllocations( Repository repository ) { return; string invoiceId = "7d5aa7cc-3b84-45f7-872f-50d1521ad347"; Invoice approvalInvoice = repository.Invoices.First( f => f.InvoiceID == new Guid( invoiceId ) ); LineItem firstLine = approvalInvoice.LineItems.First( ); Console.WriteLine( "Current invoice total: {0}", approvalInvoice.Total ); // Add a line approvalInvoice.LineItems.Add( new LineItem( ) { Description = "Alter is successful!!!", AccountCode = firstLine.AccountCode, Quantity = 1, UnitAmount = 10, TaxType = firstLine.TaxType } ); // Update a line firstLine.Quantity = firstLine.Quantity + 1; firstLine.LineAmount = null; // nullify so recalculated Invoice result = repository.UpdateOrCreate( approvalInvoice ); if ( result.ValidationErrors.Any( ) ) { Console.WriteLine( "Something went wrong: {0}", result.ValidationErrors.First( ).Message ); } else { Console.WriteLine( "No errors, the invoice total is now: {0}", result.Total ); } }