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); }
/// <summary> /// Convert the SubmitFeedResponse stream for the post feed folow into a AmazonExeption if needed /// </summary> /// <param name="responseStream">The response stream object</param> /// <param name="messageType">The type of the message</param> /// <returns></returns> private void parsedResultStreamAndLogReport(Stream responseStream, AmazonEnvelopeMessageType messageType, string submittedBy) { try { using (var stream = responseStream) { // the result may not be an XML document. This will be reveled with testing. var doc = new XmlDocument(); doc.Load(stream); var report = doc.SelectSingleNode("/AmazonEnvelope/Message/ProcessingReport"); var processingSummary = report.SelectSingleNode("ProcessingSummary"); var processingReport = new MarketplaceProcessingReport { MerchantId = _credential.MerchantId, MessageType = messageType.ToString(), TransactionId = report.SelectSingleNode("DocumentTransactionID").InnerText, MessagesProcessed = int.Parse(processingSummary.SelectSingleNode("MessagesProcessed").InnerText), MessagesSuccessful = int.Parse(processingSummary.SelectSingleNode("MessagesSuccessful").InnerText), MessagesWithError = int.Parse(processingSummary.SelectSingleNode("MessagesWithError").InnerText), MessagesWithWarning = int.Parse(processingSummary.SelectSingleNode("MessagesWithWarning").InnerText), StatusCode = report.SelectSingleNode("StatusCode").InnerText, SubmittedBy = submittedBy }; // parsed the any processing report results var results = report.SelectNodes("Result"); var reportResults = new List <MarketplaceProcessingReportResult>(); foreach (XmlNode result in results) { reportResults.Add(new MarketplaceProcessingReportResult { TransactionId = processingReport.TransactionId, MessageId = int.Parse(result.SelectSingleNode("MessageID").InnerText), Code = result.SelectSingleNode("ResultCode").InnerText, MessageCode = result.SelectSingleNode("ResultMessageCode").InnerText, Description = result.SelectSingleNode("ResultDescription").InnerText, AdditionalInfo = result.SelectSingleNode("AdditionalInfo/SKU") == null ? "" : result.SelectSingleNode("AdditionalInfo/SKU").InnerText }); } // determine the real total number of warning messages var warningCount = reportResults.Count(x => x.Code == "Warning"); processingReport.MessagesWithWarning = warningCount; // add it to the report summary processingReport.ReportResults = reportResults; // save it to the database _logger.AddProcessingReport(processingReport); } } catch (Exception ex) { _logger.Add(LogEntrySeverity.Error, LogEntryType.AmazonListing, string.Format("Error in parsing {0} result response stream. <br/> Error Message: {1}", messageType.ToString(), EisHelper.GetExceptionMessage(ex)), ex.StackTrace); } }
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 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 static FileStream GetStream(AmazonEnvelope amazonEnvelope, AmazonEnvelopeMessageType amazonEnvelopeMessageType) { var xml = SerializeFromXml(amazonEnvelope); var fileLocation = GetFeedPath(amazonEnvelopeMessageType); File.WriteAllText(fileLocation, xml); return(File.Open(fileLocation, FileMode.Open, FileAccess.Read)); }
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); }
/// <summary> /// Convert the SubmitFeedResponse stream for the post feed folow into a AmazonExeption if needed /// </summary> /// <param name="responseStream">The response stream object</param> /// <param name="messageType">The type of the message</param> /// <returns></returns> private void parsedResultStreamAndLogReport(Stream responseStream, AmazonEnvelopeMessageType messageType) { try { using (var stream = responseStream) { // the result may not be an XML document. This will be reveled with testing. loadXmlStream(stream, messageType.ToString()); using (var fileStream = File.Create(string.Format("D:\\logs\\resultfeed{0:yyyyMMdd_HHmmss}.txt", DateTime.Now))) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } } } catch (Exception ex) { Logger.LogError(LogEntryType.AmazonProductInventory, string.Format("Error in parsing {0} result response stream. <br/> Error Message: {1}", messageType.ToString(), ex.InnerException != null ? string.Format("{0} <br/>Inner Message: {1}", ex.Message, ex.InnerException.Message) : ex.Message), ex.StackTrace); } }
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); }
private static string GetFeedPath(AmazonEnvelopeMessageType amazonEnvelopeMessageType) { return(string.Format("{0}/Amazon{1}Feed-{2}.xml", GetDirPath(), amazonEnvelopeMessageType, CurrentRequestData.Now.ToString("yyyy-MM-dd hh-mm-ss"))); }
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; }
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); } }
public async Task <MwsResponse <SubmitFeedResponse> > SubmitFeed <T>(List <T> messageItems, AmazonEnvelopeMessageType messageType, DateTime effectiveDate, string feedType, bool purgeAndReplace = false, AmazonEnvelopeMessageOperationType operationType = AmazonEnvelopeMessageOperationType.Update) where T : AmazonMessageChoice { if (typeof(T).Name != messageType.ToString()) { return(new MwsResponse <SubmitFeedResponse> { Error = new ErrorResponse(), ExceptionMessage = "Feed items do not match given messageChoice" }); } var parameters = new SortedDictionary <string, string>(new SortDecendingBytes()); var envelope = InstantiateEnvelope <T>(this.SellerId, this.MarketPlaceId, purgeAndReplace, messageItems, messageType, effectiveDate, operationType); parameters["PurgeAndReplace"] = purgeAndReplace.ToString().ToLower(); parameters["FeedType"] = feedType; try { var result = await SendMws <AmazonEnvelope>(envelope, parameters, "SubmitFeed"); var resultText = await result.Content.ReadAsStringAsync(); var submitFeedResult = MwsUtilities.Deserialize <SubmitFeedResponse>(resultText); if (submitFeedResult != null) { return(new MwsResponse <SubmitFeedResponse> { Result = submitFeedResult }); } var submitFeedError = MwsUtilities.Deserialize <ErrorResponse>(resultText); if (submitFeedError != null) { return(new MwsResponse <SubmitFeedResponse> { Error = submitFeedError }); } return(new MwsResponse <SubmitFeedResponse> { Error = new ErrorResponse(), ExceptionMessage = "Unknown Error" }); } catch (Exception ex) { return(new MwsResponse <SubmitFeedResponse> { Error = new ErrorResponse(), ExceptionMessage = ex.ToString() }); } }
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 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); }