public FileStream GetSingleFeed(object feed, AmazonEnvelopeMessageType amazonEnvelopeMessageType, AmazonEnvelopeMessageOperationType? amazonEnvelopeMessageOperationType) { if (feed != null) { var message = new AmazonEnvelopeMessage { MessageID = "1", Item = feed }; if (amazonEnvelopeMessageOperationType != null) message.OperationType = amazonEnvelopeMessageOperationType.Value; var amazonEnvelope = new AmazonEnvelope { Header = new Header { DocumentVersion = "1.0", MerchantIdentifier = _amazonSellerSettings.SellerId }, MessageType = amazonEnvelopeMessageType, Message = new AmazonEnvelopeMessageCollection(){message} }; return AmazonAppHelper.GetStream(amazonEnvelope, amazonEnvelopeMessageType); } return null; }
public FileStream GetFeed(IEnumerable<object> feeds, AmazonEnvelopeMessageType amazonEnvelopeMessageType, AmazonEnvelopeMessageOperationType? amazonEnvelopeMessageOperationType) { if (feeds != null && feeds.Any()) { var messages = new AmazonEnvelopeMessageCollection(); var msgCounter = 1; foreach (var feed in feeds) { var message = new AmazonEnvelopeMessage { MessageID = msgCounter.ToString(), Item = feed }; if (amazonEnvelopeMessageOperationType != null) message.OperationType = amazonEnvelopeMessageOperationType.Value; messages.Add(message); msgCounter++; } var amazonEnvelope = new AmazonEnvelope { Header = new Header { DocumentVersion = "1.0", MerchantIdentifier = _amazonSellerSettings.SellerId }, MessageType = amazonEnvelopeMessageType, Message = messages }; return AmazonAppHelper.GetStream(amazonEnvelope, amazonEnvelopeMessageType); } return null; }
public static AmazonEnvelope Build() { var amazonEnvelope = new AmazonEnvelope(); amazonEnvelope.Header = new Header(); amazonEnvelope.Header.DocumentVersion = "1.01"; amazonEnvelope.Message = new List <Message>(); amazonEnvelope.MessageType = "Price"; return(amazonEnvelope); }
public AmazonEnvelope BuildEnvelope(AmazonEnvelopeMessageType msgType, IEnumerable <AmazonEnvelopeMessage> msgs) { AmazonEnvelope envelope = new AmazonEnvelope(); envelope.MessageType = msgType; envelope.Message = msgs.ToArray(); envelope.Header = new Header(); envelope.Header.MerchantIdentifier = _marketplace.MerchantId; envelope.Header.DocumentVersion = "1.01"; return(envelope); }
public SubmitFeedRequest BuildSubmitFeedRequest(AmazonEnvelope amazonEnvelope) { SubmitFeedRequest submitFeedRequest = new SubmitFeedRequest(); submitFeedRequest.MWSAuthToken = sellerInfo.MwsAuthToken; submitFeedRequest.Merchant = sellerInfo.SellerId; submitFeedRequest.FeedType = "_POST_PRODUCT_PRICING_DATA_"; var stream = Util.GenerateStreamFromXml <AmazonEnvelope>(amazonEnvelope); submitFeedRequest.FeedContent = stream; submitFeedRequest.ContentMD5 = Util.CalculateContentMD5(stream); return(submitFeedRequest); }
public override List <IReportItemDTO> GetReportItems(MarketType market, string marketplaceId) { AmazonEnvelope <ReturnReportMessageNode> parseResult = null; var text = _reader.ReadAll(); using (var sr = new StringReader(text)) { XmlSerializer serializer = new XmlSerializer(typeof(AmazonEnvelope <ReturnReportMessageNode>)); parseResult = (AmazonEnvelope <ReturnReportMessageNode>)serializer.Deserialize(sr); } var items = GetAllReportItems(parseResult?.Message?.ReturnDetails ?? new ReturnDetailsNode[] { }); return(items); }
public void SubmitFeedTestRed() { MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); config.ServiceURL = serviceURL; MarketplaceWebService.MarketplaceWebService service = new MarketplaceWebServiceClient( creds.AccessKey, creds.SecretKey, appName, appVersion, config); SubmitFeedRequest submitFeedRequest = new SubmitFeedRequest(); submitFeedRequest.MWSAuthToken = mWSAuthToken; submitFeedRequest.Merchant = sellerId; submitFeedRequest.FeedType = "_POST_PRODUCT_PRICING_DATA_"; AmazonEnvelope priceFeed = PriceFeedBuilder.Build(); Message msg = PriceFeedBuilder.BuildMessage(); msg.MessageID = "1"; msg.Price.StandardPrice.Value = 154.40m; msg.Price.SKU = "HEWD9P29A"; priceFeed.Message.Add(msg); Message msg2 = PriceFeedBuilder.BuildMessage(); msg2.MessageID = "2"; msg2.Price.StandardPrice.Value = 62.05m; msg2.Price.SKU = "HEW35S"; priceFeed.Message.Add(msg2); priceFeed.Header.MerchantIdentifier = sellerId; var stream = Util.GenerateStreamFromXml <AmazonEnvelope>(priceFeed); Util.GenerateFromXml <AmazonEnvelope>(priceFeed); submitFeedRequest.FeedContent = stream; submitFeedRequest.ContentMD5 = Util.CalculateContentMD5(stream); SubmitFeedResponse submitFeedResponse = service.SubmitFeed(submitFeedRequest); Console.WriteLine(submitFeedResponse.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId); }
/// <summary> /// Create inventory feed for item's quantity /// </summary> /// <param name="inventoryItems">The list of items that are to have their quantities updated</param> /// <returns></returns> public static AmazonEnvelope CreateInventoryFeedEnvelope(List <AmazonInventoryFeed> inventoryItems) { // iterate to the EIS products and parsed it into Invetory Feed var inventories = new List <AmazonWebServiceModels.Inventory>(); inventoryItems.ForEach(x => { inventories.Add(new AmazonWebServiceModels.Inventory { SKU = x.SKU, Item = x.InventoryQuantity.ToString(), // set the default leadtime shipment to 3 days FulfillmentLatency = (x.LeadtimeShip ?? 0) == 0 ? "3" : x.LeadtimeShip.ToString(), }); }); // create Amazon envelope object var amazonEnvelope = new AmazonEnvelope { Header = new Header { DocumentVersion = "1.01", MerchantIdentifier = MerchantId }, MessageType = AmazonEnvelopeMessageType.Inventory }; // add all Inventory feeds as messages to the envelope var envelopeMessages = new List <AmazonEnvelopeMessage>(); for (var i = 0; i < inventories.Count; i++) { var message = new AmazonEnvelopeMessage { MessageID = string.Format("{0}", i + 1), OperationType = AmazonEnvelopeMessageOperationType.Update, Item = inventories[i] }; envelopeMessages.Add(message); } // convert to array and set its message amazonEnvelope.Message = envelopeMessages.ToArray(); return(amazonEnvelope); }
/// <summary> /// Create Amazon Envelope for the Amazon eisProduct specified /// </summary> /// <param name="products">The Amazon products to be created into Amazon envelope</param> /// <returns></returns> public static AmazonEnvelope CreateProductsFeedEnvelope(List <MarketplaceProductFeedDto> productPostFeeds, AmazonEnvelopeMessageOperationType operationType) { // create product post feed for Amazon var products = new List <AmazonWebServiceModels.Product>(); productPostFeeds.ForEach(feedItem => { products.Add(createProductModelForAmazon(feedItem)); }); // create Amazon envelope object var amazonEnvelope = new AmazonEnvelope { Header = new Header { DocumentVersion = "1.01", MerchantIdentifier = MerchantId }, MessageType = AmazonEnvelopeMessageType.Product, PurgeAndReplace = false, PurgeAndReplaceSpecified = true }; // iterate to all products to update and convert it to envelope message var envelopeMessages = new List <AmazonEnvelopeMessage>(); for (var i = 0; i < products.Count; i++) { var message = new AmazonEnvelopeMessage { MessageID = string.Format("{0}", i + 1), OperationType = operationType, OperationTypeSpecified = true, Item = products[i], }; envelopeMessages.Add(message); } // convert to array and set its message amazonEnvelope.Message = envelopeMessages.ToArray(); return(amazonEnvelope); }
public static string ParseObjectToXML(AmazonEnvelope envelope) { string xmlBody; var objectType = envelope.GetType(); var xmlSerializer = new XmlSerializer(objectType); using (var ms = new MemoryStream()) { xmlSerializer.Serialize(ms, envelope); ms.Position = 0; var sr = new StreamReader(ms, Encoding.UTF8); xmlBody = sr.ReadToEnd(); //xmlBody = getInnerXmlBody(xmlResult); } return(xmlBody); }
public AmazonEnvelope PollFeedStatus(string feedSubmissionId) { AmazonEnvelope response = null; int sleepTime = 60000; for (int i = 0; i < 10; i++) { response = CheckFeedStatus(feedSubmissionId); if (response == null) { Thread.Sleep(sleepTime); } else { break; } } return(response); }
/// <summary> /// The the XML string to write into XML file with the specified file name /// </summary> /// <param name="envelope"></param> /// <param name="fileName"></param> /// <returns>The full file name information</returns> public static string WriteXmlToFile(AmazonEnvelope envelope, string fileName) { var documentFileName = Path.Combine(ConfigurationManager.AppSettings["MarketplaceFeedRoot"], string.Format("{1}_{0:yyyy_MM_dd_HHmmss}.xml", DateTime.Now, fileName)); var xmlString = string.Empty; using (var ms = new MemoryStream()) { var xmlSerializer = new XmlSerializer(envelope.GetType()); xmlSerializer.Serialize(ms, envelope); ms.Position = 0; var sr = new StreamReader(ms, Encoding.UTF8); xmlString = sr.ReadToEnd(); // save it to the directory File.WriteAllText(documentFileName, xmlString); } return(documentFileName); }
private bool UpdateAmazon(IList <Product> products) { bool success = false; // update price on Amazon if (sellerInfo.UpdatePrices) { nLogger.Log(LogLevel.Info, string.Format("Updating prices on Amazon")); SubmitFeedResponse submitFeedResponse = feedHandler.SubmitFeed(products); nLogger.Log(LogLevel.Info, string.Format("PollFeedStatus")); AmazonEnvelope result = feedHandler.PollFeedStatus(submitFeedResponse.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId); nLogger.Log(LogLevel.Info, string.Format("Retrieved feed result")); if (result.Message.First().ProcessingReport.StatusCode == "Complete" && Int16.Parse(result.Message.First().ProcessingReport.ProcessingSummary.MessagesSuccessful) >= 1) { nLogger.Log(LogLevel.Info, string.Format("Feed was a success, success count {0}", result.Message.First().ProcessingReport.ProcessingSummary.MessagesSuccessful)); success = true; } if (result.Message.First().ProcessingReport.StatusCode == "Complete" && Int16.Parse(result.Message.First().ProcessingReport.ProcessingSummary.MessagesWithError) >= 1) { nLogger.Log(LogLevel.Info, string.Format("Errors in feed, error count: {0}", result.Message.First().ProcessingReport.ProcessingSummary.MessagesWithError)); if (result.Message.First().ProcessingReport.Result != null) { nLogger.Log(LogLevel.Info, result.Message.First().ProcessingReport.Result.ResultDescription); } } } else { nLogger.Log(LogLevel.Info, string.Format("Update prices on Amazon Disabled")); } return(success); }
private static AmazonEnvelope InstantiateEnvelope <T>(string merchantId, string marketplaceName, bool purgeAndReplace, List <T> messageItems, AmazonEnvelopeMessageType messageType, DateTime effectiveDate, AmazonEnvelopeMessageOperationType operationType = AmazonEnvelopeMessageOperationType.Update) where T : AmazonMessageChoice { var header = new Amazon.Header() { DocumentVersion = "1.0", MerchantIdentifier = merchantId }; var messageList = new List <AmazonEnvelopeMessage>(); var currentId = 1; foreach (var messageItem in messageItems) { var message = new AmazonEnvelopeMessage() { Item = messageItem, MessageID = currentId++.ToString(), OperationType = operationType }; messageList.Add(message); } var envelope = new AmazonEnvelope() { EffectiveDate = effectiveDate, Header = header, MarketplaceName = marketplaceName, MessageType = messageType, PurgeAndReplace = purgeAndReplace, Message = messageList }; return(envelope); }
public FileStream GetFeed(IEnumerable <object> feeds, AmazonEnvelopeMessageType amazonEnvelopeMessageType, AmazonEnvelopeMessageOperationType?amazonEnvelopeMessageOperationType) { if (feeds != null && feeds.Any()) { var messages = new AmazonEnvelopeMessageCollection(); var msgCounter = 1; foreach (var feed in feeds) { var message = new AmazonEnvelopeMessage { MessageID = msgCounter.ToString(), Item = feed }; if (amazonEnvelopeMessageOperationType != null) { message.OperationType = amazonEnvelopeMessageOperationType.Value; } messages.Add(message); msgCounter++; } var amazonEnvelope = new AmazonEnvelope { Header = new Header { DocumentVersion = "1.0", MerchantIdentifier = _amazonSellerSettings.SellerId }, MessageType = amazonEnvelopeMessageType, Message = messages }; return(AmazonAppHelper.GetStream(amazonEnvelope, amazonEnvelopeMessageType)); } return(null); }
public bool ConfirmOrdersShipment() { // init the Amazon order API var config = new MarketplaceWebServiceConfig { ServiceURL = "https://mws.amazonservices.com" }; config.SetUserAgentHeader(_ApplicationName, _Version, "C#"); var serviceClient = new MarketplaceWebServiceClient(_credential.AccessKeyId, _credential.SecretKey, config); var orderFulfillmentList = new List <OrderFulfillment>(); // get the unshipped orders with tracking number for confirming its shipment var unshippedOrderFeeds = _orderRepository.GetUnshippedOrdersForShipment(ChannelName); if (!unshippedOrderFeeds.Any()) { Console.WriteLine("No unshipped orders found from {0} for shipment confirmation.", ChannelName); return(true); } try { Console.WriteLine("Sending {0} orders for shipment confirmation...", unshippedOrderFeeds.Count); // create the order fulfillment unshippedOrderFeeds.ForEach(order => { // create fulfillment item list from the order items var fulfillmentItems = new List <OrderFulfillmentItem>(); foreach (var item in order.OrderItems) { fulfillmentItems.Add(new OrderFulfillmentItem { Item = item.OrderItemId, Quantity = item.Quantity.ToString() }); } // then, the order fulfillment information orderFulfillmentList.Add(new OrderFulfillment { Item = order.OrderId, FulfillmentDate = order.FulfillmentDate, FulfillmentData = new OrderFulfillmentFulfillmentData { Item = order.Carrier.Code, ShippingMethod = "Ground", // order.ShippingMethod, ShipperTrackingNumber = order.ShipperTrackingNumber }, Item1 = fulfillmentItems.ToArray() }); }); // iterate to the order fulfillment and add it into envelope message var envelopeMessages = new List <AmazonEnvelopeMessage>(); for (var i = 0; i < orderFulfillmentList.Count; i++) { var message = new AmazonEnvelopeMessage { MessageID = string.Format("{0}", i + 1), Item = orderFulfillmentList[i] }; envelopeMessages.Add(message); } // create Amazon envelope object var amazonEnvelope = new AmazonEnvelope { Header = new Header { DocumentVersion = "1.01", MerchantIdentifier = _credential.MerchantId }, MessageType = AmazonEnvelopeMessageType.OrderFulfillment, Message = envelopeMessages.ToArray() }; // let's add these orders to the shipment history addOrderShipmentHistoryAsync(unshippedOrderFeeds); // parse the envelope into file var xmlFullName = XmlParser.WriteXmlToFile(amazonEnvelope, "AmazonOrderFulfillment"); // create feed controller and send the confirmation shipment feed var submitController = new SubmitFeedController(serviceClient, _logger, _credential.MarketplaceId, _credential.MerchantId, _ApplicationName); var streamResponse = submitController.SubmitFeedAndGetResponse(xmlFullName, AmazonFeedType._POST_ORDER_FULFILLMENT_DATA_); parsedResultStreamAndLogReport(streamResponse, AmazonEnvelopeMessageType.OrderFulfillment, _ApplicationName); _logger.LogInfo(LogEntryType.AmazonOrdersProvider, string.Format("{1}:{2} - Successfully sent confirming order shipment for Order IDs: \"{0}\"", string.Join("\", \"", unshippedOrderFeeds.Select(x => x.OrderId)), ChannelName, _ApplicationName, Constants.APP_NAME)); Console.WriteLine("Successfully sent confirming order shipment for Order IDs: \"{0}\"", string.Join("\", \"", unshippedOrderFeeds.Select(x => x.OrderId))); return(true); } catch (Exception ex) { _logger.LogError(LogEntryType.AmazonOrdersProvider, string.Format("{0}:{4} Error in confirming order shipment for for Order IDs: \"{3}\". <br/>Error Message: {1} <br/> Access Key: {2}", ChannelName, (ex.InnerException != null ? string.Format("{0} <br/>Inner Message: {1}", ex.Message, ex.InnerException.Message) : ex.Message), _credential.AccessKeyId, string.Join("\", \"", unshippedOrderFeeds.Select(x => x.OrderId)), _ApplicationName), ex.StackTrace); Console.WriteLine("Error in sending shipment confirmation! Error Message: {0} \nStackTrace: {1} ", ex.Message, ex.StackTrace); // let's delete the order confirmation deleteOrderShipmentHistoryAsync(unshippedOrderFeeds); return(false); } }
private List <string> SendAmazonFeeds(List <List <object> > amazonUpdateList, AmazonEnvelopeMessageType messageType, AmazonFeedType feedType) { { var masterCounter = 1; var returnResult = new List <string>(); foreach (var amazonUpdateGroup in amazonUpdateList) { var amazonEnvelope = new AmazonEnvelope { Header = new Header { DocumentVersion = "1.01", MerchantIdentifier = _merchantId, }, MessageType = messageType, PurgeAndReplace = false, PurgeAndReplaceSpecified = true }; var updates = new List <AmazonEnvelopeMessage>(); var counter = 1; foreach (var amazonUpdate in amazonUpdateGroup) { var curUpdate = new AmazonEnvelopeMessage { MessageID = counter.ToString(), OperationType = AmazonEnvelopeMessageOperationType.Update, //OperationTypeSpecified = true, Item = amazonUpdate }; updates.Add(curUpdate); counter++; } amazonEnvelope.Message = updates.ToArray(); var xmlString = MarketplaceHelper.ParseObjectToXML(amazonEnvelope); var path = "D:\\logs\\"; var fileName = string.Format("Amazon{0}Feed_{1}{3}.{2}", messageType, masterCounter, "xml", DateTime.Now.Second); var documentFileName = Path.Combine(path, fileName); File.WriteAllText(documentFileName, xmlString); if (!File.Exists(documentFileName)) { throw new ArgumentException("SendFeed document not generated properly"); } var feedRequest = new SubmitFeedRequest { Merchant = _merchantId, MarketplaceIdList = new IdList { Id = new List <string>(new[] { _marketplaceId }) }, FeedType = feedType.ToString(), ContentType = new ContentType(MediaType.OctetStream), FeedContent = File.Open(documentFileName, FileMode.Open, FileAccess.Read) }; feedRequest.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5(feedRequest.FeedContent); var feedConfig = new MarketplaceWebServiceConfig { ServiceURL = "https://mws.amazonservices.com" }; var feedService = new MarketplaceWebServiceClient(_awsAccessKey, _secretKey, "Demac", "1.01", feedConfig); var uploadSuccess = false; var retryCount = 0; while (!uploadSuccess) { try { var feedResponse = feedService.SubmitFeed(feedRequest); var submissionId = feedResponse.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId; returnResult.Add(submissionId); uploadSuccess = true; masterCounter++; //Thread.Sleep(120000); } catch (Exception ex) { retryCount++; if (retryCount == 3) { break; } //Thread.Sleep(18000); if (ex.ToString().ToLowerInvariant().Contains("request is throttled")) { continue; } returnResult.Add(string.Format("ERROR: {0}", ex)); } } } return(returnResult); } }
/** * Samples for Marketplace Web Service functionality */ public static async Task Main(string[] args) { var itemList = new List <OrderAcknowledgementItem>(); var item = new OrderAcknowledgementItem { AmazonOrderItemCode = "abc-134", MerchantOrderItemID = "abc" }; itemList.Add(item); var list = new List <AmazonEnvelopeMessage>(); list.Add(new AmazonEnvelopeMessage { MessageID = "1", Item = new OrderAcknowledgement { AmazonOrderID = "111-111-111", MerchantOrderID = "12", StatusCode = OrderAcknowledgementStatusCode.Success, Item = itemList.ToArray() } }); var envelope = new AmazonEnvelope { Header = new Header { DocumentVersion = "1.02", MerchantIdentifier = "id" }, MessageType = AmazonEnvelopeMessageType.OrderAcknowledgement, Message = list.ToArray() }; var writer = new XmlSerializer(typeof(AmazonEnvelope)); if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory)) { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory); } var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{Guid.NewGuid()}.xml"); var file = File.Create(path); writer.Serialize(file, envelope); file.Close(); Console.WriteLine("==========================================="); Console.WriteLine("Welcome to Marketplace Web Service Samples!"); Console.WriteLine("==========================================="); Console.WriteLine("To get started:"); Console.WriteLine("==========================================="); Console.WriteLine(" - Fill in your AWS credentials"); Console.WriteLine(" - Uncomment sample you're interested in trying"); Console.WriteLine(" - Set request with desired parameters"); Console.WriteLine(" - Hit F5 to run!"); Console.WriteLine(); Console.WriteLine("==========================================="); Console.WriteLine("Samples Output"); Console.WriteLine("==========================================="); Console.WriteLine(); /************************************************************************ * Access Key ID and Secret Acess Key ID, obtained from: * http://aws.amazon.com * * IMPORTANT: Your Secret Access Key is a secret, and should be known * only by you and AWS. You should never include your Secret Access Key * in your requests to AWS. You should never e-mail your Secret Access Key * to anyone. It is important to keep your Secret Access Key confidential * to protect your account. ***********************************************************************/ var accessKeyId = ""; var secretAccessKey = ""; /************************************************************************ * Instantiate Implementation of Marketplace Web Service ***********************************************************************/ var config = new MarketplaceWebServiceConfig(); /************************************************************************ * The application name and version are included in each MWS call's * HTTP User-Agent field. These are required fields. ***********************************************************************/ const string applicationName = "EasyKeys.AmazonMWS.Feeds.Test.Test"; const string applicationVersion = "0.1.0"; IMarketplaceWebService service = new MarketplaceWebServiceClient( accessKeyId, secretAccessKey, applicationName, applicationVersion, config); /************************************************************************ * All MWS requests must contain the seller's merchant ID and * marketplace ID. ***********************************************************************/ const string merchantId = ""; #pragma warning disable CS0219 // Variable is assigned but its value is never used const string marketplaceId = "ATVPDKIKX0DER"; #pragma warning restore CS0219 // Variable is assigned but its value is never used /************************************************************************ * Uncomment to configure the client instance. Configuration settings * include: * * - MWS Service endpoint URL * - Proxy Host and Proxy Port * - User Agent String to be sent to Marketplace Web Service service * ***********************************************************************/ //MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); //config.ProxyHost = "https://PROXY_URL"; //config.ProxyPort = 9090; // // IMPORTANT: Uncomment out the appropiate line for the country you wish // to sell in: // // United States: config.ServiceURL = "https://mws.amazonservices.com"; // // United Kingdom: // config.ServiceURL = "https://mws.amazonservices.co.uk"; // // Germany: // config.ServiceURL = "https://mws.amazonservices.de"; // // France: // config.ServiceURL = "https://mws.amazonservices.fr"; // // Japan: // config.ServiceURL = "https://mws.amazonservices.jp"; // // China: // config.ServiceURL = "https://mws.amazonservices.com.cn"; // // Canada: // config.ServiceURL = "https://mws.amazonservices.ca"; // // Italy: // config.ServiceURL = "https://mws.amazonservices.it"; // //config.SetUserAgentHeader( // applicationName, // applicationVersion, // "C#"); //MarketplaceWebService service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKey, config); /************************************************************************ * Uncomment to try out Mock Service that simulates Marketplace Web Service * responses without calling Marketplace Web Service service. * * Responses are loaded from local XML files. You can tweak XML files to * experiment with various outputs during development * * XML files available under MarketplaceWebService\Mock tree * ***********************************************************************/ //MarketplaceWebService service = new MarketplaceWebServiceMock(); /************************************************************************ * Uncomment to invoke Get Report Action ***********************************************************************/ { // GetReportRequest request = new GetReportRequest(); // request.Merchant = merchantId; // request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // Note that depending on the type of report being downloaded, a report can reach // sizes greater than 1GB. For this reason we recommend that you _always_ program to // MWS in a streaming fashion. Otherwise, as your business grows you may silently reach // the in-memory size limit and have to re-work your solution. // NOTE: Due to Content-MD5 validation, the stream must be read/write. // request.ReportId = "REPORT_ID"; // request.Report = File.Open("report.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite ); // GetReportSample.InvokeGetReport(service, request); } /************************************************************************ * Uncomment to invoke Get Report Schedule Count Action ***********************************************************************/ { var request = new GetReportScheduleCountRequest(); request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here await GetReportScheduleCountSample.InvokeGetReportScheduleCount(service, request); } /************************************************************************ * Uncomment to invoke Get Report Request List By Next Token Action ***********************************************************************/ { //GetReportRequestListByNextTokenRequest request = new GetReportRequestListByNextTokenRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional //request.NextToken = "NextToken from GetReportRequestList"; // @TODO: set additional request parameters here //GetReportRequestListByNextTokenSample.InvokeGetReportRequestListByNextToken(service, request); } /************************************************************************ * Uncomment to invoke Update Report Acknowledgements Action ***********************************************************************/ { //UpdateReportAcknowledgementsRequest request = new UpdateReportAcknowledgementsRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional //request.WithReportIdList(new IdList().WithId("REPORT_ID")); // @TODO: set additional request parameters here //UpdateReportAcknowledgementsSample.InvokeUpdateReportAcknowledgements(service, request); } /************************************************************************ * Uncomment to invoke Submit Feed Action ***********************************************************************/ { // SubmitFeedRequest request = new SubmitFeedRequest(); // request.Merchant = merchantId; // request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // request.MarketplaceIdList = new IdList(); // request.MarketplaceIdList.Id = new List<string>( new string [] { marketplaceId } ); // MWS exclusively offers a streaming interface for uploading your feeds. This is because // feed sizes can grow to the 1GB+ range - and as your business grows you could otherwise // silently reach the feed size where your in-memory solution will no longer work, leaving you // puzzled as to why a solution that worked for a long time suddenly stopped working though // you made no changes. For the same reason, we strongly encourage you to generate your feeds to // local disk then upload them directly from disk to MWS. //request.FeedContent = File.Open("feed.xml", FileMode.Open, FileAccess.Read); // Calculating the MD5 hash value exhausts the stream, and therefore we must either reset the // position, or create another stream for the calculation. //request.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent); //request.FeedContent.Position = 0; //request.FeedType = "FEED_TYPE"; //SubmitFeedSample.InvokeSubmitFeed(service, request); } /************************************************************************ * Uncomment to invoke Get Report Count Action ***********************************************************************/ { // GetReportCountRequest request = new GetReportCountRequest(); // request.Merchant = merchantId; // request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here // GetReportCountSample.InvokeGetReportCount(service, request); } /************************************************************************ * Uncomment to invoke Get Feed Submission List By Next Token Action ***********************************************************************/ { //GetFeedSubmissionListByNextTokenRequest request = new GetFeedSubmissionListByNextTokenRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional //request.NextToken = "NextToken from GetFeedSubmissionList"; // @TODO: set additional request parameters here //GetFeedSubmissionListByNextTokenSample.InvokeGetFeedSubmissionListByNextToken(service, request); } /************************************************************************ * Uncomment to invoke Cancel Feed Submissions Action ***********************************************************************/ { //CancelFeedSubmissionsRequest request = new CancelFeedSubmissionsRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here //CancelFeedSubmissionsSample.InvokeCancelFeedSubmissions(service, request); } /************************************************************************ * Uncomment to invoke Request Report Action ***********************************************************************/ { //RequestReportRequest request = new RequestReportRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional //request.MarketplaceIdList = new IdList(); //request.MarketplaceIdList.Id = new List<string>( new string [] { marketplaceId } ); //request.ReportType = "Desired Report Type"; // @TODO: set additional request parameters here //request.ReportOptions = "ShowSalesChannel=true"; //RequestReportSample.InvokeRequestReport(service, request); } /************************************************************************ * Uncomment to invoke Get Feed Submission Count Action ***********************************************************************/ { //GetFeedSubmissionCountRequest request = new GetFeedSubmissionCountRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here //GetFeedSubmissionCountSample.InvokeGetFeedSubmissionCount(service, request); } /************************************************************************ * Uncomment to invoke Cancel Report Requests Action ***********************************************************************/ { //CancelReportRequestsRequest request = new CancelReportRequestsRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here //CancelReportRequestsSample.InvokeCancelReportRequests(service, request); } /************************************************************************ * Uncomment to invoke Get Report List Action ***********************************************************************/ { //GetReportListRequest request = new GetReportListRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here //GetReportListSample.InvokeGetReportList(service, request); } /************************************************************************ * Uncomment to invoke Get Feed Submission Result Action ***********************************************************************/ { //GetFeedSubmissionResultRequest request = new GetFeedSubmissionResultRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // Note that depending on the size of the feed sent in, and the number of errors and warnings, // the result can reach sizes greater than 1GB. For this reason we recommend that you _always_ // program to MWS in a streaming fashion. Otherwise, as your business grows you may silently reach // the in-memory size limit and have to re-work your solution. // NOTE: Due to Content-MD5 validation, the stream must be read/write. //request.FeedSubmissionId = "FEED_SUBMISSION_ID"; //request.FeedSubmissionResult = File.Open("feedSubmissionResult.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite); //GetFeedSubmissionResultSample.InvokeGetFeedSubmissionResult(service, request); } /************************************************************************ * Uncomment to invoke Get Feed Submission List Action ***********************************************************************/ { //GetFeedSubmissionListRequest request = new GetFeedSubmissionListRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here //GetFeedSubmissionListSample.InvokeGetFeedSubmissionList(service, request); } /************************************************************************ * Uncomment to invoke Get Report Request List Action ***********************************************************************/ { //GetReportRequestListRequest request = new GetReportRequestListRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here //GetReportRequestListSample.InvokeGetReportRequestList(service, request); } /************************************************************************ * Uncomment to invoke Get Report Schedule List By Next Token Action ***********************************************************************/ { //GetReportScheduleListByNextTokenRequest request = new GetReportScheduleListByNextTokenRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional //request.NextToken = "NextToken from GetReportScheduleList"; // @TODO: set additional request parameters here //GetReportScheduleListByNextTokenSample.InvokeGetReportScheduleListByNextToken(service, request); } /************************************************************************ * Uncomment to invoke Get Report List By Next Token Action ***********************************************************************/ { // GetReportListByNextTokenRequest request = new GetReportListByNextTokenRequest(); // request.Merchant = merchantId; // request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional //request.NextToken = "NextToken from GetReportList"; // @TODO: set additional request parameters here // GetReportListByNextTokenSample.InvokeGetReportListByNextToken(service, request); } /************************************************************************ * Uncomment to invoke Manage Report Schedule Action ***********************************************************************/ { //ManageReportScheduleRequest request = new ManageReportScheduleRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional //request.ReportType = "Report Type"; //request.Schedule = "Schedule"; // @TODO: set additional request parameters here //ManageReportScheduleSample.InvokeManageReportSchedule(service, request); } /************************************************************************ * Uncomment to invoke Get Report Request Count Action ***********************************************************************/ { //GetReportRequestCountRequest request = new GetReportRequestCountRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here //GetReportRequestCountSample.InvokeGetReportRequestCount(service, request); } /************************************************************************ * Uncomment to invoke Get Report Schedule List Action ***********************************************************************/ { //GetReportScheduleListRequest request = new GetReportScheduleListRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here //GetReportScheduleListSample.InvokeGetReportScheduleList(service, request); } Console.WriteLine(); Console.WriteLine("==========================================="); Console.WriteLine("End of output. You can close this window"); Console.WriteLine("==========================================="); System.Threading.Thread.Sleep(50000); }
public static SubmitFeedResponse SendAmazonFeeds(IMarketplaceWebServiceClient feedService, IEnumerable <Product> amazonUpdateList, AmazonEnvelopeMessageType messageType, AmazonFeedType feedType, string AmazonMerchantId, string AmazonMarketplaceId, string AmazonServiceUrl, string AmazonAccessKeyId, string AmazonSecretAccessKey) { //var requestResponse = new List<string>(); SubmitFeedResponse feedResponse = null; var amazonEnvelope = new AmazonEnvelope { Header = new Header { DocumentVersion = "1.01", MerchantIdentifier = AmazonMerchantId, }, MessageType = messageType }; var updates = new List <AmazonEnvelopeMessage>(); var counter = 1; foreach (var amazonUpdate in amazonUpdateList) { var curUpdate = new AmazonEnvelopeMessage { MessageID = counter.ToString(), Item = amazonUpdate }; updates.Add(curUpdate); counter++; } //add all update products to envelope's message amazonEnvelope.Message = updates.ToArray(); var serializer = new XmlSerializer(amazonEnvelope.GetType()); var stringReader = new StringWriter(); serializer.Serialize(stringReader, amazonEnvelope); var xmlResult = stringReader.ToString(); using (MemoryStream feedStream = new MemoryStream()) { serializer.Serialize(feedStream, amazonEnvelope); var feedRequest = new SubmitFeedRequest { Merchant = AmazonMerchantId, MarketplaceIdList = new IdList { Id = new List <string>(new[] { AmazonMarketplaceId }) }, FeedType = feedType.ToString(), ContentType = new ContentType(MediaType.OctetStream), FeedContent = feedStream }; // Calculating the MD5 hash value exhausts the stream, and therefore we must either reset the // position, or create another stream for the calculation. feedRequest.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5(feedRequest.FeedContent); //var feedService = new MockMarketplaceWebServiceClient(); var uploadSuccess = false; var retryCount = 0; while (!uploadSuccess) { try { feedResponse = feedService.SubmitFeed(feedRequest); //var submissionId = feedResponse.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId; //requestResponse.Add(submissionId); uploadSuccess = true; } catch (Exception ex) { //if sending not succeed after 3 attempts stop retrying retryCount++; if (retryCount == 3) { break; } //pause sending for 3 minutes Thread.Sleep(18000); if (ex.ToString().ToLowerInvariant().Contains("request is throttled")) { continue; } //requestResponse.Add(string.Format("ERROR: {0}", ex)); } } } return(feedResponse); }
public bool ConfirmOrderShimpmentDetails(MarketplaceOrderFulfillment marketplaceOrder, string submittedBy) { if (!marketplaceOrder.OrderItems.Any()) { return(false); } // create configuratin to use US marketplace var config = new MarketplaceWebServiceConfig { ServiceURL = RequestHelper.ServiceUrl }; config.SetUserAgentHeader(_ApplicationName, _Version, "C#"); _amazonClient = new MarketplaceWebServiceClient(_credential.AccessKeyId, _credential.SecretKey, config); try { // create fulfillment item list from the order items var fulfillmentItems = new List <OrderFulfillmentItem>(); foreach (var item in marketplaceOrder.OrderItems) { fulfillmentItems.Add(new OrderFulfillmentItem { Item = item.OrderItemId, Quantity = item.Quantity.ToString() }); } // create the order fulfillment information var fulfillment = new OrderFulfillment { Item = marketplaceOrder.OrderId, FulfillmentDate = marketplaceOrder.FulfillmentDate, FulfillmentData = new OrderFulfillmentFulfillmentData { Item = marketplaceOrder.Carrier.Code, ShippingMethod = marketplaceOrder.ShippingMethod, ShipperTrackingNumber = marketplaceOrder.ShipperTrackingNumber }, Item1 = fulfillmentItems.ToArray() }; // create Amazon envelope object var amazonEnvelope = new AmazonEnvelope { Header = new Header { DocumentVersion = "1.01", MerchantIdentifier = _credential.MerchantId }, MessageType = AmazonEnvelopeMessageType.OrderFulfillment, Message = new AmazonEnvelopeMessage[] { new AmazonEnvelopeMessage { MessageID = "1", Item = fulfillment } } }; // parse the envelope into file var xmlFullName = XmlParser.WriteXmlToFile(amazonEnvelope, "OrderFulfillment"); var submitController = new SubmitFeedController(_amazonClient, _logger, _credential.MarketplaceId, _credential.MerchantId, submittedBy); var streamResponse = submitController.SubmitFeedAndGetResponse(xmlFullName, AmazonFeedType._POST_ORDER_FULFILLMENT_DATA_); parsedResultStreamAndLogReport(streamResponse, AmazonEnvelopeMessageType.OrderFulfillment, submittedBy); _logger.Add(LogEntrySeverity.Information, LogEntryType.AmazonOrdersProvider, string.Format("{0} - Successfully sent confirming order shipment for Order ID \'{1}\'", ChannelName, marketplaceOrder.OrderId)); return(true); } catch (Exception ex) { _logger.Add(LogEntrySeverity.Error, LogEntryType.AmazonOrdersProvider, string.Format("{0} - Error in confirming order shipment for OrderId: {3}. <br/>Error Message: {1} <br/> Access Key: {2}", ChannelName, EisHelper.GetExceptionMessage(ex), _credential.AccessKeyId, marketplaceOrder.OrderId), ex.StackTrace); return(false); } }