how to add purchase order with QBO rest api v3.0 - c#

I am trying to send a PurchaseOrder created with Intuit .NET SDK v3. I found a suitable example with Invoice: how to add invoice or sales receipt quickbooks rest api v3.0
But I cannot work out what I need to do to make it working for Purchase Order. I am getting BadRequest no matter what properties do I set.
DataService commonService = new DataService(context);
QueryService<Vendor> accountQueryService = new QueryService<Vendor>(context);
Vendor customer = accountQueryService.Where(x => x.Id == "9").FirstOrDefault<Vendor>();
QueryService<Item> itemQueryService = new QueryService<Item>(context);
Item item = itemQueryService.Where(x => x.Id == "1").FirstOrDefault<Item>();
PurchaseOrder invoice = new PurchaseOrder();
invoice.VendorRef = new ReferenceType()
{
name = customer.DisplayName,
Value = customer.Id
};
/*invoice.APAccountRef = new ReferenceType()
{
type = Enum.GetName(typeof(objectNameEnumType), objectNameEnumType.Account),
name = "Account Receivable",
Value = "QB:37"
};*/
List<Line> lineList = new List<Line>();
Line line = new Line();
line.Description = "Description";
line.Amount = new Decimal(100.00);
line.AmountSpecified = true;
//line.DetailType = LineDetailTypeEnum.DescriptionOnly;
//line.DetailTypeSpecified = true;
line.DetailType = LineDetailTypeEnum.PurchaseOrderItemLineDetail;
line.DetailTypeSpecified = true;
PurchaseOrderItemLineDetail det = new PurchaseOrderItemLineDetail();
det.Qty = 10;
det.QtySpecified = true;
det.ItemRef = new ReferenceType()
{
name = item.Name,
Value = item.Id
};
line.AnyIntuitObject = det;
lineList.Add(line);
invoice.Line = lineList.ToArray();
I've tried to set account and use just description in the line without success. If I add PurchaseOrder created with the above code I am getting BadRequest error with Validation exception inside.
Can please somebody point me in the right direction here. I am probably missing some PurchaseOrder property.
I am using the August V3 SDK loaded using NuGet.
UPDATE
This is c# translation of the XML suggested by Manas Mukherjee below
DataService commonService = new DataService(context);
QueryService<Vendor> accountQueryService = new QueryService<Vendor>(context);
Vendor customer = accountQueryService.Where(x => x.Id == "9").FirstOrDefault<Vendor>();
QueryService<Item> itemQueryService = new QueryService<Item>(context);
Item item = itemQueryService.Where(x => x.Id == "1").FirstOrDefault<Item>();
PurchaseOrder invoice = new PurchaseOrder();
invoice.TxnDate = DateTime.Now;
invoice.TxnDateSpecified = true;
invoice.Memo = "For Internal usage";
invoice.GlobalTaxCalculation = GlobalTaxCalculationEnum.TaxInclusive;
invoice.GlobalTaxCalculationSpecified = true;
invoice.ReplyEmail = new EmailAddress();
invoice.ReplyEmail.Address = "testing#testing.com";
invoice.ReplyEmail.Default = false;
invoice.ReplyEmail.DefaultSpecified = true;
invoice.ReplyEmail.Tag = "Home";
invoice.ShipAddr = new PhysicalAddress();
invoice.ShipAddr.Line1 = "shippingToAddr1Sat Oct 19 09:48:52 IST 2013";
invoice.ShipAddr.Line2 = "shippingToAddr2Sat Oct 19 09:48:52 IST 2013";
invoice.ShipAddr.Line3 = "shippingToAddr3Sat Oct 19 09:48:52 IST 2013";
invoice.ShipAddr.City = "Bangalore";
invoice.ShipAddr.Country = "India";
invoice.ShipAddr.CountrySubDivisionCode = "KA";
invoice.ShipAddr.PostalCode = "560045";
invoice.POEmail = new EmailAddress();
invoice.POEmail.Address = "testing#testing.com";
invoice.POEmail.Default = true;
invoice.POEmail.DefaultSpecified = true;
invoice.POEmail.Tag = "Business";
invoice.VendorRef = new ReferenceType()
{
name = customer.DisplayName,
Value = customer.Id
};
invoice.TotalAmt = new Decimal(100.00);
invoice.TotalAmtSpecified = true;
invoice.APAccountRef = new ReferenceType()
{
//type = Enum.GetName(typeof(objectNameEnumType), objectNameEnumType.Account),
name = "Accounts Payable (A/P)",
Value = "32"
};
List<Line> lineList = new List<Line>();
Line line = new Line();
line.Amount = new Decimal(100.00);
line.AmountSpecified = true;
line.DetailType = LineDetailTypeEnum.AccountBasedExpenseLineDetail;
line.DetailTypeSpecified = true;
AccountBasedExpenseLineDetail det = new AccountBasedExpenseLineDetail();
det.AccountRef = new ReferenceType()
{
name = "Accounts Payable (A/P)",
Value = "32"
};
line.AnyIntuitObject = det;
/*PurchaseOrderItemLineDetail det = new PurchaseOrderItemLineDetail();
det.Qty = 10;
det.QtySpecified = true;
det.ItemRef = new ReferenceType()
{
name = item.Name,
Value = item.Id
};
line.AnyIntuitObject = det;*/
lineList.Add(line);
invoice.Line = lineList.ToArray();
return invoice;
Unfortunately I am still getting BadRequest error.
UPDATE 2
After some more testing I found out that it gives error because of APAccountRef property. It's OK without setting up this property.
The other issue came when I tried to use PurchaseOrderItemLineDetail in lines. Not sure if this type is correct (based on the name it looks like one) but using this details type is causing BadRequest error. Using ItemBasedExpenseLineDetail is a workaround.
I will set Manas answer as correct since it gave me a direction to investigate further. But big thanks to Nimisha Shrivastava for the help with logging.

Here is one working PurchaseOrder create request XML.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PurchaseOrder domain="QBO" xmlns="http://schema.intuit.com/finance/v3">
<TxnDate>2013-10-19</TxnDate>
<Line>
<Amount>3.00</Amount>
<DetailType>AccountBasedExpenseLineDetail</DetailType>
<AccountBasedExpenseLineDetail>
<AccountRef name="Accounts Payable (A/P)">32</AccountRef>
</AccountBasedExpenseLineDetail>
</Line>
<VendorRef name="TestDataVendor926e8Sample1">1386</VendorRef>
<TotalAmt>3.00</TotalAmt>
<ReplyEmail>
<Address>testing#testing.com</Address>
<Default>false</Default>
<Tag>Home</Tag>
</ReplyEmail>
<Memo>For Internal usage</Memo>
<GlobalTaxCalculation>TaxInclusive</GlobalTaxCalculation>
<ShipAddr>
<Line1>shippingToAddr1Sat Oct 19 09:48:52 IST 2013</Line1>
<Line2>shippingToAddr2Sat Oct 19 09:48:52 IST 2013</Line2>
<Line3>shippingToAddr3Sat Oct 19 09:48:52 IST 2013</Line3>
<City>Bangalore</City>
<Country>India</Country>
<CountrySubDivisionCode>KA</CountrySubDivisionCode>
<PostalCode>560045</PostalCode>
</ShipAddr>
<POEmail>
<Address>test#testing.com</Address>
<Default>true</Default>
<Tag>Business</Tag>
</POEmail>
</PurchaseOrder>
I've used java devkit(PFB code). Hope you'll find similar properties in .net devkit.
public PurchaseOrder purchaseOrderWithAllProperties() throws FMSException, ParseException {
PurchaseOrder purchaseOrder = new PurchaseOrder();
purchaseOrder.setVendorRef(this.vendorRef);
purchaseOrder.setMemo("For Internal usage");
Line line1 = new Line();
line1.setAmount(new BigDecimal("3.00"));
line1.setDetailType(LineDetailTypeEnum.ACCOUNT_BASED_EXPENSE_LINE_DETAIL);
AccountBasedExpenseLineDetail detail = new AccountBasedExpenseLineDetail();
ReferenceType expenseAccountRef = this.accountRef;
detail.setAccountRef(expenseAccountRef);
line1.setAccountBasedExpenseLineDetail(detail);
List<Line> lines1 = new ArrayList<Line>();
lines1.add(line1);
purchaseOrder.setLine(lines1);
EmailAddress emailAddr = new EmailAddress();
emailAddr.setAddress("test#testing.com");
emailAddr.setDefault(true);
emailAddr.setTag("Business");
purchaseOrder.setPOEmail(emailAddr);
//purchaseOrder.setDueDate(DateUtils.getDateWithNextDays(45));
purchaseOrder.setDomain("QBO");
//purchaseOrder.setExchangeRate(new BigDecimal("20.00"));
purchaseOrder.setGlobalTaxCalculation(GlobalTaxCalculationEnum.TAX_INCLUSIVE);
EmailAddress replyEmail = new EmailAddress();
replyEmail.setAddress("testing#testing.com");
replyEmail.setDefault(false);
replyEmail.setTag("Home");
purchaseOrder.setReplyEmail(replyEmail);
PhysicalAddress shipAddr = new PhysicalAddress();
shipAddr.setLine1("shippingToAddr1" + DateUtils.getCurrentDateTime());
shipAddr.setLine2("shippingToAddr2" + DateUtils.getCurrentDateTime());
shipAddr.setLine3("shippingToAddr3" + DateUtils.getCurrentDateTime());
shipAddr.setCity("Bangalore");
shipAddr.setCountry("India");
shipAddr.setCountrySubDivisionCode("KA");
shipAddr.setPostalCode("560045");
purchaseOrder.setShipAddr(shipAddr);
//purchaseOrder.setStatus(EntityStatusEnum.IN_TRANSIT);
purchaseOrder.setTotalAmt(new BigDecimal("3.00"));
purchaseOrder.setTxnDate(DateUtils.getCurrentDateTime());
return purchaseOrder;
}
Thanks

Try this one adding purchase order.
PurchaseOrder po = new PurchaseOrder();
po.ReplyEmail = new EmailAddress();
po.ReplyEmail.Address = "kalpana.kodavaluru#gmail.com";
po.ReplyEmail.Default = false;
po.ReplyEmail.DefaultSpecified = true;
po.ReplyEmail.Tag = "Home";
po.ShipAddr = new PhysicalAddress();
po.ShipAddr.Line1 = "shippingToAddr1Sat Oct 19 09:48:52 IST 2013";
po.ShipAddr.Line2 = "shippingToAddr2Sat Oct 19 09:48:52 IST 2013";
po.ShipAddr.Line3 = "shippingToAddr3Sat Oct 19 09:48:52 IST 2013";
po.ShipAddr.City = "Bangalore";
po.ShipAddr.Country = "India";
po.ShipAddr.CountrySubDivisionCode = "KA";
po.ShipAddr.PostalCode = "560045";
po.POEmail = new EmailAddress();
po.POEmail.Address = "testing#testing.com";
po.POEmail.Default = true;
po.POEmail.DefaultSpecified = true;
po.POEmail.Tag = "Business";
po.VendorRef = new ReferenceType()
{
name = supplier.DisplayName,
Value = supplier.Id
};
po.TotalAmt = new Decimal(100.00);
po.TotalAmtSpecified = true;
List<Line> lineList1 = new List<Line>();
Line line1 = new Line();
line1.Id = "1";
line1.Amount = new Decimal(100.00);
line1.AmountSpecified = true;
line1.DetailType = LineDetailTypeEnum.ItemBasedExpenseLineDetail;
line1.DetailTypeSpecified = true;
ItemBasedExpenseLineDetail det = new ItemBasedExpenseLineDetail();
det.ItemRef = new ReferenceType()
{
name = item.Name,
Value = item.Id
};
det.Qty = new decimal(1);
det.QtySpecified = true;
det.ItemElementName = ItemChoiceType.UnitPrice;
det.AnyIntuitObject = new decimal(100);
det.BillableStatus = new BillableStatusEnum();
line1.AnyIntuitObject = det;
lineList1.Add(line1);
po.Line = lineList1.ToArray();
try
{
var podata=commonService.Add(po);
}
catch (Exception ex)
{
throw ex;
}

Related

TimeActivity with .NET API v3 SDK

I can't get a time activity to save with the latest version of the .NET SDK and Quickbooks Online. I think it's the Employee Reference, but I just can't sort it out. Does the API even work right?
DataService commonService = new DataService(serviceContext);
string displayName = "Test Customer";
displayName = displayName.Replace("'", "\\'"); //Escape special characters
QueryService<Customer> customerQueryServiceXX = new QueryService<Customer>(serviceContext);
Customer resultCustomer = customerQueryServiceXX.Where(m => m.DisplayName == displayName).FirstOrDefault();
string employeeName = "First Last";
employeeName = employeeName.Replace("'", "\\'"); //Escape special characters
QueryService<Employee> customerQueryServiceEE = new QueryService<Employee>(serviceContext);
Employee resultEmployee = customerQueryServiceEE.Where(m => m.DisplayName == employeeName).FirstOrDefault();
string sfasdfasdfasdf = resultEmployee.FamilyName;
TimeActivity timeActivity = new TimeActivity();
timeActivity.BillableStatus = BillableStatusEnum.Billable;
timeActivity.BillableStatusSpecified = true;
timeActivity.Hours = 8;
timeActivity.Minutes = 0;
timeActivity.TxnDate = DateTime.Now.Date;
timeActivity.TxnDateSpecified = true;
//timeActivity.HourlyRate = new decimal(200);
//timeActivity.HourlyRateSpecified = true;
timeActivity.NameOf = TimeActivityTypeEnum.Employee;
timeActivity.NameOfSpecified = true;
timeActivity.CustomerRef = new ReferenceType()
{
name = resultCustomer.DisplayName,
Value = resultCustomer.Id
};
timeActivity.ItemRef = new ReferenceType()
{
name = resultEmployee.DisplayName,
Value = resultEmployee.Id,
};
timeActivity.Description = "Did something";
TimeActivity timeActivityResult = commonService.Add(timeActivity);
ItemRef is for providing service Items. Please use timeActivity.AnyIntuitObject for specifying vendor or employee
timeActivity.NameOf = TimeActivityTypeEnum.Employee;
timeActivity.NameOfSpecified = true;
timeActivity.ItemElementName = ItemChoiceType5.EmployeeRef;
timeActivity.AnyIntuitObject= new ReferenceType()
{
name = resultEmployee.DisplayName,
Value = resultEmployee.Id,
};

How to insert multiple items in Quickbook Invoice

I need to insert a new invoice for a particular customer , I can able to insert , but i don't have any idea about how to insert multiple items in invoice. How to use the property Items and ItemsElementName to insert multiple items.
If my question is unclear please let me know. I have attached the snapshot and code for reference.
Code:
protected void btnsendInvoiceDetails_Click(object sender, EventArgs e)
{
string accessToken = "lvprdRM1HLr6o11Bnip2fGizlXWbFfADnS1Btvm2L4VPOTRI";
string appToken = "297db54bb5526b494adb86fb2a41063192cd";
string accessTokenSecret = "JfSTrprW83JTXrSVHD3uf7th23gP0SOzBQcn4Nrt";
string consumerKey = "qyprdKLN5YHpCPSlWQZTiKVc28dywR";
string consumerSecret = "JPMNB37YnCPGU9m9vuXkF2M71lbDb7blhcLB7HeF";
string companyID = "813162085";
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
ServiceContext context = new ServiceContext(oauthValidator,appToken,companyID, IntuitServicesType.QBO);
DataServices service = new DataServices(context);
InvoiceHeader a = new InvoiceHeader();
a.CustomerName = "Antivirus Norton Security";
a.CustomerId = new IdType { idDomain = idDomainEnum.QBO, Value = "6" };
a.TotalAmt = 157.00m;
a.SubTotalAmt = 37.00m;
a.ShipMethodName = "Gmail";
a.ShipMethodId = new IdType { idDomain = idDomainEnum.QBO, Value = "41" };
a.DocNumber = "1040";
a.DueDateSpecified = true;
// a.Item = 10.00m;
//a.ItemElementName = ItemChoiceType2.DiscountAmt;
DateTime dt = Convert.ToDateTime("08/07/2013");
a.DueDate = dt;
InvoiceLine mnm = new InvoiceLine();
mnm.Desc = "Antivirus Norton Security The Best Security ";
mnm.Id = new IdType { idDomain = idDomainEnum.QBO, Value = "25" };
mnm.Amount = 65.00m;
mnm.AmountSpecified = true;
// mnm.Items = "Europe";
//mnm.ItemsElementName = "Zebronic";
InvoiceLine[] invline = new InvoiceLine[] { mnm };
var invoices = new Intuit.Ipp.Data.Qbo.Invoice();
invoices.Header = a;
invoices.Line = invline;
var addedInvoice = service.Add(invoices);
var qboInvoices = service.FindAll(invoices, 1,10);
foreach (var qboinv in qboInvoices)
{
string id = Convert.ToString(qboinv.Id.Value);
}
GridView1.DataSource = invoices;
GridView1.DataBind();
}
Image:
Try this:
InvoiceLine i = new InvoiceLine();
i.ItemsElementName = new ItemsChoiceType2[1];
i.ItemsElementName[0] = ItemsChoiceType2.ItemId;
i.Items = new Intuit.Ipp.Data.Qbd.IdType[1];
i.Items[0] = new Intuit.Ipp.Data.Qbd.IdType() { idDomain = Intuit.Ipp.Data.Qbd.idDomainEnum.QBO, Value = "6" };

Using eBay SDK API: internationalShippingOptions.ShipToLocation.Add("Worldwide"); causes:"Object reference not set to an instance of an object"

My goal here so to make the listing say "Free International Shipping". Trying to set up international options and it said I need to set ShipToLocation I tried the line below:
internationalShippingOptions.ShipToLocation.Add("Worldwide");
But when the program hits it I get this error:
"Object reference not set to an instance of an object"
If you would like to see the full method it is:
static ShippingDetailsType BuildShippingDetails()
{
ShippingDetailsType sd = new ShippingDetailsType();
sd.ApplyShippingDiscount = false;
sd.ShippingType = ShippingTypeCodeType.Flat;
AmountType amount = new AmountType();
amount.Value = 0;
amount.currencyID = CurrencyCodeType.USD;
ShippingServiceOptionsTypeCollection shippingOptions = new ShippingServiceOptionsTypeCollection();
ShippingServiceOptionsType domesticShippingOptions = new ShippingServiceOptionsType();
domesticShippingOptions.ShippingService = ShippingServiceCodeType.EconomyShippingFromOutsideUS.ToString();
domesticShippingOptions.FreeShipping = true;
domesticShippingOptions.ShippingServiceCost = amount;
domesticShippingOptions.ShippingServicePriority = 1;
shippingOptions.Add(domesticShippingOptions);
ShippingServiceOptionsType internationalShippingOptions = new ShippingServiceOptionsType();
InternationalShippingServiceOptionsType internationalShippingOptions = new InternationalShippingServiceOptionsType();
internationalShippingOptions.ShippingService = ShippingServiceCodeType.StandardInternational.ToString();
internationalShippingOptions.ShipToLocation.Add("Worldwide");
internationalShippingOptions.FreeShipping = true;
sd.InternationalShippingServiceOption = new InternationalShippingServiceOptionsTypeCollection(new InternationalShippingServiceOptionsType[] { internationalShippingOptions });
sd.ShippingServiceOptions = shippingOptions;
return sd;
}
Here is the code to make it say "Free Standard Intl Shipping". At first in the sandbox it says "Free Standard Shipping" but if you change the shipping destination in the sandbox it will say "Free Standard Intl Shipping".
static ShippingDetailsType BuildShippingDetails()
{
// Shipping details
ShippingDetailsType sd = new ShippingDetailsType();
sd.ApplyShippingDiscount = true;
sd.PaymentInstructions = "eBay .Net SDK test instruction.";
sd.ShippingRateType = ShippingRateTypeCodeType.StandardList;
// Shipping type and shipping service options
//adding international shipping
InternationalShippingServiceOptionsType internationalShipping1 = new InternationalShippingServiceOptionsType();
internationalShipping1.ShippingService = ShippingServiceCodeType.StandardInternational.ToString();
internationalShipping1.ShippingServiceCost = new AmountType { Value = 0, currencyID = CurrencyCodeType.USD };
internationalShipping1.ShippingServicePriority = 1;
internationalShipping1.ShipToLocation = new StringCollection(new[] { "Worldwide" });
sd.ShippingServiceUsed = ShippingServiceCodeType.StandardInternational.ToString();
sd.InternationalShippingServiceOption = new InternationalShippingServiceOptionsTypeCollection(new[] { internationalShipping1 });
//adding domestic shipping
ShippingServiceOptionsType domesticShipping1 = new ShippingServiceOptionsType();
domesticShipping1.ShippingService = ShippingServiceCodeType.ShippingMethodStandard.ToString();
domesticShipping1.ShippingServiceCost = new AmountType { Value = 0, currencyID = CurrencyCodeType.USD };
domesticShipping1.ShippingInsuranceCost = new AmountType { Value = 0, currencyID = CurrencyCodeType.USD };
domesticShipping1.ShippingServicePriority = 4;
domesticShipping1.LocalPickup = true;
domesticShipping1.FreeShipping = true;
sd.ShippingServiceOptions = new ShippingServiceOptionsTypeCollection(new[] { domesticShipping1 });
sd.ShippingType = ShippingTypeCodeType.Flat;
return sd;
To call the method:
item.ShippingDetails = BuildShippingDetails();

UPS API - LabelLinksIndicator - Object Reference not set to an instance of an object

Below is some code for generating a UPS shipping label. It is based on the .net sample provided in the UPS developer kit. My problem is with the line highlighted in bold below. It throws and error as follows "System.NullReferenceException: Object reference not set to an instance of an object.".
What I know is this LabelLinksIndicator is required if you want the UPS API to return a link to a label. Otherwise it returns details on the shipment but no label. The relevant section of the UPS documentation is at the bottom of my question.
What do I need to do to overcome this error? It is not clear to me from the documentation what value I should be passing for LabelLinksIndicator. I've tried passing a 1, true and and an empty string. Same error in every case. The error message seems to indicate that there is an object I need to instantiate that I am not currently. However, I can't figure out what to instantiate. The available information on the web and on UPS.com is unfortunately sparse.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Foo.Web.UPSWebReference;
namespace Foo.Web.Auth
{
public partial class UPS : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
try
{
ShipService shpSvc = new ShipService();
ShipmentRequest shipmentRequest = new ShipmentRequest();
UPSSecurity upss = new UPSSecurity();
UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
upssSvcAccessToken.AccessLicenseNumber = "foo";
upss.ServiceAccessToken = upssSvcAccessToken;
UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
upssUsrNameToken.Username = "foo";
upssUsrNameToken.Password = "foo";
upss.UsernameToken = upssUsrNameToken;
shpSvc.UPSSecurityValue = upss;
RequestType request = new RequestType();
String[] requestOption = { "nonvalidate" };
request.RequestOption = requestOption;
shipmentRequest.Request = request;
ShipmentType shipment = new ShipmentType();
shipment.Description = "Ship webservice example";
ReturnServiceType rtn = new ReturnServiceType();
rtn.Code = "8";
rtn.Description = "Description";
ShipperType shipper = new ShipperType();
shipper.ShipperNumber = "foo";
PaymentInfoType paymentInfo = new PaymentInfoType();
ShipmentChargeType shpmentCharge = new ShipmentChargeType();
BillShipperType billShipper = new BillShipperType();
billShipper.AccountNumber = "foo";
shpmentCharge.BillShipper = billShipper;
shpmentCharge.Type = "01";
ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
paymentInfo.ShipmentCharge = shpmentChargeArray;
shipment.PaymentInformation = paymentInfo;
foo.Web.UPSWebReference.ShipAddressType shipperAddress = new foo.Web.UPSWebReference.ShipAddressType();
String[] addressLine = { "301 166th Street" };
shipperAddress.AddressLine = addressLine;
shipperAddress.City = "Jersey City";
shipperAddress.PostalCode = "07310";
shipperAddress.StateProvinceCode = "NJ";
shipperAddress.CountryCode = "US";
shipperAddress.AddressLine = addressLine;
shipper.Address = shipperAddress;
shipper.Name = "ABC Associates";
shipper.AttentionName = "ABC Associates";
ShipPhoneType shipperPhone = new ShipPhoneType();
shipperPhone.Number = "1234567890";
shipper.Phone = shipperPhone;
shipment.Shipper = shipper;
ShipFromType shipFrom = new ShipFromType();
foo.Web.UPSWebReference.ShipAddressType shipFromAddress = new foo.Web.UPSWebReference.ShipAddressType();
String[] shipFromAddressLine = { "100 82nd Street" };
shipFromAddress.AddressLine = addressLine;
shipFromAddress.City = "New York";
shipFromAddress.PostalCode = "10024";
shipFromAddress.StateProvinceCode = "NY";
shipFromAddress.CountryCode = "US";
shipFrom.Address = shipFromAddress;
shipFrom.AttentionName = "Mr.ABC";
shipFrom.Name = "ABC Associates";
shipment.ShipFrom = shipFrom;
ShipToType shipTo = new ShipToType();
ShipToAddressType shipToAddress = new ShipToAddressType();
String[] addressLine1 = { "Some Street" };
shipToAddress.AddressLine = addressLine1;
shipToAddress.City = "Roswell";
shipToAddress.PostalCode = "30076";
shipToAddress.StateProvinceCode = "GA";
shipToAddress.CountryCode = "US";
shipTo.Address = shipToAddress;
shipTo.Address.ResidentialAddressIndicator = "1"; //dan
shipTo.AttentionName = "DEF";
shipTo.Name = "DEF Associates";
ShipPhoneType shipToPhone = new ShipPhoneType();
shipToPhone.Number = "1234567890";
shipTo.Phone = shipToPhone;
shipment.ShipTo = shipTo;
ServiceType service = new ServiceType();
service.Code = "03";
service.Description = "Ground";
shipment.Service = service;
PackageType package = new PackageType();
package.Description = "Deliver to Warehouse";
PackageWeightType packageWeight = new PackageWeightType();
packageWeight.Weight = "10";
ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
uom.Code = "LBS";
packageWeight.UnitOfMeasurement = uom;
package.PackageWeight = packageWeight;
PackagingType packType = new PackagingType();
packType.Code = "02";
package.Packaging = packType;
PackageType[] pkgArray = { package };
shipment.Package = pkgArray;
LabelSpecificationType labelSpec = new LabelSpecificationType();
LabelImageFormatType labelImageFormat = new LabelImageFormatType();
labelImageFormat.Code = "GIF";
labelSpec.LabelImageFormat = labelImageFormat;
string userAgent = Request.UserAgent;
labelSpec.HTTPUserAgent = userAgent;
shipmentRequest.LabelSpecification = labelSpec;
**shipmentRequest.Shipment.ShipmentServiceOptions.LabelDelivery.LabelLinksIndicator = "1";**
shipmentRequest.Shipment = shipment;
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);
Response.Redirect(shipmentResponse.ShipmentResults.LabelURL.ToString());
I figured out what the problem was. I needed first to new-up an instance of
ShipmentTypeShipmentServiceOptions shipServOpt = new ShipmentTypeServiceOptions();
and
LabelDeliveryType labelDel = new LabelDeliveryType();
Then set the LabelLinksIndicator element
labeldel.LabelLinksIndicator = "";
Then assign the options to my shipment instance
shipment.ShipmentServiceOptions = shipServOpt;
Note, ShipmentServiceOptionsType is NOT the same as ShipmentTypeServiceOptions. This tripped me up for a while.
Dear UPS, if you are reading this please consider improving upon your documentation and providing a more complete set of code examples.
shipmentRequest.Shipment appears to be null, since you aren't assigning anything to it until the next line. So, you can't do shipmentRequest.Shipment.ANYTHING. Switch them around, so that you have
shipmentRequest.Shipment = shipment;
shipmentRequest.Shipment.ShipmentServiceOptions.LabelDelivery.LabelLinksIndicator = "1";
The element needs to get passed as <LabelLinksIndicator/> in the XML. In your sample you'd be sending it as <LabelLinksIndicator>1</LabelLinksIndicator> which is invalid.

EWS - How to search for items [message] between dates?

I am trying to search for message items between two dates from the inbox folder.
I use the following restrictionType but it throws this error:
firmt.RootFolder = null
What am I doing wrong?
There is some messages between the mentionned dates ;-)
Thanks for your suggestions.
using (ExchangeServiceBinding esb = new ExchangeServiceBinding())
{
esb.Url = ConfigurationManager.AppSettings["ExchangeWebServicesURL"].ToString();
esb.RequestServerVersionValue = new RequestServerVersion();
esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1;
esb.PreAuthenticate = true;
esb.Credentials = new NetworkCredential(email, password);
FindItemType findItemRequest = new FindItemType();
// paging
IndexedPageViewType ipvt = new IndexedPageViewType();
ipvt.BasePoint = IndexBasePointType.Beginning;
ipvt.MaxEntriesReturned = nombreMessage;
ipvt.MaxEntriesReturnedSpecified = true;
ipvt.Offset = offset;
findItemRequest.Item = ipvt;
// filter by dates
AndType andType = new AndType();
List<SearchExpressionType> searchExps = new List<SearchExpressionType>();
RestrictionType restriction = new RestrictionType();
PathToUnindexedFieldType pteft = new PathToUnindexedFieldType
{
FieldURI = UnindexedFieldURIType.itemDateTimeSent
};
IsGreaterThanOrEqualToType IsGreaterThanOrEqualTo = new IsGreaterThanOrEqualToType
{
Item = pteft,
FieldURIOrConstant = new FieldURIOrConstantType
{
Item = new ConstantValueType
{
Value = DateTime.Today.AddDays(-6d).ToString()
}
}
};
searchExps.Add(IsGreaterThanOrEqualTo);
IsLessThanOrEqualToType IsLessThanOrEqualTo = new IsLessThanOrEqualToType
{
Item = pteft,
FieldURIOrConstant = new FieldURIOrConstantType
{
Item = new ConstantValueType
{
Value = DateTime.Today.AddDays(1d).ToString()
}
}
};
searchExps.Add(IsLessThanOrEqualTo);
andType.Items = searchExps.ToArray();
restriction.Item = andType;
findItemRequest.Restriction = restriction;
//// Define the sort order of items.
FieldOrderType[] fieldsOrder = new FieldOrderType[1];
fieldsOrder[0] = new FieldOrderType();
PathToUnindexedFieldType dateOrder = new PathToUnindexedFieldType
{
FieldURI = UnindexedFieldURIType.itemDateTimeReceived
};
fieldsOrder[0].Item = dateOrder;
fieldsOrder[0].Order = SortDirectionType.Descending;
findItemRequest.SortOrder = fieldsOrder;
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;
// define which item properties are returned in the response
findItemRequest.ItemShape = new ItemResponseShapeType
{
BaseShape = DefaultShapeNamesType.IdOnly
};
// identify which folder to search
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType { Id = DistinguishedFolderIdNameType.inbox };
// add folders to request
findItemRequest.ParentFolderIds = folderIDArray;
// find the messages
FindItemResponseType findItemResponse = esb.FindItem(findItemRequest);
//-------------
ArrayOfResponseMessagesType responseMessages = findItemResponse.ResponseMessages;
ResponseMessageType responseMessage = responseMessages.Items[0];
if (responseMessage is FindItemResponseMessageType)
{
FindItemResponseMessageType firmt = (responseMessage as FindItemResponseMessageType);
*******FindItemParentType fipt = firmt.RootFolder;********
object obj = fipt.Item;
// FindItem contains an array of items.
ArrayOfRealItemsType realitems = (obj as ArrayOfRealItemsType);
ItemType[] items = realitems.Items;
// if no messages were found, then return null -- we're done
if (items == null || items.Count() <= 0)
return null;
// FindItem never gets "all" the properties, so now that we've found them all, we need to get them all.
BaseItemIdType[] itemIds = new BaseItemIdType[items.Count()];
for (int i = 0; i < items.Count(); i++)
itemIds[i] = items[i].ItemId;
GetItemType getItemType = new GetItemType
{
ItemIds = itemIds,
ItemShape = new ItemResponseShapeType
{
BaseShape = DefaultShapeNamesType.AllProperties,
BodyType = BodyTypeResponseType.Text,
BodyTypeSpecified = true,
AdditionalProperties = new BasePathToElementType[] {
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.itemDateTimeSent },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageFrom },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageIsRead },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageSender },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageToRecipients },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageCcRecipients },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageBccRecipients }
}
}
};
GetItemResponseType getItemResponse = esb.GetItem(getItemType);
messages = ReadItems(getItemResponse, items.Count());
}
I found the answer on my own after a long search about date format.
The restrictions has to be defined as this:
// greater or equal to
string dateStart = DateTime.Today.add(-6d);
string dateEnd = DateTime.Today.Add(1d);
PathToUnindexedFieldType dateSentPath = new PathToUnindexedFieldType();
dateSentPath.FieldURI = UnindexedFieldURIType.itemDateTimeSent;
IsGreaterThanOrEqualToType IsGreaterThanOrEqual = new IsGreaterThanOrEqualToType();
IsGreaterThanOrEqual.Item = dateSentPath;
FieldURIOrConstantType dateConstant = new FieldURIOrConstantType();
ConstantValueType dateConstantValue = new ConstantValueType();
dateConstantValue.Value = string.Format("{0}-{1}-{2}T00:00:00Z", dateStart.Year.ToString(), dateStart.Month.ToString(), dateStart.Day.ToString());
dateConstant.Item = dateConstantValue;
IsGreaterThanOrEqual.FieldURIOrConstant = dateConstant;
// less than or equal to
PathToUnindexedFieldType dateSentPath1 = new PathToUnindexedFieldType();
dateSentPath1.FieldURI = UnindexedFieldURIType.itemDateTimeSent;
IsLessThanOrEqualToType lessThanOrEqualTo = new IsLessThanOrEqualToType();
lessThanOrEqualTo.Item = dateSentPath1;
FieldURIOrConstantType dateConstant1 = new FieldURIOrConstantType();
ConstantValueType dateConstantValue1 = new ConstantValueType();
dateConstantValue1.Value = string.Format("{0}-{1}-{2}T00:00:00Z", dateEnd.Year.ToString(), dateEnd.Month.ToString(), dateEnd.Day.ToString());
dateConstant1.Item = dateConstantValue1;
lessThanOrEqualTo.FieldURIOrConstant = dateConstant1;
RestrictionType restriction = new RestrictionType();
AndType andType = new AndType();
andType.Items = new SearchExpressionType[] { lessThanOrEqualTo, IsGreaterThanOrEqual };
restriction.Item = andType;
findItemRequest.Restriction = restriction;
Hope this help someone some day ;-)
In case anyone stumbles upon this in the future, EWS has gotten even more strict about date formatting. The accepted answer formatting works for 2 digit months, but it does not for single digit months.
The formatting that works in all cases is:
DateTime.Today.AddDays(15).ToString("yyyy-MM-ddThh:mm:ssZ")
The restriction also works using the "Sortable date/time pattern".
Datetime.Now.ToString("s")

Categories

Resources