コード例 #1
0
        public void SubmitFeedTest()
        {
            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();

            priceFeed.Message.First().MessageID = "1";
            priceFeed.Message.First().Price.StandardPrice.Value = 67.00m;
            priceFeed.Message.First().Price.SKU = "8E-5FMM-A9HN";             //priceFeed.Message.Add(new Message() { MessageID = "123" });
            priceFeed.Header.MerchantIdentifier = sellerId;
            var stream = Util.GenerateStreamFromXml <AmazonEnvelope>(priceFeed);

            submitFeedRequest.FeedContent = stream;
            submitFeedRequest.ContentMD5  = Util.CalculateContentMD5(stream);
            SubmitFeedResponse submitFeedResponse = service.SubmitFeed(submitFeedRequest);

            //Util.GenerateFromXml<AmazonEnvelope>(priceFeed);

            Console.WriteLine(submitFeedResponse.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId);
        }
コード例 #2
0
        public SubmitFeedResponse SubmitFeed(IList <RedCarpet.Data.Model.Product> products)
        {
            nLogger.Info("SubmitFeed");

            AmazonEnvelope     amazonEnvelope     = BuildAmazonEnvelope(products);
            SubmitFeedRequest  submitFeedRequest  = BuildSubmitFeedRequest(amazonEnvelope);
            SubmitFeedResponse submitFeedResponse = service.SubmitFeed(submitFeedRequest);

            return(submitFeedResponse);
        }
コード例 #3
0
ファイル: FeedSubmissionTests.cs プロジェクト: jdease/EasyMWS
        private void Setup_SubmitFeed_Returns_FeedSubmissionIdWasGenerated(string expectedFeedSubmissionId, string feedType)
        {
            var response = new SubmitFeedResponse
            {
                ResponseHeaderMetadata = new ResponseHeaderMetadata("requestId", "responseContext", "timestamp"),
                SubmitFeedResult       = new SubmitFeedResult()
                {
                    FeedSubmissionInfo = new FeedSubmissionInfo()
                    {
                        FeedSubmissionId = expectedFeedSubmissionId
                    }
                }
            };

            _mwsClientMock
            .Setup(mws => mws.SubmitFeed(It.Is <SubmitFeedRequest>(rrr => rrr.FeedType == feedType && rrr.Merchant == _merchantId)))
            .Returns(response);
        }
        private SubmitFeedResponse InvokeSubmitFeed(SubmitFeedParamaters objParams, string xmlFeedContent)
        {
            SubmitFeedResponse resSubmitFeed = new SubmitFeedResponse();

            try
            {
                UTF8Encoding      encoding   = new UTF8Encoding();
                Stream            streamData = new MemoryStream(encoding.GetBytes(xmlFeedContent));
                SubmitFeedRequest request    = new SubmitFeedRequest();
                request.Merchant             = objParams.objSOAmazonSetup.SellerId;
                request.FeedContent          = streamData;
                request.ContentMD5           = MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent);
                request.FeedContent.Position = 0;
                request.PurgeAndReplace      = false;
                request.FeedType             = SOConstants.feedTypePostOrderFulfillment;
                request.MWSAuthToken         = objParams.objSOAmazonSetup.AuthToken;
                resSubmitFeed = clientFeed.SubmitFeed(request);
            }
            catch (Exception ex)
            {
                if (ex is MarketplaceWebServiceException)
                {
                    MarketplaceWebServiceException exception = ex as MarketplaceWebServiceException;
                    if (!string.IsNullOrEmpty(exception.ErrorCode) && exception.ErrorCode.ToLower().Trim() == SOMessages.requestThrottled)
                    {
                        Thread.Sleep(SOHelper.DelayProcess(objParams.objPartialMaint, SOConstants.apiSubmitFeed));
                        resSubmitFeed = InvokeSubmitFeed(objParams, xmlFeedContent);
                    }
                    else
                    {
                        throw new PXException(!string.IsNullOrEmpty(ex.Message) ? ex.Message :
                                              ex.InnerException != null && ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message
                             : SOConstants.exceptionIsEmpty);
                    }
                }
                else
                {
                    throw new PXException(!string.IsNullOrEmpty(ex.Message) ? ex.Message :
                                          ex.InnerException != null && ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message
                             : SOConstants.exceptionIsEmpty);
                }
            }
            return(resSubmitFeed);
        }
        public AmazonEnvelope InvokeServicesCalls(SubmitFeedParamaters objParams, string xmlFeedContent)
        {
            AmazonEnvelope resultEnvelope = null;

            try
            {
                MarketplaceWebService.MarketplaceWebService serviceConfig = this.Configurations(objParams.objSOAmazonSetup.IntegrationType.Trim(), objParams.objSOAmazonSetup.AccessKey, objParams.objSOAmazonSetup.SecretKey);
                if (serviceConfig != null)
                {
                    SubmitFeedResponse feedresponse = null;
                    feedresponse = new AMSubmitFeedServiceCall(serviceConfig).InvokeSubmitFeed(objParams, xmlFeedContent);
                    if (feedresponse != null && feedresponse.SubmitFeedResult != null && feedresponse.SubmitFeedResult.FeedSubmissionInfo != null &&
                        !string.IsNullOrEmpty(feedresponse.SubmitFeedResult.FeedSubmissionInfo.FeedProcessingStatus) &&
                        feedresponse.SubmitFeedResult.FeedSubmissionInfo.FeedProcessingStatus.ToUpper().Trim('_') == SOConstants.Submitted)
                    {
                        string submissionFeedId = feedresponse.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            new AMSubmitFeedServiceCall(serviceConfig).GetSubmitFeedResult(objParams, submissionFeedId, ms);
                            XmlDocument xDocument = new XmlDocument();
                            xDocument.Load(ms);
                            string        xmlResultContent = SOHelper.ObjectToXMLConversion(xDocument, string.Empty, true);
                            XmlSerializer deserializer     = new XmlSerializer(typeof(AmazonEnvelope), new XmlRootAttribute(SOConstants.amazonEnvelope));
                            using (TextReader reader = new StringReader(xmlResultContent))
                            {
                                resultEnvelope = (AmazonEnvelope)deserializer.Deserialize(reader);
                            }
                            return(resultEnvelope);
                        }
                    }
                }
                else
                {
                    throw new PXException(SOConstants.credentialsinvalid);
                }
            }
            catch (Exception ex)
            {
                throw new PXException(ex.Message);
            }
            return(resultEnvelope);
        }
コード例 #6
0
		public void SubmitFeedTestRedCarpet()
		{
			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.GenerateXmlFile<AmazonEnvelope>(priceFeed);

			submitFeedRequest.FeedContent = stream;
			submitFeedRequest.ContentMD5 = Util.CalculateContentMD5(stream);
			SubmitFeedResponse submitFeedResponse = service.SubmitFeed(submitFeedRequest);


			Console.WriteLine(submitFeedResponse.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId);
		}
コード例 #7
0
        public FeedSubmissionInfo SubmitFeed(EFeedType FeedType, string FeedContent, bool PurgeAndReplace)
        {
            switch (PurgeAndReplace)
            {
            case true:
                this.Throttle(ERequestType.SubmitFeedPurgeAndReplace);
                break;

            case false:
                this.Throttle();
                break;
            }

            AmazonCredential            Credentials = this.GetCredential();
            MarketplaceWebServiceClient Client      = this.GetClient(Credentials);
            SubmitFeedRequest           Request     = new SubmitFeedRequest()
            {
                Merchant        = Credentials.MerchantID,
                FeedType        = EnumStringHandler.GetEnumString <EFeedType>(FeedType),
                FeedContent     = new MemoryStream(Encoding.ASCII.GetBytes(FeedContent)),
                PurgeAndReplace = PurgeAndReplace
            };
            SubmitFeedResponse Response = Client.SubmitFeed(Request);

            if (Response.IsSetSubmitFeedResult())
            {
                SubmitFeedResult Result = Response.SubmitFeedResult;
                if (Result.IsSetFeedSubmissionInfo())
                {
                    return(Result.FeedSubmissionInfo);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
コード例 #8
0
        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);
        }
コード例 #9
0
        public SubmitFeedResult SubmitFeed(MarketplaceWebService service, FileInfo fileInfo, AmazonFeedType feedType)
        {
            var response = new SubmitFeedResponse();

            var sfRequest = new SubmitFeedRequest();

            sfRequest.Merchant          = _merchantId;
            sfRequest.MarketplaceIdList = new IdList {
                Id = new List <string>(new[] { _marketplaceId })
            };

            using (var stream = new FileStream(fileInfo.Name, FileMode.Open, FileAccess.ReadWrite))
            {
                sfRequest.FeedContent          = stream;
                sfRequest.ContentMD5           = MarketplaceWebServiceClient.CalculateContentMD5(sfRequest.FeedContent);
                sfRequest.FeedContent.Position = 0;
                sfRequest.FeedType             = feedType.ToString();

                response = service.SubmitFeed(sfRequest);
            }

            return(response.SubmitFeedResult);
        }
        public Stream SubmitFeedAndGetResponse(Stream dataStream, string feedType)
        {
            var submitFeedRequest = CreateSubmitFeedRequest(dataStream, feedType);
            SubmitFeedResponse submitFeedResponse = null;

            try
            {
                submitFeedResponse = _AmazonClient.SubmitFeed(submitFeedRequest);
            }
            catch (MarketplaceWebServiceException ex)
            {
                // Make sure the file stream gets closed after everything.
                dataStream.Close();
                throw ex;
            }
            // Make sure the file stream gets closed after everything.
            dataStream.Close();

            // If the previous errors out then don't run this. Return an exception.
            WaitForGetFeedSubmissionListToComplete(submitFeedResponse.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId);

            return(GetFeedSubmissionResultStream(submitFeedResponse.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId));
        }
コード例 #11
0
        public static string SubmitAmazonTrackingFeed(string filepath, string merchantId, string marketplaceId, string accessKeyId, string secretAccessKey)
        {
            string            feedSubmissionId = "";
            SubmitFeedRequest request          = new SubmitFeedRequest();

            request.Merchant             = merchantId;
            request.MarketplaceIdList    = new IdList();
            request.MarketplaceIdList.Id = new List <string>(new string[] { marketplaceId });
            request.FeedContent          = File.Open(filepath, FileMode.Open, FileAccess.Read);
            request.ContentMD5           = MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent);
            request.FeedContent.Position = 0;
            request.FeedType             = "_POST_ORDER_FULFILLMENT_DATA_";

            const string applicationName       = "<Your Application Name>";
            const string applicationVersion    = "<Your Application Version>";
            MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();

            config.ServiceURL = "https://mws.amazonservices.com";
            config.SetUserAgentHeader(
                applicationName,
                applicationVersion,
                "C#",
                "<Parameter 1>", "<Parameter 2>");
            MarketplaceWebService.MarketplaceWebService service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKey, config);

            try
            {
                SubmitFeedResponse response = service.SubmitFeed(request);


                Console.WriteLine("Service Response");
                Console.WriteLine("=============================================================================");
                Console.WriteLine();

                Console.WriteLine("        SubmitFeedResponse");
                if (response.IsSetSubmitFeedResult())
                {
                    Console.WriteLine("            SubmitFeedResult");
                    SubmitFeedResult submitFeedResult = response.SubmitFeedResult;
                    if (submitFeedResult.IsSetFeedSubmissionInfo())
                    {
                        Console.WriteLine("                FeedSubmissionInfo");
                        FeedSubmissionInfo feedSubmissionInfo = submitFeedResult.FeedSubmissionInfo;
                        if (feedSubmissionInfo.IsSetFeedSubmissionId())
                        {
                            Console.WriteLine("                    FeedSubmissionId");
                            Console.WriteLine("                        {0}", feedSubmissionInfo.FeedSubmissionId);
                            feedSubmissionId = feedSubmissionInfo.FeedSubmissionId;
                        }
                        if (feedSubmissionInfo.IsSetFeedType())
                        {
                            Console.WriteLine("                    FeedType");
                            Console.WriteLine("                        {0}", feedSubmissionInfo.FeedType);
                        }
                        if (feedSubmissionInfo.IsSetSubmittedDate())
                        {
                            Console.WriteLine("                    SubmittedDate");
                            Console.WriteLine("                        {0}", feedSubmissionInfo.SubmittedDate);
                        }
                        if (feedSubmissionInfo.IsSetFeedProcessingStatus())
                        {
                            Console.WriteLine("                    FeedProcessingStatus");
                            Console.WriteLine("                        {0}", feedSubmissionInfo.FeedProcessingStatus);
                        }
                        if (feedSubmissionInfo.IsSetStartedProcessingDate())
                        {
                            Console.WriteLine("                    StartedProcessingDate");
                            Console.WriteLine("                        {0}", feedSubmissionInfo.StartedProcessingDate);
                        }
                        if (feedSubmissionInfo.IsSetCompletedProcessingDate())
                        {
                            Console.WriteLine("                    CompletedProcessingDate");
                            Console.WriteLine("                        {0}", feedSubmissionInfo.CompletedProcessingDate);
                        }
                    }
                }
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }

                Console.WriteLine("            ResponseHeaderMetadata");
                Console.WriteLine("                RequestId");
                Console.WriteLine("                    " + response.ResponseHeaderMetadata.RequestId);
                Console.WriteLine("                ResponseContext");
                Console.WriteLine("                    " + response.ResponseHeaderMetadata.ResponseContext);
                Console.WriteLine("                Timestamp");
                Console.WriteLine("                    " + response.ResponseHeaderMetadata.Timestamp);
            }
            catch (MarketplaceWebServiceException ex)
            {
                ExceptionUtility exceptionUtility = new ExceptionUtility();
                exceptionUtility.CatchMethod(ex, "SubmitAmazonTrackingFeed Error:", ex.Message.ToString(), senderEmail, messageFromPassword, messageToEmail, smtpClient, smtpPortNum);

                Console.WriteLine("Caught Exception: " + ex.Message);
                Console.WriteLine("Response Status Code: " + ex.StatusCode);
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine("Error Type: " + ex.ErrorType);
                Console.WriteLine("Request ID: " + ex.RequestId);
                Console.WriteLine("XML: " + ex.XML);
                Console.WriteLine("ResponseHeaderMetadata: " + ex.ResponseHeaderMetadata);
            }

            return(feedSubmissionId);
        }
コード例 #12
0
        public List <XElement> SubmitFeed(string accountName, XElement feed)
        {
            List <XElement>   errors  = new List <XElement>();
            SubmitFeedRequest request = new SubmitFeedRequest();

            request.FeedType             = "_POST_INVENTORY_AVAILABILITY_DATA_";
            request.MWSAuthToken         = mwsAuthTokenDictionary[accountName];
            request.Merchant             = sellerIdDictionary[accountName];
            request.MarketplaceIdList    = new IdList();
            request.MarketplaceIdList.Id = new List <string>();
            request.MarketplaceIdList.Id.Add(marketplaceId);
            MemoryStream memoryStream = new MemoryStream();

            feed.Save(memoryStream);
            request.FeedContent          = memoryStream;
            request.FeedContent.Position = 0;
            request.ContentMD5           = MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent);
            request.FeedContent.Position = 0;

            int retryCount = 0;
            SubmitFeedResponse response = null;

            while (retryCount <= 4 && response == null)
            {
                Thread.Sleep(TimeSpan.FromMinutes(retryCount * 2));
                try
                {
                    response = mwsClient.SubmitFeed(request);
                }
                catch (Exception e)
                {
                    if (retryCount >= 4)
                    {
                        throw e;
                    }
                    retryCount++;
                }
            }

            memoryStream.Close();
            string feedSubmissionId = response.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId;

            int  count = 0;
            bool done  = false;

            while (count < 100 && !done)
            {
                Thread.Sleep(60000);
                GetFeedSubmissionListRequest feedSubmissionListRequest = new GetFeedSubmissionListRequest();
                feedSubmissionListRequest.MWSAuthToken         = mwsAuthTokenDictionary[accountName];
                feedSubmissionListRequest.Merchant             = sellerIdDictionary[accountName];
                feedSubmissionListRequest.FeedSubmissionIdList = new IdList();
                feedSubmissionListRequest.FeedSubmissionIdList.Id.Add(feedSubmissionId);
                GetFeedSubmissionListResponse feedSubmissionResponse = mwsClient.GetFeedSubmissionList(feedSubmissionListRequest);
                foreach (FeedSubmissionInfo info in feedSubmissionResponse.GetFeedSubmissionListResult.FeedSubmissionInfo)
                {
                    if (info.FeedSubmissionId == feedSubmissionId)
                    {
                        if (info.FeedProcessingStatus == "_DONE_")
                        {
                            done = true;
                            GetFeedSubmissionResultRequest feedSubmissionResultRequest = new GetFeedSubmissionResultRequest();
                            feedSubmissionResultRequest.MWSAuthToken     = mwsAuthTokenDictionary[accountName];
                            feedSubmissionResultRequest.Merchant         = sellerIdDictionary[accountName];
                            feedSubmissionResultRequest.FeedSubmissionId = feedSubmissionId;

                            MemoryStream stream = new MemoryStream();
                            feedSubmissionResultRequest.FeedSubmissionResult = stream;

                            retryCount = 0;
                            GetFeedSubmissionResultResponse feedSubmissionResultResponse = null;
                            while (retryCount <= m_maxRetry && feedSubmissionResultResponse == null)
                            {
                                Thread.Sleep(TimeSpan.FromMinutes(retryCount * 2));
                                try
                                {
                                    feedSubmissionResultResponse = mwsClient.GetFeedSubmissionResult(feedSubmissionResultRequest);
                                }
                                catch (MarketplaceWebServiceException e)
                                {
                                    if (e.ErrorCode == "RequestThrottled")
                                    {
                                        retryCount++;
                                    }
                                }
                            }


                            XElement responseElement        = XElement.Load(stream);
                            IEnumerable <XElement> messages = responseElement.Descendants("Message");
                            foreach (XElement message in messages)
                            {
                                XElement processingReportElement = message.Element("ProcessingReport");
                                int      nError = (int)processingReportElement.Element("ProcessingSummary").Element("MessagesWithError");
                                if (nError > 0)
                                {
                                    int messageId = (int)message.Element("MessageID");
                                }
                            }
                        }
                    }
                }
                count++;
            }

            return(errors);
        }
コード例 #13
0
        /// <summary>
        /// Uploads a file for processing together with the necessary
        /// metadata to process the file, such as which type of feed it is.
        /// PurgeAndReplace if true means that your existing e.g. inventory is
        /// wiped out and replace with the contents of this feed - use with
        /// caution (the default is false).
        ///
        /// </summary>
        /// <param name="service">Instance of MarketplaceWebService service</param>
        /// <param name="request">SubmitFeedRequest request</param>
        public static void InvokeSubmitFeed(MarketplaceWebService service, SubmitFeedRequest request)
        {
            try
            {
                SubmitFeedResponse response = service.SubmitFeed(request);


                Console.WriteLine("Service Response");
                Console.WriteLine("=============================================================================");
                Console.WriteLine();

                Console.WriteLine("        SubmitFeedResponse");
                if (response.IsSetSubmitFeedResult())
                {
                    Console.WriteLine("            SubmitFeedResult");
                    SubmitFeedResult submitFeedResult = response.SubmitFeedResult;
                    if (submitFeedResult.IsSetFeedSubmissionInfo())
                    {
                        Console.WriteLine("                FeedSubmissionInfo");
                        FeedSubmissionInfo feedSubmissionInfo = submitFeedResult.FeedSubmissionInfo;
                        if (feedSubmissionInfo.IsSetFeedSubmissionId())
                        {
                            Console.WriteLine("                    FeedSubmissionId");
                            Console.WriteLine("                        {0}", feedSubmissionInfo.FeedSubmissionId);
                        }
                        if (feedSubmissionInfo.IsSetFeedType())
                        {
                            Console.WriteLine("                    FeedType");
                            Console.WriteLine("                        {0}", feedSubmissionInfo.FeedType);
                        }
                        if (feedSubmissionInfo.IsSetSubmittedDate())
                        {
                            Console.WriteLine("                    SubmittedDate");
                            Console.WriteLine("                        {0}", feedSubmissionInfo.SubmittedDate);
                        }
                        if (feedSubmissionInfo.IsSetFeedProcessingStatus())
                        {
                            Console.WriteLine("                    FeedProcessingStatus");
                            Console.WriteLine("                        {0}", feedSubmissionInfo.FeedProcessingStatus);
                        }
                        if (feedSubmissionInfo.IsSetStartedProcessingDate())
                        {
                            Console.WriteLine("                    StartedProcessingDate");
                            Console.WriteLine("                        {0}", feedSubmissionInfo.StartedProcessingDate);
                        }
                        if (feedSubmissionInfo.IsSetCompletedProcessingDate())
                        {
                            Console.WriteLine("                    CompletedProcessingDate");
                            Console.WriteLine("                        {0}", feedSubmissionInfo.CompletedProcessingDate);
                        }
                    }
                }
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
            }
            catch (MarketplaceWebServiceException ex)
            {
                Console.WriteLine("Caught Exception: " + ex.Message);
                Console.WriteLine("Response Status Code: " + ex.StatusCode);
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine("Error Type: " + ex.ErrorType);
                Console.WriteLine("Request ID: " + ex.RequestId);
                Console.WriteLine("XML: " + ex.XML);
            }
        }
コード例 #14
0
        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);
        }