I want to calculate the formula of a cell and retrieve the calculated value. But it gives #NAME? as the cell value when cell.Calculate() is executed.
var package = new ExcelPackage();
var ws = package.Workbook.Worksheets.Add("Test");
ExcelRange cellTest = ws.Cells[1, 1];
cellTest.Formula = "TRIM( Hello World )";
cellTest.Calculate();
var cellCalculatedValue = cellTest.Value;
Here the cellTest.Value = #NAME?
Remember the Epplus doesnt actually have access to the excel engine, it just generates raw XML files that excel interprets when the file is first opened.
So for Formula, the documentation does say you can use Calculate() to get a value like you could in Excel. But what it doesnt tell you is that it does not support all excel built in functions. And understand that the functions in Epplus/C# are NOT the exact same as what will be ran in Excel. They are simply Epplus's interpretation/copies of what excel has.
If you look at https://github.com/JanKallman/EPPlus/blob/master/EPPlus/FormulaParsing/Excel/Functions/BuiltInFunctions.cs:
namespace OfficeOpenXml.FormulaParsing.Excel.Functions
{
public class BuiltInFunctions : FunctionsModule
{
public BuiltInFunctions()
{
// Text
Functions["len"] = new Len();
Functions["lower"] = new Lower();
Functions["upper"] = new Upper();
Functions["left"] = new Left();
Functions["right"] = new Right();
Functions["mid"] = new Mid();
Functions["replace"] = new Replace();
Functions["rept"] = new Rept();
Functions["substitute"] = new Substitute();
Functions["concatenate"] = new Concatenate();
Functions["char"] = new CharFunction();
Functions["exact"] = new Exact();
Functions["find"] = new Find();
Functions["fixed"] = new Fixed();
Functions["proper"] = new Proper();
Functions["search"] = new Search();
Functions["text"] = new Text.Text();
Functions["t"] = new T();
Functions["hyperlink"] = new Hyperlink();
Functions["value"] = new Value();
// Numbers
Functions["int"] = new CInt();
// Math
Functions["abs"] = new Abs();
Functions["asin"] = new Asin();
Functions["asinh"] = new Asinh();
Functions["cos"] = new Cos();
Functions["cosh"] = new Cosh();
Functions["power"] = new Power();
Functions["sign"] = new Sign();
Functions["sqrt"] = new Sqrt();
Functions["sqrtpi"] = new SqrtPi();
Functions["pi"] = new Pi();
Functions["product"] = new Product();
Functions["ceiling"] = new Ceiling();
Functions["count"] = new Count();
Functions["counta"] = new CountA();
Functions["countblank"] = new CountBlank();
Functions["countif"] = new CountIf();
Functions["countifs"] = new CountIfs();
Functions["fact"] = new Fact();
Functions["floor"] = new Floor();
Functions["sin"] = new Sin();
Functions["sinh"] = new Sinh();
Functions["sum"] = new Sum();
Functions["sumif"] = new SumIf();
Functions["sumifs"] = new SumIfs();
Functions["sumproduct"] = new SumProduct();
Functions["sumsq"] = new Sumsq();
Functions["stdev"] = new Stdev();
Functions["stdevp"] = new StdevP();
Functions["stdev.s"] = new Stdev();
Functions["stdev.p"] = new StdevP();
Functions["subtotal"] = new Subtotal();
Functions["exp"] = new Exp();
Functions["log"] = new Log();
Functions["log10"] = new Log10();
Functions["ln"] = new Ln();
Functions["max"] = new Max();
Functions["maxa"] = new Maxa();
Functions["median"] = new Median();
Functions["min"] = new Min();
Functions["mina"] = new Mina();
Functions["mod"] = new Mod();
Functions["average"] = new Average();
Functions["averagea"] = new AverageA();
Functions["averageif"] = new AverageIf();
Functions["averageifs"] = new AverageIfs();
Functions["round"] = new Round();
Functions["rounddown"] = new Rounddown();
Functions["roundup"] = new Roundup();
Functions["rand"] = new Rand();
Functions["randbetween"] = new RandBetween();
Functions["rank"] = new Rank();
Functions["rank.eq"] = new Rank();
Functions["rank.avg"] = new Rank(true);
Functions["quotient"] = new Quotient();
Functions["trunc"] = new Trunc();
Functions["tan"] = new Tan();
Functions["tanh"] = new Tanh();
Functions["atan"] = new Atan();
Functions["atan2"] = new Atan2();
Functions["atanh"] = new Atanh();
Functions["acos"] = new Acos();
Functions["acosh"] = new Acosh();
Functions["var"] = new Var();
Functions["varp"] = new VarP();
Functions["large"] = new Large();
Functions["small"] = new Small();
Functions["degrees"] = new Degrees();
// Information
Functions["isblank"] = new IsBlank();
Functions["isnumber"] = new IsNumber();
Functions["istext"] = new IsText();
Functions["isnontext"] = new IsNonText();
Functions["iserror"] = new IsError();
Functions["iserr"] = new IsErr();
Functions["error.type"] = new ErrorType();
Functions["iseven"] = new IsEven();
Functions["isodd"] = new IsOdd();
Functions["islogical"] = new IsLogical();
Functions["isna"] = new IsNa();
Functions["na"] = new Na();
Functions["n"] = new N();
// Logical
Functions["if"] = new If();
Functions["iferror"] = new IfError();
Functions["ifna"] = new IfNa();
Functions["not"] = new Not();
Functions["and"] = new And();
Functions["or"] = new Or();
Functions["true"] = new True();
Functions["false"] = new False();
// Reference and lookup
Functions["address"] = new Address();
Functions["hlookup"] = new HLookup();
Functions["vlookup"] = new VLookup();
Functions["lookup"] = new Lookup();
Functions["match"] = new Match();
Functions["row"] = new Row();
Functions["rows"] = new Rows();
Functions["column"] = new Column();
Functions["columns"] = new Columns();
Functions["choose"] = new Choose();
Functions["index"] = new Index();
Functions["indirect"] = new Indirect();
Functions["offset"] = new Offset();
// Date
Functions["date"] = new Date();
Functions["today"] = new Today();
Functions["now"] = new Now();
Functions["day"] = new Day();
Functions["month"] = new Month();
Functions["year"] = new Year();
Functions["time"] = new Time();
Functions["hour"] = new Hour();
Functions["minute"] = new Minute();
Functions["second"] = new Second();
Functions["weeknum"] = new Weeknum();
Functions["weekday"] = new Weekday();
Functions["days360"] = new Days360();
Functions["yearfrac"] = new Yearfrac();
Functions["edate"] = new Edate();
Functions["eomonth"] = new Eomonth();
Functions["isoweeknum"] = new IsoWeekNum();
Functions["workday"] = new Workday();
Functions["networkdays"] = new Networkdays();
Functions["networkdays.intl"] = new NetworkdaysIntl();
Functions["datevalue"] = new DateValue();
Functions["timevalue"] = new TimeValue();
// Database
Functions["dget"] = new Dget();
Functions["dcount"] = new Dcount();
Functions["dcounta"] = new DcountA();
Functions["dmax"] = new Dmax();
Functions["dmin"] = new Dmin();
Functions["dsum"] = new Dsum();
Functions["daverage"] = new Daverage();
Functions["dvar"] = new Dvar();
Functions["dvarp"] = new Dvarp();
//Finance
Functions["pmt"] = new Pmt();
}
}
}
You will see that Trim is not in there, unfortunately. You could, in theory, add it yourself like this:
[TestMethod]
public void Test1()
{
using (var package = new ExcelPackage())
{
package.Workbook.FormulaParserManager.LoadFunctionModule(new MyFunctionModule());
var ws = package.Workbook.Worksheets.Add("Test");
var cellTest = ws.Cells[1, 1];
cellTest.Formula = "TRIM(\"Hello World\")";
ws.Calculate();
var cellCalculatedValue = cellTest.Value; //Will now show a proper value
}
}
public class TrimFunction : ExcelFunction
{
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
ValidateArguments(arguments, 1);
var result = arguments.ElementAt(0).Value.ToString().Trim();
return CreateResult(result, DataType.String);
}
}
public class MyFunctionModule : FunctionsModule
{
public MyFunctionModule()
{
Functions.Add("trim", new TrimFunction());
}
}
But, again, it has nothing to do with the actual function in excel - they are completely separate. The TRIM function above will only existing in the C# world. When excel opens the file, it will apply its own TRIM function.
Related
I'm trying to generate a checkbox from C#.net using google sheets API but I'm encountering the oneof field kind is already set error. I tried combining extendedValue and DataValidation. Please see code snippet below:
ConditionValue conditionValueTrue = new ConditionValue();
conditionValueTrue.UserEnteredValue = "TRUE";
ConditionValue conditionValueFalse = new ConditionValue();
conditionValueFalse.UserEnteredValue = "FALSE";
ConditionValue[] validValues = { conditionValueTrue, conditionValueFalse };
BooleanCondition bc = new BooleanCondition();
bc.Type = "BOOLEAN";
bc.Values = validValues;
DataValidationRule dataValidationRule = new DataValidationRule();
dataValidationRule.Condition = bc;
dataValidationRule.ShowCustomUi = true;
GridRange validationRange = new GridRange();
validationRange.StartColumnIndex = 7;
validationRange.EndColumnIndex = 7;
validationRange.SheetId = 0;
SetDataValidationRequest setDataValidationRequest = new SetDataValidationRequest();
setDataValidationRequest.Rule = dataValidationRule;
setDataValidationRequest.Range = validationRange;
ExtendedValue extendedValue = new ExtendedValue();
extendedValue.BoolValue = true;
BatchUpdateSpreadsheetRequest busr = new BatchUpdateSpreadsheetRequest();
busr.Requests = new List<Request>();
Request r = new Request();
busr.Requests.Add(r);
r.UpdateCells = new UpdateCellsRequest();
r.SetDataValidation = setDataValidationRequest;
var gc = new GridCoordinate();
gc.ColumnIndex = 7;
gc.RowIndex = row;
gc.SheetId = 0;
r.UpdateCells.Start = gc;
r.UpdateCells.Fields = "*";
r.UpdateCells.Rows = new List<RowData>();
var rd = new RowData();
r.UpdateCells.Rows.Add(rd);
rd.Values = new List<CellData>();
var cd = new CellData();
cd.UserEnteredValue = extendedValue;
rd.Values.Add(cd);
SpreadsheetsResource.BatchUpdateRequest bur = _sheetsService.Spreadsheets.BatchUpdate(busr, SpreadsheetId);
bur.Execute();
I need these varaible names to be dynamic.
To give you an example of what I'm looking at > https://ebaydts.com/eBayKBDetails?KBid=1742
Now in the above link, it has some code for variaitons.
//Specify Variations
VariationTypeCollection VarCol = new VariationTypeCollection();
//Variation 1 - Black S
VariationType var1 = new VariationType();
var1.SKU = "VAR1";
var1.Quantity = 10;
var1.StartPrice = new AmountType();
var1.StartPrice.currencyID = CurrencyCodeType.AUD;
var1.StartPrice.Value = 35;
var1.VariationSpecifics = new NameValueListTypeCollection();
NameValueListType Var1Spec1 = new NameValueListType();
StringCollection Var1Spec1Valuecoll = new StringCollection();
Var1Spec1.Name = "Colour";
Var1Spec1Valuecoll.Add("Black");
Var1Spec1.Value = Var1Spec1Valuecoll;
var1.VariationSpecifics.Add(Var1Spec1);
NameValueListType Var1Spec2 = new NameValueListType();
StringCollection Var1Spec2Valuecoll = new StringCollection();
Var1Spec2.Name = "Size";
Var1Spec2Valuecoll.Add("S");
Var1Spec2.Value = Var1Spec2Valuecoll;
var1.VariationSpecifics.Add(Var1Spec2);
VarCol.Add(var1);
//Variation 2 - Black L
VariationType var2 = new VariationType();
var2.SKU = "VAR2";
var2.Quantity = 10;
var2.StartPrice = new AmountType();
var2.StartPrice.currencyID = CurrencyCodeType.AUD;
var2.StartPrice.Value = 45;
var2.VariationSpecifics = new NameValueListTypeCollection();
NameValueListType Var2Spec1 = new NameValueListType();
StringCollection Var2Spec1Valuecoll = new StringCollection();
Var2Spec1.Name = "Colour";
Var2Spec1Valuecoll.Add("Black");
Var2Spec1.Value = Var2Spec1Valuecoll;
var2.VariationSpecifics.Add(Var2Spec1);
NameValueListType Var2Spec2 = new NameValueListType();
StringCollection Var2Spec2Valuecoll = new StringCollection();
Var2Spec2.Name = "Size";
Var2Spec2Valuecoll.Add("L");
Var2Spec2.Value = Var2Spec2Valuecoll;
var2.VariationSpecifics.Add(Var2Spec2);
VarCol.Add(var2);
So the code I'm working with I would Like dynamically create the varaible names, because as you can imagine there is no way for me to know how many variations each product has.
Sure i could count the amount of variations, and set up an if else structure
if (count == 1) {
//some code
}
else if (count == 2) {
//some code
}
But that doesn't seem like a good solution.
At the moment variables are required to be output inside a for each loop
Here is the code I'm working with:
string UPC = "";
string Brand = "";
string MPN = "";
if (!String.IsNullOrEmpty(product.Gtin))
UPC = product.Gtin;
if (!String.IsNullOrEmpty(ebayProduct.EbayProductBrandName))
Brand = ebayProduct.EbayProductBrandName;
if (!String.IsNullOrEmpty(product.ManufacturerPartNumber))
MPN = product.ManufacturerPartNumber;
//create the call object
AddFixedPriceItemCall AddFPItemCall = new AddFixedPriceItemCall(context);
AddFPItemCall.AutoSetItemUUID = true;
//create an item object and set the properties
ItemType item = new ItemType();
//set the item condition depending on the value from GetCategoryFeatures
item.ConditionID = 1000; //new
//Basic properties of a listing
item.Country = CountryCodeType.AU;
item.Currency = CurrencyCodeType.AUD;
//Track item by SKU
item.InventoryTrackingMethod = InventoryTrackingMethodCodeType.SKU;
item.SKU = ebayProduct.EbayProductSKU;
if (!String.IsNullOrEmpty(ebayProduct.EbayProductDescription))
item.Description = ebayProduct.EbayProductDescription;
else
item.Description = "This product is brand new.";
if (!String.IsNullOrEmpty(ebayProduct.EbayProductTitle))
item.Title = ebayProduct.EbayProductTitle;
item.SubTitle = ebayProduct.EbayProductItemSubtitle;
item.ListingDuration = "GTC";
item.ItemSpecifics = new NameValueListTypeCollection();
NameValueListTypeCollection ItemSpecs = new NameValueListTypeCollection();
var productSpecAttributes = product.ProductSpecificationAttributes.ToList();
foreach (var val in productSpecAttributes)
{
StringCollection valueCol1 = new StringCollection();
NameValueListType nv1 = new NameValueListType();
nv1.Name = val.SpecificationAttributeOption.SpecificationAttribute.Name.Replace(":", "");
valueCol1.Add(val.CustomValue);
nv1.Value = valueCol1;
ItemSpecs.Add(nv1);
}
item.ItemSpecifics = ItemSpecs;
item.PaymentMethods = new BuyerPaymentMethodCodeTypeCollection();
item.PaymentMethods.Add(BuyerPaymentMethodCodeType.PayPal);
item.PayPalEmailAddress = "test#test.com";
item.PostalCode = "5000";
//Specify Shipping Services
item.DispatchTimeMax = 3;
item.ShippingDetails = new ShippingDetailsType();
item.ShippingDetails.ShippingServiceOptions = new ShippingServiceOptionsTypeCollection();
ShippingServiceOptionsType shipservice1 = new ShippingServiceOptionsType();
shipservice1.ShippingService = "AU_Regular";
shipservice1.ShippingServicePriority = 1;
shipservice1.ShippingServiceCost = new AmountType();
shipservice1.ShippingServiceCost.currencyID = CurrencyCodeType.AUD;
shipservice1.ShippingServiceCost.Value = 1.0;
shipservice1.ShippingServiceAdditionalCost = new AmountType();
shipservice1.ShippingServiceAdditionalCost.currencyID = CurrencyCodeType.AUD;
shipservice1.ShippingServiceAdditionalCost.Value = 1.0;
item.ShippingDetails.ShippingServiceOptions.Add(shipservice1);
ShippingServiceOptionsType shipservice2 = new ShippingServiceOptionsType();
shipservice2.ShippingService = "AU_Express";
shipservice2.ShippingServicePriority = 2;
shipservice2.ShippingServiceCost = new AmountType();
shipservice2.ShippingServiceCost.currencyID = CurrencyCodeType.AUD;
shipservice2.ShippingServiceCost.Value = 4.0;
shipservice2.ShippingServiceAdditionalCost = new AmountType();
shipservice2.ShippingServiceAdditionalCost.currencyID = CurrencyCodeType.AUD;
shipservice2.ShippingServiceAdditionalCost.Value = 1.0;
item.ShippingDetails.ShippingServiceOptions.Add(shipservice2);
//Specify Return Policy
item.ReturnPolicy = new ReturnPolicyType();
item.ReturnPolicy.ReturnsAcceptedOption = "ReturnsAccepted";
item.StartPrice = new AmountType();
item.StartPrice.currencyID = CurrencyCodeType.AUD;
item.StartPrice.Value = Double.Parse(ebayProduct.EbayProductPrice.ToString());
item.PrimaryCategory = new CategoryType();
item.PrimaryCategory.CategoryID = ebayProduct.EbayCategoryID;
item.ProductListingDetails = new ProductListingDetailsType();
//Specifying UPC as the product identifier. Other applicable product identifiers
//include ISBN, EAN, Brand-MPN.
item.ProductListingDetails.UPC = UPC;
//If multiple product identifiers are specified, eBay uses the first one that
//matches a product in eBay's catalog system.
item.ProductListingDetails.BrandMPN = new BrandMPNType();
item.ProductListingDetails.BrandMPN.Brand = ebayProduct.EbayProductBrandName;
item.ProductListingDetails.BrandMPN.MPN = product.ManufacturerPartNumber;
//If multiple prod matches found, list the item with the 1st product's information
item.ProductListingDetails.UseFirstProduct = true;
//Add pictures
item.PictureDetails = new PictureDetailsType();
item.PictureDetails.PictureURL = new StringCollection();
//Specify GalleryType
item.PictureDetails.GalleryType = GalleryTypeCodeType.None;
item.PictureDetails.GalleryTypeSpecified = true;
/*
* Handle Variations
*/
var childProducts = _productService.GetAssociatedProducts(product.Id);
if (childProducts != null)
{
//Specify VariationsSpecificsSet
item.Variations = new VariationsType();
item.Variations.VariationSpecificsSet = new NameValueListTypeCollection();
var colourSpec = productSpecAttributes.FirstOrDefault(
x => x.SpecificationAttributeOption.SpecificationAttribute.Name == "Colour");
var sizeSpec = productSpecAttributes.FirstOrDefault(
x => x.SpecificationAttributeOption.SpecificationAttribute.Name == "Size");
if (colourSpec != null && sizeSpec == null)
{
List<string> colourSpecsList = new List<string>();
foreach (var cp in childProducts)
{
var colourSpecs = cp.ProductSpecificationAttributes.FirstOrDefault(
x => x.SpecificationAttributeOption.SpecificationAttribute.Name == "Colour");
colourSpecsList.Add(colourSpecs.SpecificationAttributeOption.Name);
}
//sizes
NameValueListType NVListVS2 = new NameValueListType();
NVListVS2.Name = "Colour";
StringCollection VSvaluecollection2 = new StringCollection();
String[] Colour = colourSpecsList.ToArray();
VSvaluecollection2.AddRange(Colour);
NVListVS2.Value = VSvaluecollection2;
item.Variations.VariationSpecificsSet.Add(NVListVS2);
}
//Add Variation Specific Pictures
item.Variations.Pictures = new PicturesTypeCollection();
foreach (var cp in childProducts)
{
//Specify Variations
VariationTypeCollection VarCol = new VariationTypeCollection();
PicturesType pic = new PicturesType();
var specs = cp.ProductSpecificationAttributes.FirstOrDefault(x => x.SpecificationAttributeOption.SpecificationAttribute.Name == "Colour");
var childEbayProduct = _ebayProductService.GetEbayProductById(cp.Id);
if (!String.IsNullOrEmpty(specs.SpecificationAttributeOption.Name))
{
VariationType var1 = new VariationType();
var1.SKU = cp.RexProductId.ToString();
Debug.WriteLine(cp.RexProductId.ToString());
var1.Quantity = cp.StockQuantity;
var1.StartPrice = new AmountType();
var1.StartPrice.currencyID = CurrencyCodeType.AUD;
var1.StartPrice.Value = Double.Parse(cp.Price.ToString());
var1.VariationSpecifics = new NameValueListTypeCollection();
NameValueListType Var1Spec1 = new NameValueListType();
StringCollection Var1Spec1Valuecoll = new StringCollection();
Var1Spec1.Name = "Colour";
Var1Spec1Valuecoll.Add(specs.SpecificationAttributeOption.Name);
Var1Spec1.Value = Var1Spec1Valuecoll;
var1.VariationSpecifics.Add(Var1Spec1);
//pics
pic.VariationSpecificName = "Colour";
pic.VariationSpecificPictureSet = new VariationSpecificPictureSetTypeCollection();
VariationSpecificPictureSetType VarPicSet1 = new VariationSpecificPictureSetType();
VarPicSet1.VariationSpecificValue = specs.SpecificationAttributeOption.Name;
StringCollection PicURLVarPicSet1 = new StringCollection();
PicURLVarPicSet1.Add(childEbayProduct.EbayProductMainImgUrl);
VarPicSet1.PictureURL = PicURLVarPicSet1;
pic.VariationSpecificPictureSet.Add(VarPicSet1);
item.Variations.Pictures.Add(pic);
VarCol.Add(var1);
item.Variations.Variation = VarCol;
}
}
}
Anyone know what I might be able to do here.
Cheers
The closest thing to "dynamic variable names" is a Dictionary.
Dictionary<string, string> variables = new Dictionary<string, string>();
variables.Add("var1", "test1");
variables.Add("var2", "test2");
MessageBox.Show(variables["var1"]); // will display test1
If you have a set of needed data for each "variable", make a class or struct (maybe call it "TheData")
Dictionary<string, TheData> variables = new Dictionary<string, TheData>();
variables.Add("var1", new TheData() { price = 25.28, upc = "01121...", manufacturer = "ACME" });
I am trying to get the UPS Rating API that now supports Time In Transit to work. I have the latest WSDL (UPS API). I keep getting an exception error "An exception has been raised as a result of client data." and I can not figure out what is the problem. Note: The "Rate" requestOption works with no issues - when TimeinTransit and DeliveryInformation data is commented out.
What could be wrong? Any help would be appreciated, thank you.
Here is my C# code:
UPSRateWS.RequestType request = new UPSRateWS.RequestType();
String[] requestOption = { "ratetimeintransit" };
request.RequestOption = requestOption;
request.SubVersion = "1601";
rateRequest.Request = request;
UPSRateWS.ShipmentType shipment = new UPSRateWS.ShipmentType();
UPSRateWS.ShipperType shipper = new UPSRateWS.ShipperType();
UPSRateWS.ShipmentRatingOptionsType shipmentRatingOptions = new
UPSRateWS.ShipmentRatingOptionsType();
shipmentRatingOptions.NegotiatedRatesIndicator = "";
shipmentRatingOptions.RateChartIndicator = "";
shipment.ShipmentRatingOptions = shipmentRatingOptions;
UPSRateWS.TimeInTransitRequestType timeInTransit = new
UPSRateWS.TimeInTransitRequestType();
UPSRateWS.PickupType pickupInTransitType = new UPSRateWS.PickupType();
pickupInTransitType.Date = "20170414";
pickupInTransitType.Time = "1630";
timeInTransit.Pickup = pickupInTransitType;
timeInTransit.PackageBillType = "02";
shipment.NumOfPieces = "1";
shipment.DeliveryTimeInformation = timeInTransit;
UPSRateWS.ShipmentWeightType shipWeightType = new
UPSRateWS.ShipmentWeightType();
shipWeightType.Weight = "10.80";
UPSRateWS.CodeDescriptionType shipWeightUOM = new
UPSRateWS.CodeDescriptionType();
shipWeightUOM.Code = "LBS";
shipWeightUOM.Description = "pounds";
shipWeightType.UnitOfMeasurement = shipWeightUOM;
shipment.ShipmentTotalWeight = shipWeightType;
shipper.ShipperNumber = "XXXXXX";
UPSRateWS.AddressType shipperAddress = new UPSRateWS.AddressType();
string testAddr = "7650 Tyler Blvd";
String[] addressLine = { testAddr };
shipperAddress.AddressLine = addressLine;
shipperAddress.City = "Mentor";
shipperAddress.PostalCode = "44060";
shipperAddress.StateProvinceCode = "OH";
shipperAddress.CountryCode = "US";
shipperAddress.AddressLine = addressLine;
shipper.Address = shipperAddress;
shipment.Shipper = shipper;
UPSRateWS.ShipFromType shipFrom = new UPSRateWS.ShipFromType();
UPSRateWS.ShipAddressType shipFromAddress = new UPSRateWS.ShipAddressType();
string testAddr2 = "";
String[] addressLine1 = { testAddr2 };
shipFromAddress.AddressLine = addressLine1;
shipFromAddress.City = "";
shipFromAddress.PostalCode = "45069";
shipFromAddress.StateProvinceCode = "OH";
shipFromAddress.CountryCode = "US";
shipFrom.Address = shipFromAddress;
shipment.ShipFrom = shipFrom;
UPSRateWS.ShipToType shipTo = new UPSRateWS.ShipToType();
UPSRateWS.ShipToAddressType shipToAddress = new UPSRateWS.ShipToAddressType();
string testAddr3 = "7650 Tyler Blvd";
String[] addressLine2 = { testAddr3 };
shipToAddress.AddressLine = addressLine2;
shipToAddress.City = "Mentor";
shipToAddress.PostalCode = "44060";
shipToAddress.StateProvinceCode = "OH";
shipToAddress.CountryCode = "US";
shipToAddress.ResidentialAddressIndicator = "1";
shipTo.Address = shipToAddress;
shipment.ShipTo = shipTo;
UPSRateWS.CodeDescriptionType service = new UPSRateWS.CodeDescriptionType();
service.Code = "03";
shipment.Service = service;
UPSRateWS.PackageType package = new UPSRateWS.PackageType();
UPSRateWS.PackageWeightType packageWeight = new UPSRateWS.PackageWeightType();
packageWeight.Weight = "10.80";
UPSRateWS.CodeDescriptionType uom = new UPSRateWS.CodeDescriptionType();
uom.Code = "LBS";
uom.Description = "pounds";
packageWeight.UnitOfMeasurement = uom;
package.PackageWeight = packageWeight;
UPSRateWS.CodeDescriptionType packType = new UPSRateWS.CodeDescriptionType();
packType.Code = "02";
package.PackagingType = packType;
UPSRateWS.PackageServiceOptionsType packServType = new
UPSRateWS.PackageServiceOptionsType();
UPSRateWS.InsuredValueType insuredValueType = new UPSRateWS.InsuredValueType();
insuredValueType.CurrencyCode = "USD";
insuredValueType.MonetaryValue = "65.75";
packServType.DeclaredValue = insuredValueType;
UPSRateWS.ShipperDeclaredValueType shipperDeclaredValueType = new
UPSRateWS.ShipperDeclaredValueType();
shipperDeclaredValueType.CurrencyCode = "USD";
shipperDeclaredValueType.MonetaryValue = "65.75";
packServType.ShipperDeclaredValue = shipperDeclaredValueType;
package.PackageServiceOptions = packServType;
UPSRateWS.PackageType[] pkgArray = { package };
shipment.Package = pkgArray;
rateRequest.Shipment = shipment;
UPSRateWS.CodeDescriptionType pickupType = new UPSRateWS.CodeDescriptionType();
pickupType.Code = "01";
pickupType.Description = "Daily Pickup";
rateRequest.PickupType = pickupType;
UPSRateWS.RateResponse rateResponse = myRatePortTypeClient.ProcessRate(upss,
rateRequest);
You need to include both the "rate" option and the "ratetimeintransit" options:
String[] requestOption = { "rate","ratetimeintransit" };
I'm trying to work with the UPS api to create a shipping label. The UPS api uses a webservice to send an XML request to UPS. UPS then sends a response back. Here is my question.
Is there a way to view the XML that is outputted when I call the "shipmentRequest" method?
This is the first time I've used an API and a webservice so if you need me to provide more information just let me know.
Thanks!
EDIT: Here is my C# code
ShipService shpSvc = new ShipService();
ShipmentRequest shipmentRequest = new ShipmentRequest();
UPSSecurity upss = new UPSSecurity();
//shpSvc.Url = "https://onlinetools.ups.com/webservices/Ship";
UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
upssSvcAccessToken.AccessLicenseNumber = apiCode;
upss.ServiceAccessToken = upssSvcAccessToken;
UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
upssUsrNameToken.Username = userName;
upssUsrNameToken.Password = password;
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";
ShipperType shipper = new ShipperType();
shipper.ShipperNumber = accountNumber;
PaymentInfoType paymentInfo = new PaymentInfoType();
ShipmentChargeType shpmentCharge = new ShipmentChargeType();
BillShipperType billShipper = new BillShipperType();
billShipper.AccountNumber = accountNumber;
shpmentCharge.BillShipper = billShipper;
shpmentCharge.Type = "01";
ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
paymentInfo.ShipmentCharge = shpmentChargeArray;
shipment.PaymentInformation = paymentInfo;
ShipWSSample.ShipWebReference.ShipAddressType shipperAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
String[] addressLine = { "480 Parkton Plaza" };
shipperAddress.AddressLine = addressLine;
shipperAddress.City = "Timonium";
shipperAddress.PostalCode = "21093";
shipperAddress.StateProvinceCode = "MD";
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();
ShipWSSample.ShipWebReference.ShipAddressType shipFromAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
String[] shipFromAddressLine = { "Ship From Street" };
shipFromAddress.AddressLine = addressLine;
shipFromAddress.City = "Timonium";
shipFromAddress.PostalCode = "21093";
shipFromAddress.StateProvinceCode = "MD";
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.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 = "01";
shipment.Service = service;
PackageType package = new PackageType();
PackageWeightType packageWeight = new PackageWeightType();
packageWeight.Weight = "1";
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();
LabelStockSizeType labelStockSize = new LabelStockSizeType();
labelStockSize.Height = "6";
labelStockSize.Width = "4";
labelSpec.LabelStockSize = labelStockSize;
LabelImageFormatType labelImageFormat = new LabelImageFormatType();
labelImageFormat.Code = "SPL";
labelSpec.LabelImageFormat = labelImageFormat;
shipmentRequest.LabelSpecification = labelSpec;
shipmentRequest.Shipment = shipment;
ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);
MessageBox.Show("The transaction was a " + shipmentResponse.Response.ResponseStatus.Description);
MessageBox.Show("The 1Z number of the new shipment is " + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
You can inherit from the UPS service and read the response as xml by providing your own XmlWriter by overriding GetWriterForMessage(). You can see a working example here.
i am using this code display xml it may help you.
XDocument mySourceDoc = new XDocument();
mySourceDoc = XDocument.Load(shipmentResponse);
txtxml.Text = mySourceDoc.ToString();
I am creating a xml schema using schema object model, on step "set.compile()", I get the above mentioned error. I guess its related to the base type name of simpletype elements, help!
Is there any method, we can actually see what is giong in while set.compile() method compiles the code??
XmlSchemaSimpleType namesimpletype = new XmlSchemaSimpleType();
XmlSchemaSimpleTypeRestriction res = new XmlSchemaSimpleTypeRestriction();
res.BaseTypeName = new XmlQualifiedName("string","");
XmlSchemaMinLengthFacet facet1 = new XmlSchemaMinLengthFacet();
facet1.Value = "3";
XmlSchemaMaxLengthFacet facet2 = new XmlSchemaMaxLengthFacet();
facet2.Value = "10";
res.Facets.Add(facet1);
res.Facets.Add(facet2);
namesimpletype.Content = res;
XmlSchemaSimpleType phonetype = new XmlSchemaSimpleType();
XmlSchemaSimpleTypeRestriction phone_res = new XmlSchemaSimpleTypeRestriction();
phone_res.BaseTypeName = new XmlQualifiedName("string", "");
XmlSchemaMinLengthFacet phone_facet1 = new XmlSchemaMinLengthFacet();
phone_facet1.Value = "4";
XmlSchemaMaxLengthFacet phone_facet2 = new XmlSchemaMaxLengthFacet();
phone_facet2.Value = "20";
phone_res.Facets.Add(phone_facet1);
phone_res.Facets.Add(phone_facet2);
phonetype.Content = phone_res;
XmlSchemaSimpleType notetype = new XmlSchemaSimpleType();
XmlSchemaSimpleTypeRestriction note_res = new XmlSchemaSimpleTypeRestriction();
note_res.BaseTypeName = new XmlQualifiedName("string", "");
XmlSchemaMinLengthFacet note_facet1 = new XmlSchemaMinLengthFacet();
note_facet1.Value = "0";
XmlSchemaMaxLengthFacet note_facet2 = new XmlSchemaMaxLengthFacet();
facet2.Value = "50";
note_res.Facets.Add(note_facet1);
note_res.Facets.Add(note_facet2);
notetype.Content = note_res;
XmlSchemaComplexType employeetype = new XmlSchemaComplexType();
XmlSchemaSequence emp_seq = new XmlSchemaSequence();
XmlSchemaElement firstname = new XmlSchemaElement();
firstname.Name = "firstname";
firstname.SchemaType = namesimpletype;
XmlSchemaElement lastname = new XmlSchemaElement();
lastname.Name = "lastname";
lastname.SchemaType = namesimpletype;
XmlSchemaElement homephone = new XmlSchemaElement();
homephone.Name = "homePhone";
homephone.SchemaType = phonetype;
XmlSchemaElement notes = new XmlSchemaElement();
notes.Name = "notes";
notes.SchemaType = notetype;
emp_seq.Items.Add(firstname);
emp_seq.Items.Add(lastname);
emp_seq.Items.Add(homephone);
emp_seq.Items.Add(notes);
employeetype.Particle = emp_seq;
/* XmlSchemaAttribute employeeid = new XmlSchemaAttribute();
employeeid.Name = "employeeid";
employeeid.SchemaTypeName = new XmlQualifiedName("int", "");
employeeid.Use = XmlSchemaUse.Required;
employeetype.Attributes.Add(employeeid);
*/
XmlSchemaComplexType complextype = new XmlSchemaComplexType();
complextype.Name = "employees";
XmlSchemaElement employee = new XmlSchemaElement();
employee.Name = "employee";
employee.SchemaType = employeetype;
employee.MinOccurs = 0;
employee.MaxOccursString = "unbounded";
XmlSchemaSequence emps_seq = new XmlSchemaSequence();
emps_seq.Items.Add(employee);
complextype.Particle = emps_seq;
XmlSchema schema = new XmlSchema();
schema.Items.Add(complextype);
XmlSchemaSet set = new XmlSchemaSet();
set.Add(schema);
set.Compile();
/* try
{
set.Compile();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
} */
FileStream stream = new FileStream(textBox1.Text, FileMode.Open);
XmlTextWriter writer = new XmlTextWriter(stream, null);
schema.Write(writer);
writer.Close();
Try to use full name with namespace:
res.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
See Example section on page http://msdn.microsoft.com/en-us/library/1c4sky9s(v=vs.110).aspx