/// <summary> /// Default public contructor. All properties are set via the config file /// </summary> public AmazonIntegration() { // Verify that the settings in the config file are setup correctly. if (string.IsNullOrWhiteSpace(_AccessKeyId)) throw new InvalidOperationException("AWSAccessKeyId setting in the config file can't be whitespace, blank or null"); if (string.IsNullOrWhiteSpace(_SecretAccessKey)) throw new InvalidOperationException("AWSSecretAccessKey setting in the config file can't be whitespace, blank or null"); if (string.IsNullOrWhiteSpace(_ApplicationName)) throw new InvalidOperationException("AWSApplicationName setting in the config file can't be whitespace, blank or null"); if (string.IsNullOrWhiteSpace(_ApplicationVersion)) throw new InvalidOperationException("AWSApplicationVersion setting in the config file can't be whitespace, blank or null"); if (string.IsNullOrWhiteSpace(_MerchantId)) throw new InvalidOperationException("AWSMerchantId setting in the config file can't be whitespace, blank or null"); if (string.IsNullOrWhiteSpace(_MarketplaceId)) throw new InvalidOperationException("AWSMarketplaceId setting in the config file can't be whitespace, blank or null"); if (string.IsNullOrWhiteSpace(_TemporaryFileDirectory)) throw new InvalidOperationException("TempFileDirectory setting in the config file can't be whitespace, blank or null"); var config = new MarketplaceWebServiceConfig(); // Set configuration to use US marketplace config.ServiceURL = "https://mws.amazonservices.com"; // Set the HTTP Header for user agent for the application. config.SetUserAgentHeader( _ApplicationName, _ApplicationVersion, "C#"); _AmazonClient = new MarketplaceWebServiceClient(_AccessKeyId, _SecretAccessKey, config); // Setup the orders service client var ordersConfig = new MarketplaceWebServiceOrdersConfig(); ordersConfig.ServiceURL = "https://mws.amazonservices.com/Orders/2011-01-01"; ordersConfig.SetUserAgent(_ApplicationName, _ApplicationVersion); _AmazonOrdersClient = new MarketplaceWebServiceOrdersClient( _ApplicationName, _ApplicationVersion, _AccessKeyId, _SecretAccessKey, ordersConfig); }
private static void Test() { var config = new MarketplaceWebServiceConfig(); config.SetUserAgentHeader( "", "", "C#" ); config.ServiceURL = "https://mws.amazonservices.com"; MarketplaceWebService service = new MarketplaceWebServiceClient( Secret.AwsAccessKeyId, Secret.AwsSecretAccessKey, config ); var request = new SubmitFeedRequest { Merchant = Secret.MerchantId, MWSAuthToken = null,//"", MarketplaceIdList = new IdList { Id = new List< string >( new string[] { Secret.MarketplaceId } ) }, FeedContent = File.Open( Filename, FileMode.Open, FileAccess.Read ), FeedType = FeedType }; request.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5( request.FeedContent ); request.FeedContent.Position = 0; SubmitFeedSample.InvokeSubmitFeed( service, request ); }
public void GetFeedsTest() { MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); config.ServiceURL = serviceURL; MarketplaceWebService.MarketplaceWebService service = new MarketplaceWebServiceClient( creds.AccessKey, creds.SecretKey, appName, appVersion, config); GetFeedSubmissionListRequest req = new GetFeedSubmissionListRequest(); req.MWSAuthToken = mWSAuthToken; req.Merchant = sellerId; var response = service.GetFeedSubmissionList(req); foreach (var item in response.GetFeedSubmissionListResult.FeedSubmissionInfo) { Console.WriteLine(item.FeedSubmissionId); } }
public MarketplaceWebServiceClient GetMWSClient() { MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); config.ServiceURL = "https://mws.amazonservices.com"; config.SetUserAgentHeader( "berkeley", "1.0", "C#", "<Parameter 1>", "<Parameter 2>"); MarketplaceWebServiceClient service = new MarketplaceWebServiceClient( this.AccessKeyId, this.SecretAccessKey, "berkeley", "1.0", config); return(service); }
public AmazonService(PlatformServiceFactory platformServiceFactory, string company, string connectionString) { m_platformServiceFactory = platformServiceFactory; m_company = company; m_connectionString = connectionString; using (ERPContext context = new ERPContext(m_connectionString)) { var q = from amazonAccount in context.AmazonAccount select amazonAccount; foreach (var row in q) { sellerIdDictionary[row.AccountName] = row.SellerId; mwsAuthTokenDictionary[row.AccountName] = row.MWSAuthToken; } } MarketplaceWebServiceOrdersConfig config = new MarketplaceWebServiceOrdersConfig(); config.ServiceURL = serviceURL; client = new MarketplaceWebServiceOrdersClient(accessKey, secretKey, appName, appVersion, config); MarketplaceWebServiceConfig mwsConfig = new MarketplaceWebServiceConfig(); mwsConfig.ServiceURL = serviceURL; mwsClient = new MarketplaceWebServiceClient(accessKey, secretKey, appName, appVersion, mwsConfig); }
public void RequestReportTest() { MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); config.ServiceURL = serviceURL; MarketplaceWebService.MarketplaceWebService service = new MarketplaceWebServiceClient( creds.AccessKey, creds.SecretKey, appName, appVersion, config); string reportType = "_GET_FLAT_FILE_ORDERS_DATA_"; RequestReportRequest request = new RequestReportRequest(); request.ReportType = reportType; request.Merchant = sellerId; request.MWSAuthToken = mWSAuthToken; // Optional //@TODO: set additional request parameters here RequestReportResponse response = service.RequestReport(request); Assert.IsTrue(response.RequestReportResult.ReportRequestInfo.ReportType == reportType); Console.WriteLine("GeneratedReportId: " + response.RequestReportResult.ReportRequestInfo.GeneratedReportId); }
public void GetFeedSubmissionResultTest() { MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); config.ServiceURL = serviceURL; MarketplaceWebService.MarketplaceWebService service = new MarketplaceWebServiceClient( creds.AccessKey, creds.SecretKey, appName, appVersion, config); GetFeedSubmissionResultRequest req = new GetFeedSubmissionResultRequest(); req.MWSAuthToken = mWSAuthToken; req.Merchant = sellerId; req.FeedSubmissionId = "50014017726"; //50003017583 //50002017580 var response = service.GetFeedSubmissionResultAmazonEnvelope(req); Console.WriteLine(response.Message.First().ProcessingReport.ProcessingSummary.MessagesSuccessful); Console.WriteLine(response.Message.First().ProcessingReport.ProcessingSummary.MessagesWithError); if (response.Message.First().ProcessingReport.Result != null) { Console.WriteLine(response.Message.First().ProcessingReport.Result.ResultCode); Console.WriteLine(response.Message.First().ProcessingReport.Result.ResultMessageCode); Console.WriteLine(response.Message.First().ProcessingReport.Result.ResultDescription); } }
static void Main(string[] args) { Console.WriteLine("Preparing application..."); string accessKeyId = "<Your AWS Access Key>"; string secretAccessKey = "<Your AWS Secret Key>"; string applicationName = "<Your Application Name>"; string applicationVersion = "<Your Application Version>"; string merchantId = "<Your Merchant ID>"; string marketplaceId = "<Your Marketplace ID>"; MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); config.ServiceURL = "https://mws.amazonservices.com"; Console.WriteLine("Contacting Amazon web services..."); config.SetUserAgentHeader( applicationName, applicationVersion, "C#", "<Parameter 1>", "<Parameter 2>"); MarketplaceWebService.MarketplaceWebService service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKey, config); Console.WriteLine("Service client created. Downloading settlement report..."); DownloadSettlementReport(service, merchantId); Console.Read(); }
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); }
public SubmitFeedController(MarketplaceWebServiceClient amazonClient, string marketplaceId, string merchantId, string submittedBy) { _amazonCient = amazonClient; _marketplaceId = marketplaceId; _merchantId = merchantId; _submittedBy = submittedBy; SleepFirst = true; }
private void InitMwsFeedClient() { var mwsConfig = new MarketplaceWebServiceConfig(); mwsConfig.SetUserAgentHeader( "Speadbot", "1.0", "C#" ); mwsConfig.ServiceURL = AmazonSettings.ServiceUrl; _mwsFeedClient = new MarketplaceWebServiceClient( AmazonSettings.AwsAccessKeyId, AmazonSettings.AwsSecretAccessKey, mwsConfig ); }
public AmazonMarketplaceReportProvider() { // create configuratin to use US marketplace var config = new MarketplaceWebServiceConfig { ServiceURL = RequestHelper.ServiceUrl }; config.SetUserAgentHeader("EIS Inventory System", "3.0", "C#"); _amazonClient = new MarketplaceWebServiceClient("AKIAJDQNAJIEJ2XZWVQA", "iRJplr+w2vZ1felGmV/OuUqOSreEyAx6c7o8nF3J", config); }
/// <summary> /// Default public contructor. All properties are set via the config file /// </summary> public AmazonIntegration() { // Verify that the settings in the config file are setup correctly. if (string.IsNullOrWhiteSpace(_AccessKeyId)) { throw new InvalidOperationException("AWSAccessKeyId setting in the config file can't be whitespace, blank or null"); } if (string.IsNullOrWhiteSpace(_SecretAccessKey)) { throw new InvalidOperationException("AWSSecretAccessKey setting in the config file can't be whitespace, blank or null"); } if (string.IsNullOrWhiteSpace(_ApplicationName)) { throw new InvalidOperationException("AWSApplicationName setting in the config file can't be whitespace, blank or null"); } if (string.IsNullOrWhiteSpace(_ApplicationVersion)) { throw new InvalidOperationException("AWSApplicationVersion setting in the config file can't be whitespace, blank or null"); } if (string.IsNullOrWhiteSpace(_MerchantId)) { throw new InvalidOperationException("AWSMerchantId setting in the config file can't be whitespace, blank or null"); } if (string.IsNullOrWhiteSpace(_MarketplaceId)) { throw new InvalidOperationException("AWSMarketplaceId setting in the config file can't be whitespace, blank or null"); } if (string.IsNullOrWhiteSpace(_TemporaryFileDirectory)) { throw new InvalidOperationException("TempFileDirectory setting in the config file can't be whitespace, blank or null"); } var config = new MarketplaceWebServiceConfig(); // Set configuration to use US marketplace config.ServiceURL = "https://mws.amazonservices.com"; // Set the HTTP Header for user agent for the application. config.SetUserAgentHeader( _ApplicationName, _ApplicationVersion, "C#"); _AmazonClient = new MarketplaceWebServiceClient(_AccessKeyId, _SecretAccessKey, config); // Setup the orders service client var ordersConfig = new MarketplaceWebServiceOrdersConfig(); ordersConfig.ServiceURL = "https://mws.amazonservices.com/Orders/2011-01-01"; ordersConfig.SetUserAgent(_ApplicationName, _ApplicationVersion); _AmazonOrdersClient = new MarketplaceWebServiceOrdersClient( _ApplicationName, _ApplicationVersion, _AccessKeyId, _SecretAccessKey, ordersConfig); }
/// <summary> /// Creates the SubmitFeedRequest given a stream of content /// </summary> /// <param name="dataContent">The stream of the content</param> /// <param name="feedType">The type of feed to be submitted.</param> /// <returns>A SubmitFeedRequest object</returns> private SubmitFeedRequest CreateSubmitFeedRequest(Stream dataContent, string feedType) { var request = new SubmitFeedRequest(); request.Merchant = _MerchantId; request.MarketplaceIdList = new IdList(); request.MarketplaceIdList.Id = new List <string>(new string[] { _MarketplaceId }); request.FeedContent = dataContent; // Set the MD5 hash of the content request.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent); // Reset the position of the reader of the FeedContent request.FeedType = feedType; return(request); }
public SubmitFeedRequest GetSubmitFeedRequest(AmazonFeedType feedType, FileStream feedContent) { var request = new SubmitFeedRequest() { Merchant = _amazonSellerSettings.SellerId, ContentType = new ContentType(MediaType.XML), FeedContent = feedContent, FeedType = feedType.ToString(), MarketplaceIdList = new IdList { Id = new List <string>(new[] { _amazonSellerSettings.MarketplaceId }) } }; request.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent); return(request); }
public AmazonReportController() { // init the reports directory _reportsDirectory = ConfigurationManager.AppSettings["ReportsPath"].ToString(); _merchantId = ConfigurationManager.AppSettings["MerchantId"].ToString(); _accessKeyId = ConfigurationManager.AppSettings["AccessKeyId"].ToString(); _secretAccessKey = ConfigurationManager.AppSettings["SecretAccessKey"].ToString(); // create configuratin to use US marketplace var config = new MarketplaceWebServiceConfig { ServiceURL = "https://mws.amazonservices.com" }; config.SetUserAgentHeader("EIS Reports Service", "3.0", "C#"); _amazonClient = new MarketplaceWebServiceClient(_accessKeyId, _secretAccessKey, config); }
public string Create() { var client = new MarketplaceWebServiceClient(_accessKey, _secretKey, new MarketplaceWebServiceConfig { ServiceURL = _serviceUrl }); var req = new Claytondus.AmazonMWS.Feeds.Model.SubmitFeedRequest(); req.Merchant = _merchantId; req.WithMarketplaceIdList(new Claytondus.AmazonMWS.Feeds.Model.IdList { Id = new List <string> { } }); var res = client.SubmitFeed(req); return(string.Empty); }
public string GetReport(string ReportId, string Path) { string amazonFileLocation = ""; GetReportRequest requestReport = new GetReportRequest(); #pragma warning disable CS0618 // Type or member is obsolete requestReport.Marketplace = api.MarketplaceId; #pragma warning restore CS0618 // Type or member is obsolete requestReport.Merchant = api.Merchant; requestReport.ReportId = ReportId; string Extension = string.Format("{1}{0}", ".txt", DateTime.Now.ToString("hh.mm.ss.ffffff")); string FullPath = Path + Extension; if (!File.Exists(FullPath)) { var stream = File.Create(FullPath); stream.Close(); } // string fileLocation = FileAmazon.createFile(reportId, "txt", ReportModule, ""); -> METHOD TO CREATE THE PATH if (FullPath != "") { var stream = File.Open(FullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite); requestReport.Report = stream; MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); config.ServiceURL = webService.SERVICE_URL; config.WithUserAgent(webService.USER_AGENT); MarketplaceWebServiceClient client = new MarketplaceWebServiceClient(api.AccessKey, api.SecretKey, config); InvokeGetReport(client, requestReport); stream.Close(); amazonFileLocation = FullPath; } return(amazonFileLocation); }
/// <summary> /// Create SubmitFeedRequest object with the specified XML file path and the type of the feed /// </summary> /// <param name="filePath">The full file path of the XML</param> /// <param name="feedType">The type of Amazon feed</param> /// <returns></returns> public static SubmitFeedRequest CreateSubmitFeedRequest(string filePath, AmazonFeedType feedType) { // create submit feed request var feedRequest = new SubmitFeedRequest { Merchant = MerchantId, MarketplaceIdList = new IdList { Id = MarketplaceIdList }, FeedType = feedType.ToString(), ContentType = new ContentType(MediaType.OctetStream), FeedContent = File.Open(filePath, FileMode.Open, FileAccess.Read) }; feedRequest.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5(feedRequest.FeedContent); return(feedRequest); }
public MwsProductsApi(string sellerId, string marketPlaceId, string accessKeyId, string secretAccessKeyId, string serviceUrl) { m_sellerId = sellerId; m_marketPlaceId = marketPlaceId; MarketplaceWebServiceProductsConfig config = new MarketplaceWebServiceProductsConfig { ServiceURL = serviceUrl }; m_productClient = new MarketplaceWebServiceProductsClient(string.Empty, string.Empty, accessKeyId, secretAccessKeyId, config); MarketplaceWebServiceConfig configService = new MarketplaceWebServiceConfig() .WithServiceURL("https://mws.amazonservices.com"); configService.SetUserAgentHeader(string.Empty, string.Empty, "C#"); m_service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKeyId, configService); }
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 MwsFeedsApi(string sellerId, string marketPlaceId, string accessKeyId, string secretAccessKeyId, string merchantIdentifier) { m_merchantId = sellerId; m_marketPlaceId = marketPlaceId; m_merchantId = sellerId; m_merchantIdentifier = merchantIdentifier; const string serviceUrl = "https://mws.amazonservices.com"; MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig { ServiceURL = serviceUrl }; config.ServiceURL = serviceUrl; config.SetUserAgentHeader("applicationName", "applicationVersion", "C#", "<Parameter 1>", "<Parameter 1>"); m_service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKeyId, config); }
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); }
/// <summary> /// Create SubmitFeedRequest given an XML file path and feed type /// </summary> /// <param name="xmlFilePath">The xml full file path</param> /// <param name="feedType">The type of feed to be submitted</param> /// <returns></returns> private SubmitFeedRequest createSubmitFeedRequest(string xmlFilePath, AmazonFeedType feedType) { // create submit feed request var feedRequest = new SubmitFeedRequest { Merchant = _merchantId, MarketplaceIdList = new IdList { Id = new List <string> { _marketplaceId } }, FeedType = feedType.ToString(), ContentType = new ContentType(MediaType.OctetStream), FeedContent = File.Open(xmlFilePath, FileMode.Open, FileAccess.ReadWrite) }; feedRequest.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5(feedRequest.FeedContent); return(feedRequest); }
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); } }
public void GetReportCountTest() { MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); config.ServiceURL = serviceURL; MarketplaceWebService.MarketplaceWebService service = new MarketplaceWebServiceClient( creds.AccessKey, creds.SecretKey, appName, appVersion, config); GetReportCountRequest request = new GetReportCountRequest(); request.Merchant = sellerId; request.MWSAuthToken = ""; // Optional //@TODO: set additional request parameters here GetReportCountResponse response = service.GetReportCount(request); }
/// <param name="region">The region of the account. Required parameter. A finer grained region or country can be specified on a PropertiesContainer by specifying its marketplaceIdList constructor argument.</param> /// <param name="merchantId">Seller ID / Merchant ID. Required parameter.</param> /// <param name="accessKeyId">Amazon account access key. Required parameter. This key can either belong to a seller or to a developer account authorized by a seller. If the key belongs to a developer account authorized by the seller then also make sure to specify the MWSAuthToken argument.</param> /// <param name="mwsSecretAccessKey">Amazon account secret access key. Required parameter. This key can either belong to a seller or to a developer account authorized by a seller. If the key belongs to a developer account authorized by the seller then also make sure to specify the MWSAuthToken argument.</param> /// <param name="mwsAuthToken">MWS Authorization Token. Optional parameter. If the provided access keys belong to a developer account authorized by a seller, this argument is the MWS Authorization Token provided by the seller to the authorized developer.</param> /// <param name="easyMwsLogger">An optional IEasyMwsLogger instance that can provide access to logs. It is strongly recommended to use a logger implementation already existing in the EasyMws package.</param> /// <param name="options">Configuration options for EasyMwsClient</param> public EasyMwsClient(AmazonRegion region, string merchantId, string accessKeyId, string mwsSecretAccessKey, string mwsAuthToken = null, IEasyMwsLogger easyMwsLogger = null, EasyMwsOptions options = null) { if (string.IsNullOrEmpty(merchantId) || string.IsNullOrEmpty(accessKeyId) || string.IsNullOrEmpty(mwsSecretAccessKey)) { throw new ArgumentNullException( "One or more required parameters provided to initialize the EasyMwsClient were null or empty"); } _amazonRegion = region; _merchantId = merchantId; _options = options ?? new EasyMwsOptions(); _easyMwsLogger = easyMwsLogger ?? new EasyMwsLogger(isEnabled: false); var mwsClient = new MarketplaceWebServiceClient(accessKeyId, mwsSecretAccessKey, CreateConfig(_amazonRegion)); _reportProcessor = _reportProcessor ?? new ReportProcessor(_amazonRegion, _merchantId, mwsAuthToken, _options, mwsClient, _easyMwsLogger); _feedProcessor = _feedProcessor ?? new FeedProcessor(_amazonRegion, _merchantId, mwsAuthToken, _options, mwsClient, _easyMwsLogger); RegisterEvents(); }
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 string RequestReport(string Type, DateTime From, DateTime To) { try { RequestReportRequest requestReport = new RequestReportRequest(); #pragma warning disable CS0618 // Type or member is obsolete requestReport.Marketplace = api.MarketplaceId; #pragma warning restore CS0618 // Type or member is obsolete requestReport.Merchant = api.Merchant; requestReport.StartDate = From; requestReport.EndDate = To; requestReport.ReportOptions = "true"; IdList idList = new IdList(); idList.Id = new List <string>() { api.MarketplaceId }; requestReport.MarketplaceIdList = idList; requestReport.ReportType = Type; MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); config.ServiceURL = webService.SERVICE_URL; config.WithUserAgent(webService.USER_AGENT); MarketplaceWebServiceClient client = new MarketplaceWebServiceClient(api.AccessKey, api.SecretKey, config); return(InvokeRequestReport(client, requestReport)); } catch (Exception ex) { return(ex.Message); } }
public void UpdateOurPrices(IEnumerable <UpdatedItemPrice> newPrices) { SubmitFeedRequest request = new SubmitFeedRequest { Merchant = m_merchantId, MarketplaceIdList = new IdList { Id = new List <string>(new[] { m_marketPlaceId }) } }; // This chunk of code takes our queue, writes the formatted xml string needed, deletes the queue. // Puts the xml string into a temporary stream, and makes the request to Amazon. string newPricesXmlString = ConstructXmlFile(newPrices); byte[] byteArray = Encoding.ASCII.GetBytes(newPricesXmlString); request.FeedContent = new MemoryStream(byteArray); request.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent); request.FeedType = "_POST_PRODUCT_PRICING_DATA_"; InvokeSubmitFeed(request); // No memory leaks? I think this is unnecessary. request.FeedContent.Close(); }
private static string AdlsAccountName = ""; // Name of the Azure Data Lake Store static void Main(string[] args) { // Fetching Prerequisites Data from Azure SQL Server using (SqlConnection con = new SqlConnection(connectionString)) { // Fetching data from Report Config Table SqlCommand cmd = new SqlCommand("USE CommerceLabsDW;OPEN SYMMETRIC KEY SymmetricKey1 DECRYPTION BY CERTIFICATE Certificate1; SELECT CONVERT(varchar(max), DECRYPTBYKEY(SellerCentral_LoginID)), CONVERT(varchar(max), DECRYPTBYKEY(SellerCentral_LoginPWD)), CONVERT(varchar(max), DECRYPTBYKEY(ADS_RefreshToken)), CONVERT(varchar(max), DECRYPTBYKEY(ADS_ClientID)), CONVERT(varchar(max), DECRYPTBYKEY(ADS_ClientSecret)), CONVERT(varchar(max), DECRYPTBYKEY(ADS_Scope)), CONVERT(varchar(max), DECRYPTBYKEY(WP_Authorization)), CONVERT(varchar(max), DECRYPTBYKEY(MWS_AccessID)), CONVERT(varchar(max), DECRYPTBYKEY(MWS_SecretKey)), CONVERT(varchar(max), DECRYPTBYKEY(MWS_MerchantID)), CONVERT(varchar(max), DECRYPTBYKEY(MWS_AuthToken)), CONVERT(varchar(max), DECRYPTBYKEY(Azure_ClientID)), CONVERT(varchar(max), DECRYPTBYKEY(Azure_ClientSecret)), CONVERT(varchar(max), DECRYPTBYKEY(Azure_TenantID)), CONVERT(varchar(max), DECRYPTBYKEY(Azure_DataLakeName)) FROM stage.rpt_ConfigTable WHERE ID = 1; ", con); //Opening the Connection con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { SC_LoginID = reader.GetString(0); SC_LoginPwd = reader.GetString(1); ADS_RefreshToken = reader.GetString(2); ADS_ClientID = reader.GetString(3); ADS_ClientSecret = reader.GetString(4); ADS_Scope = reader.GetString(5); WP_Authorization = reader.GetString(6); MWS_AccessID = reader.GetString(7); MWS_SecretKey = reader.GetString(8); MWS_MerchantID = reader.GetString(9); MWS_AuthToken = reader.GetString(10); AzureClientId = reader.GetString(11); AzureClientSecret = reader.GetString(12); AzureTenantId = reader.GetString(13); AdlsAccountName = reader.GetString(14); } //Closing the Connection con.Close(); } // Azure Data Lake Initialisation SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); var clientCredential = new ClientCredential(AzureClientId, AzureClientSecret); var creds = ApplicationTokenProvider.LoginSilentAsync(AzureTenantId, clientCredential).Result; adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds); string Azuresource = "", Azuredestination = ""; // Azure Source and Destination Variable // Creating a Folder in the App Path var directoryFullPath = AppDomain.CurrentDomain.BaseDirectory + @"DownloadedReports\"; // Creating a Folder in Current Directory if not exists Directory.CreateDirectory(directoryFullPath); // Web Driver Object IWebDriver driver; // Setting the needed Chrome Options ChromeOptions options = new ChromeOptions(); options.AddUserProfilePreference("download.default_directory", directoryFullPath); // Setting the default directory for the report to be downloaded options.AddUserProfilePreference("intl.accept_languages", "en-us"); // Setting the language as English // options.AddArgument("--headless"); // Setting headless browser option driver = new ChromeDriver(options); // Assigning all the above options to Chrome Driver Console.WriteLine("Started"); // Amazon Seller Central Login Page driver.Navigate().GoToUrl("https://sellercentral.amazon.com/"); driver.FindElement(By.ClassName("secondary")).Click(); driver.FindElement(By.Id("ap_email")).SendKeys(SC_LoginID); driver.FindElement(By.Id("ap_password")).SendKeys(SC_LoginPwd); driver.FindElement(By.Id("signInSubmit")).Click(); /*// Generating OTP * var otpKeyStr = "WGHSYZEE2RJOO6OFMCBMB6HKNHDZRADH4TK2FDJ77YWQ5YFRWDBQ"; // 2FA secret key. * var otpKeyBytes = Base32Encoding.ToBytes(otpKeyStr); * var totp = new Totp(otpKeyBytes); * var twoFactorCode = totp.ComputeTotp(DateTime.UtcNow); // 2FA code at this time! * Console.WriteLine(twoFactorCode);*/ // OTP Console.WriteLine("Please enter the OTP : "); var input = Console.ReadLine(); driver.FindElement(By.Id("auth-mfa-otpcode")).SendKeys(input); driver.FindElement(By.Id("auth-mfa-remember-device")).Click(); driver.FindElement(By.Id("auth-signin-button")).Click(); // ------------------ REPORT 1 ------------------ // ---- Automating Scraping Method ----- // Downloading Business Report driver.Navigate().GoToUrl("https://sellercentral.amazon.com/gp/site-metrics/report.html#reportID=102%3ADetailSalesTrafficBySKU&runDate=&fromDate=&toDate="); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1000); Thread.Sleep(1000); // Downloading Past 3 Days' Reports by looping through dates for (int i = -1; i > -4; i--) { // Looping through Dates and setting the Date Value var DateValue = DateTime.Now.AddDays(i).ToString("MM/dd/yyyy").Replace("-", "/"); // Setting From Date IWebElement FromDateBox = driver.FindElement(By.Id("fromDate2")); FromDateBox.Clear(); FromDateBox.SendKeys(DateValue + Keys.Enter); // Setting To Date IWebElement ToDateBox = driver.FindElement(By.Id("toDate2")); ToDateBox.Clear(); ToDateBox.SendKeys(DateValue + Keys.Enter); // Downloading the Report Thread.Sleep(1000); driver.FindElement(By.Id("export")).Click(); Thread.Sleep(1000); driver.FindElement(By.Id("downloadCSV")).Click(); Thread.Sleep(1000); // Editing the Business Report CSV string BusRepfilePath = directoryFullPath + "BusinessReport-" + DateTime.Now.AddDays(-1).ToString("MM/dd/yy") + ".csv"; Thread.Sleep(1000); // Transaction Date var Buscol1 = File.ReadLines(BusRepfilePath).Select((line, index) => index == 0 ? line + ", Transaction Date" : line + "," + DateValue.Replace("/", "-")).ToList(); File.WriteAllLines(BusRepfilePath, Buscol1); // Account var Buscol2 = File.ReadLines(BusRepfilePath).Select((line, index) => index == 0 ? line + ",Account" : line + ",Meal Prep Haven").ToList(); File.WriteAllLines(BusRepfilePath, Buscol2); // Country var Buscol3 = File.ReadLines(BusRepfilePath).Select((line, index) => index == 0 ? line + ",Country" : line + ",US").ToList(); File.WriteAllLines(BusRepfilePath, Buscol3); // Reference URL var Buscol4 = File.ReadLines(BusRepfilePath).Select((line, index) => index == 0 ? line + ",Reference" : line + "," + driver.Url).ToList(); File.WriteAllLines(BusRepfilePath, Buscol4); // Renaming the Report File File.Move(BusRepfilePath, directoryFullPath + "BusinessReport" + i + ".csv"); } // Combining all the CSV Files into 1 string BussourceFolder = directoryFullPath; string BusdestinationFile = directoryFullPath + "BusinessReport-" + DateTime.Now.ToString("dd/MM/yyyy") + ".csv"; // Matches the CSV files by searching the specified wildcard and combines them to single file string[] filePaths = Directory.GetFiles(BussourceFolder, "BusinessReport-?.csv"); StreamWriter fileDest = new StreamWriter(BusdestinationFile, true); for (int j = 0; j < filePaths.Length; j++) { string file = filePaths[j]; string[] lines = File.ReadAllLines(file); if (j > 0) { lines = lines.Skip(1).ToArray(); // Skipping Header row for all except first file } foreach (string line in lines) { fileDest.WriteLine(line); } } fileDest.Close(); // Uploading Business Report to Azure Data Lake Azuresource = directoryFullPath + @"BusinessReport-" + DateTime.Now.ToString("dd/MM/yyyy") + ".csv"; Azuredestination = "Meal prep haven/CA_AO/Business Reports/" + "BusinessReport-" + DateTime.Now.ToString("dd/MM/yyyy") + ".csv"; adlsFileSystemClient.FileSystem.UploadFile(AdlsAccountName, Azuresource, Azuredestination, 1, false, true); Console.WriteLine("Uploaded Business Report"); // Deleting the Business Report Files Array.ForEach(Directory.GetFiles(directoryFullPath), File.Delete); // ------------------ REPORT 2 ------------------ // ---- Automating Scraping Method ---- // Downloading Reserved Inventory Report driver.Navigate().GoToUrl("https://sellercentral.amazon.com/gp/ssof/reports/search.html#orderAscending=&recordType=ReserveBreakdown&noResultType=&merchantSku=&fnSku=&FnSkuXORMSku=&reimbursementId=&orderId=&genericOrderId=&asin=&lpn=&shipmentId=&problemType=ALL_DEFECT_TYPES&hazmatStatus=&inventoryEventTransactionType=&fulfillmentCenterId=&transactionItemId=&inventoryAdjustmentReasonGroup=&eventDateOption=1&fromDate=mm%2Fdd%2Fyyyy&toDate=mm%2Fdd%2Fyyyy&startDate=&endDate=&fromMonth=1&fromYear=2019&toMonth=1&toYear=2019&startMonth=&startYear=&endMonth=&endYear=&specificMonth=1&specificYear=2019"); Thread.Sleep(1000); driver.FindElement(By.XPath("//*[@id=\"requestCsvTsvDownload\"]/tr[1]/td[2]/button")).Click(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1000); Thread.Sleep(10000); driver.FindElement(By.XPath("//*[@id=\"downloadArchive\"]/table/tbody/tr[1]/td[5]/a")).Click(); // Editing the Reserved Inventory CSV // Appending Columns and Values in Existing CSV File string ResRepfilePath = ""; foreach (string filename in Directory.GetFiles(directoryFullPath)) { ResRepfilePath = directoryFullPath + Path.GetFileName(filename); // Getting the File Name } // Account var Rescol1 = File.ReadLines(ResRepfilePath).Select((line, index) => index == 0 ? line + ",Account" : line + ",Meal Prep Haven").ToList(); File.WriteAllLines(ResRepfilePath, Rescol1); // Country var Rescol2 = File.ReadLines(ResRepfilePath).Select((line, index) => index == 0 ? line + ",Country" : line + ",US").ToList(); File.WriteAllLines(ResRepfilePath, Rescol2); // Reference URL var Rescol3 = File.ReadLines(ResRepfilePath).Select((line, index) => index == 0 ? line + ",Reference" : line + "," + driver.Url).ToList(); File.WriteAllLines(ResRepfilePath, Rescol3); // Transaction Date var Rescol4 = File.ReadLines(ResRepfilePath).Select((line, index) => index == 0 ? line + ", Transaction Date" : line + "," + DateTime.Now.ToString("MM/dd/yyyy")).ToList(); File.WriteAllLines(ResRepfilePath, Rescol4); // Renaming the Report File File.Move(ResRepfilePath, directoryFullPath + "ReservedInventoryReport.csv"); // Uploading Reserved Inventory Report to Azure Data Lake Azuresource = directoryFullPath + "ReservedInventoryReport.csv"; Azuredestination = "Meal prep haven/CA_AO/Reserved Inventory Reports/" + "ReservedInventoryReport-" + DateTime.Now.ToString("dd/MM/yyyy") + ".csv"; adlsFileSystemClient.FileSystem.UploadFile(AdlsAccountName, Azuresource, Azuredestination, 1, false, true); Console.WriteLine("Uploaded Reserved Inventory Report"); // Deleting the Reserved Inventory Report File Array.ForEach(Directory.GetFiles(directoryFullPath), File.Delete); // ------------------ REPORT 3 ------------------ // ---- Automating Scraping Method ---- // Downloading Managed Inventory Report driver.Navigate().GoToUrl("https://sellercentral.amazon.com/gp/ssof/reports/search.html?#orderAscending=&recordType=FBA_MYI_UNSUPPRESSED_INVENTORY&noResultType=&merchantSku=&fnSku=&FnSkuXORMSku=&reimbursementId=&orderId=&genericOrderId=&asin=&lpn=&shipmentId=&problemType=ALL_DEFECT_TYPES&hazmatStatus=&inventoryEventTransactionType=&fulfillmentCenterId=&transactionItemId=&inventoryAdjustmentReasonGroup=&eventDateOption=1&fromDate=mm%2Fdd%2Fyyyy&toDate=mm%2Fdd%2Fyyyy&startDate=&endDate=&fromMonth=1&fromYear=2019&toMonth=1&toYear=2019&startMonth=&startYear=&endMonth=&endYear=&specificMonth=1&specificYear=2019"); Thread.Sleep(1000); driver.FindElement(By.XPath("//*[@id=\"requestCsvTsvDownload\"]/tr[1]/td[2]/button")).Click(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1000); Thread.Sleep(10000); driver.FindElement(By.XPath("//*[@id=\"downloadArchive\"]/table/tbody/tr[1]/td[5]/a")).Click(); // Editing the Managed Inventory CSV // Appending Columns and Values in Existing CSV File string ManRepfilePath = ""; foreach (string filename in Directory.GetFiles(directoryFullPath)) { ManRepfilePath = directoryFullPath + Path.GetFileName(filename); // Getting the File Name } // Account var Mancol1 = File.ReadLines(ManRepfilePath).Select((line, index) => index == 0 ? line + ",Account" : line + ",Meal Prep Haven").ToList(); File.WriteAllLines(ManRepfilePath, Mancol1); // Country var Mancol2 = File.ReadLines(ManRepfilePath).Select((line, index) => index == 0 ? line + ",Country" : line + ",US").ToList(); File.WriteAllLines(ManRepfilePath, Mancol2); // Reference URL var Mancol3 = File.ReadLines(ManRepfilePath).Select((line, index) => index == 0 ? line + ",Reference" : line + "," + driver.Url).ToList(); File.WriteAllLines(ManRepfilePath, Mancol3); // Transaction Date var Mancol4 = File.ReadLines(ManRepfilePath).Select((line, index) => index == 0 ? line + ", Transaction Date" : line + "," + DateTime.Now.ToString("MM/dd/yyyy")).ToList(); File.WriteAllLines(ManRepfilePath, Mancol4); // Renaming the Report File File.Move(ManRepfilePath, directoryFullPath + "ManagedInventoryReport.csv"); // Uploading Reserved Inventory Report to Azure Data Lake Azuresource = directoryFullPath + "ManagedInventoryReport.csv"; Azuredestination = "Meal prep haven/CA_AO/Managed Inventory Reports/" + "ManagedInventoryReport-" + DateTime.Now.ToString("dd/MM/yyyy") + ".csv"; adlsFileSystemClient.FileSystem.UploadFile(AdlsAccountName, Azuresource, Azuredestination, 1, false, true); Console.WriteLine("Uploaded Managed Inventory Report"); // Deleting the Managed Inventory Report File Array.ForEach(Directory.GetFiles(directoryFullPath), File.Delete); // ------------------ REPORT 4 ------------------ // ---- Automating Scraping Method ---- // Downloading Payment Report driver.Navigate().GoToUrl("https://sellercentral.amazon.com/payments/reports/custom/request?tbla_daterangereportstable=sort:%7B%22sortOrder%22%3A%22DESCENDING%22%7D;search:undefined;pagination:1;"); Thread.Sleep(1000); driver.FindElement(By.XPath("//*[@id=\"drrGenerateReportButton\"]/span/input")).Click(); driver.FindElement(By.XPath("//*[@id=\"drrReportTypeRadioTransaction\"]")).Click(); driver.FindElement(By.XPath("//*[@id=\"drrReportRangeTypeRadioCustom\"]")).Click(); driver.FindElement(By.XPath("//*[@id=\"drrFromDate\"]")).SendKeys(DateTime.Now.AddDays(-2).ToString("MM/dd/yyyy").Replace("-", "/") + Keys.Enter); driver.FindElement(By.XPath("//*[@id=\"drrToDate\"]")).SendKeys(DateTime.Now.AddDays(-2).ToString("MM/dd/yyyy").Replace("-", "/") + Keys.Enter); driver.FindElement(By.XPath("//*[@id=\"drrGenerateReportsGenerateButton\"]/span/input")).Click(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1000); driver.FindElement(By.ClassName("drrRefreshTable")).Click(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1000); Thread.Sleep(10000); driver.FindElement(By.XPath("//*[@id=\"downloadButton\"]")).Click(); // Editing the Payment CSV // Appending Columns and Values in Existing CSV File string PayRepfilePath = ""; foreach (string filename in Directory.GetFiles(directoryFullPath)) { PayRepfilePath = directoryFullPath + Path.GetFileName(filename); // Getting the File Name } // Account var Paycol1 = File.ReadLines(PayRepfilePath).Select((line, index) => index == 0 ? line + ",Account" : line + ",Meal Prep Haven").ToList(); File.WriteAllLines(PayRepfilePath, Paycol1); // Country var Paycol2 = File.ReadLines(PayRepfilePath).Select((line, index) => index == 0 ? line + ",Country" : line + ",US").ToList(); File.WriteAllLines(PayRepfilePath, Paycol2); // Reference URL var Paycol3 = File.ReadLines(PayRepfilePath).Select((line, index) => index == 0 ? line + ",Reference" : line + ",https://sellercentral.amazon.com/payments/reports/custom/request?tbla_daterangereportstable=sort:%7B%22sortOrder%22%3A%22DESCENDING%22%7D;search:undefined;pagination:1;").ToList(); //+ driver.Url).ToList(); File.WriteAllLines(PayRepfilePath, Paycol3); // Renaming the Report File File.Move(PayRepfilePath, directoryFullPath + "PaymentReport.csv"); // Uploading Payment Report to Azure Data Lake Azuresource = directoryFullPath + "PaymentReport.csv"; Azuredestination = "Meal prep haven/CA_AO/Payment Reports/" + "PaymentReport-17-10-2019.csv"; //+ DateTime.Now.ToString("dd/MM/yyyy") + ".csv"; adlsFileSystemClient.FileSystem.UploadFile(AdlsAccountName, Azuresource, Azuredestination, 1, false, true); Console.WriteLine("Uploaded Payment Report"); // Deleting the Payment Report File Array.ForEach(Directory.GetFiles(directoryFullPath), File.Delete); // ------------------ REPORT 5 ------------------ // ---- Automating Scraping Method ---- // Downloading Storage Fees Report driver.Navigate().GoToUrl("https://sellercentral.amazon.com/gp/ssof/reports/search.html#orderAscending=&recordType=STORAGE_FEE_CHARGES&noResultType=&merchantSku=&fnSku=&FnSkuXORMSku=&reimbursementId=&orderId=&genericOrderId=&asin=&lpn=&shipmentId=&problemType=ALL_DEFECT_TYPES&hazmatStatus=&inventoryEventTransactionType=&fulfillmentCenterId=&transactionItemId=&inventoryAdjustmentReasonGroup=&eventDateOption=1&fromDate=mm%2Fdd%2Fyyyy&toDate=mm%2Fdd%2Fyyyy&startDate=&endDate=&fromMonth=1&fromYear=2019&toMonth=1&toYear=2019&startMonth=&startYear=&endMonth=&endYear=&specificMonth=1&specificYear=2019"); Thread.Sleep(1000); driver.FindElement(By.XPath("//*[@id=\"specificMonthDownload\"]/option[9]")).Click(); driver.FindElement(By.XPath("//*[@id=\"specificYearDownload\"]/option[1]")).Click(); driver.FindElement(By.XPath("//*[@id=\"requestCsvTsvDownload\"]/tr[1]/td[2]/button")).Click(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(4000); Thread.Sleep(10000); driver.FindElement(By.XPath("//*[@id=\"downloadArchive\"]/table/tbody/tr[1]/td[5]/a")).Click(); // Editing the Storage Fees CSV // Appending Columns and Values in Existing CSV File string StoRepfilePath = ""; foreach (string filename in Directory.GetFiles(directoryFullPath)) { StoRepfilePath = directoryFullPath + Path.GetFileName(filename); // Getting the File Name } // Account var Stocol1 = File.ReadLines(StoRepfilePath).Select((line, index) => index == 0 ? line + ",Account" : line + ",Meal Prep Haven").ToList(); File.WriteAllLines(StoRepfilePath, Stocol1); // Country var Stocol2 = File.ReadLines(StoRepfilePath).Select((line, index) => index == 0 ? line + ",Country" : line + ",US").ToList(); File.WriteAllLines(StoRepfilePath, Stocol2); // Reference URL var Stocol3 = File.ReadLines(StoRepfilePath).Select((line, index) => index == 0 ? line + ",Reference" : line + "," + driver.Url).ToList(); File.WriteAllLines(StoRepfilePath, Stocol3); // Transaction Date var Stocol4 = File.ReadLines(StoRepfilePath).Select((line, index) => index == 0 ? line + ", Transaction Date" : line + "," + DateTime.Now.ToString("MM/dd/yyyy")).ToList(); File.WriteAllLines(StoRepfilePath, Stocol4); // Renaming the Report File File.Move(StoRepfilePath, directoryFullPath + "StorageFeesReport.csv"); // Uploading Storage Fees Report to Azure Data Lake Azuresource = directoryFullPath + "StorageFeesReport.csv"; Azuredestination = "Meal prep haven/CA_AO/Storage Fees Reports/" + "StorageFeesReport-" + DateTime.Now.ToString("dd/MM/yyyy") + ".csv"; adlsFileSystemClient.FileSystem.UploadFile(AdlsAccountName, Azuresource, Azuredestination, 1, false, true); Console.WriteLine("Uploaded Storage Fees Report"); // Deleting the Storage Fees Report File Array.ForEach(Directory.GetFiles(directoryFullPath), File.Delete); // ------------------ REPORT 6 ------------------ // ---- API Method ---- // Downloading Amazon ADS Product Report through API // Refreshing Access Token var client1 = new RestClient("https://api.amazon.com/auth/o2/token"); var request1 = new RestRequest(Method.POST); request1.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request1.AddParameter("grant_type", "refresh_token"); request1.AddParameter("refresh_token", ADS_RefreshToken); request1.AddParameter("client_id", ADS_ClientID); request1.AddParameter("client_secret", ADS_ClientSecret); IRestResponse response1 = client1.Execute(request1); dynamic result1 = JsonConvert.DeserializeObject(response1.Content); string ADS_AccessToken = result1.access_token; // Getting the Report ID var client2 = new RestClient("https://advertising-api.amazon.com/v2/sp/productAds/report"); var request2 = new RestRequest(Method.POST); request2.AddHeader("Content-Type", "application/json"); request2.AddHeader("Authorization", "Bearer " + ADS_AccessToken); request2.AddHeader("Amazon-Advertising-API-ClientId", ADS_ClientID); request2.AddHeader("Amazon-Advertising-API-Scope", ADS_Scope); request2.AddParameter("undefined", "{\"reportDate\":\"20190930\", \"metrics\":\"campaignName,campaignId,adGroupName,adGroupId,currency,asin,sku,impressions,clicks,cost,attributedConversions1d,attributedConversions7d,attributedConversions14d,attributedConversions30d,attributedConversions1dSameSKU,attributedConversions7dSameSKU,attributedConversions14dSameSKU,attributedConversions30dSameSKU,attributedUnitsOrdered1d,attributedUnitsOrdered7d,attributedUnitsOrdered14d,attributedUnitsOrdered30d,attributedSales1d,attributedSales7d,attributedSales14d,attributedSales30d,attributedSales1dSameSKU,attributedSales7dSameSKU,attributedSales14dSameSKU,attributedSales30dSameSKU\"}", ParameterType.RequestBody); IRestResponse response2 = client2.Execute(request2); dynamic result2 = JsonConvert.DeserializeObject(response2.Content); string ReportID = result2.reportId; Thread.Sleep(3000); // Retrieving the Report Status var client3 = new RestClient("https://advertising-api.amazon.com/v2/reports/" + ReportID); var request3 = new RestRequest(Method.GET); request3.AddHeader("Content-Type", "application/json"); request3.AddHeader("Authorization", "Bearer " + ADS_AccessToken); request3.AddHeader("Amazon-Advertising-API-ClientId", ADS_ClientID); request3.AddHeader("Amazon-Advertising-API-Scope", ADS_Scope); IRestResponse response3 = client3.Execute(request3); dynamic result3 = JsonConvert.DeserializeObject(response3.Content); string DownloadLocation = result3.location; if (result3.status == "SUCCESS") { // Retrieving Report Download URL var client4 = new RestClient(DownloadLocation); var request4 = new RestRequest(Method.GET); request4.AddHeader("Authorization", "Bearer " + ADS_AccessToken); request4.AddHeader("Amazon-Advertising-API-Scope", ADS_Scope); IRestResponse response4 = client4.Execute(request4); string DownloadURL = response4.ResponseUri.ToString(); // Downloading the Report driver.Navigate().GoToUrl(DownloadURL); } // Extracting .gz Zip file DirectoryInfo directorySelected = new DirectoryInfo(directoryFullPath); foreach (FileInfo fileToDecompress in directorySelected.GetFiles("*.gz")) { Decompress(fileToDecompress); } // Uploading Amazon ADS Product Report to Azure Data Lake Azuresource = directoryFullPath + "ADSProductReport.json"; Azuredestination = "Meal prep haven/CA_AO/Advertised Product Reports/" + "AmazonADSProductReport-" + DateTime.Now.ToString("dd/MM/yyyy") + ".json"; adlsFileSystemClient.FileSystem.UploadFile(AdlsAccountName, Azuresource, Azuredestination, 1, false, true); Console.WriteLine("Uploaded Amazon ADS Product Report"); // Deleting the Amazon ADS Product Report File Array.ForEach(Directory.GetFiles(directoryFullPath), File.Delete); // ------------------ REPORT 7 ------------------ // ---- API Method ---- // Downloading WorldPack Report through API // Getting the Access Token var clientw1 = new RestClient("http://secure-wms.com/AuthServer/api/Token"); var requestw1 = new RestRequest(Method.POST); requestw1.AddHeader("Content-Type", "application/json; charset=utf-8"); requestw1.AddHeader("Accept", "application/json"); requestw1.AddHeader("Authorization", "Basic " + WP_Authorization); requestw1.AddParameter("undefined", "{\"grant_type\": \"client_credentials\",\"tpl\": \"{1ddbea91-a4ff-4b42-a25d-81a25b8cb727}\",\"user_login_id\": \"759\"}", ParameterType.RequestBody); IRestResponse responsew1 = clientw1.Execute(requestw1); dynamic resultw1 = JsonConvert.DeserializeObject(responsew1.Content); string WP_AccessToken = resultw1.access_token; // Getting the Inventory Details var clientw2 = new RestClient("https://secure-wms.com/inventory/stockdetails?customerid=194&facilityid=4"); var requestw2 = new RestRequest(Method.GET); requestw2.AddHeader("Content-Type", "application/hal+json; charset=utf-8"); requestw2.AddHeader("Accept", "application/hal+json"); requestw2.AddHeader("Authorization", "Bearer " + WP_AccessToken); IRestResponse responsew2 = clientw2.Execute(requestw2); dynamic resultw2 = JsonConvert.DeserializeObject(responsew2.Content); string jsonstr = resultw2._embedded.ToString(); // Uploading WorldPack Report to Azure Data Lake Azuresource = directoryFullPath + "WorldPackReport.json"; Azuredestination = "Third Party Reports/WorldPack Reports/" + "WorldPackReport-" + DateTime.Now.ToString("dd/MM/yyyy") + ".json"; adlsFileSystemClient.FileSystem.UploadFile(AdlsAccountName, Azuresource, Azuredestination, 1, false, true); Console.WriteLine("Uploaded World Pack Report"); // Deleting the Amazon ADS Product Report File Array.ForEach(Directory.GetFiles(directoryFullPath), File.Delete); // ------------------ REPORT 8 ------------------ // ---- API Method ---- // Downloading Amazon MWS Reports - FBA_StorageFees Report through API string accessKeyId = MWS_AccessID; string secretAccessKey = MWS_SecretKey; MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); config.ServiceURL = "https://mws.amazonservices.com"; const string applicationName = "ApplicationName"; const string applicationVersion = "0.1a"; MarketplaceWebServiceClient service = new MarketplaceWebServiceClient( accessKeyId, secretAccessKey, applicationName, applicationVersion, config); string merchantID = MWS_MerchantID; string mwsauthtoken = MWS_AuthToken; // Requesting the Report RequestReportRequest reportRequest = new RequestReportRequest(); reportRequest.Merchant = merchantID; reportRequest.MWSAuthToken = mwsauthtoken; reportRequest.ReportType = "_GET_FBA_STORAGE_FEE_CHARGES_DATA_"; reportRequest.StartDate = DateTime.Parse(DateTime.Now.AddMonths(-1).ToString("dd/MM/yyyy")); reportRequest.EndDate = DateTime.Now; reportRequest.ReportOptions = "true"; //shows sales channel to certain reports // Handling the Response of RequestReport RequestReportResponse reportResponse = service.RequestReport(reportRequest); Thread.Sleep(30000); //sleep for 30 seconds to allow report request to generate prior to requesting the reportRequestID string requestID = reportResponse.RequestReportResult.ReportRequestInfo.ReportRequestId; string reportStatus = ""; // holds the status of the report // Getting the Report Request List GetReportRequestListRequest reportRequestList = new GetReportRequestListRequest(); reportRequestList.Merchant = merchantID; reportRequestList.MWSAuthToken = mwsauthtoken; // Handling the Response of Report Request List GetReportRequestListResponse reportRequestListReponse = service.GetReportRequestList(reportRequestList); foreach (ReportRequestInfo info in reportRequestListReponse.GetReportRequestListResult.ReportRequestInfo) { if (info.ReportRequestId.Equals(requestID)) { reportStatus = info.ReportProcessingStatus; if (reportStatus == "_DONE_") { // Getting the Report using Report ID GetReportRequest getReport = new GetReportRequest(); getReport.ReportId = info.GeneratedReportId; getReport.Merchant = merchantID; getReport.MWSAuthToken = mwsauthtoken; // Writting the Report as a File string filename = Path.Combine(directoryFullPath, "FBA_StorageFeesReport-" + DateTime.Now.ToString("dd/MM/yyyy") + ".csv"); getReport.Report = File.Open(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite); GetReportResponse report_response = service.GetReport(getReport); Console.WriteLine("Sleeping for 1 minute to allow processes to settle. "); Thread.Sleep(60000); getReport.Report.Close(); // Uploading FBA Storage Fees to Azure Data Lake Azuresource = filename; Azuredestination = "Amazon MWS Reports/" + "FBA_StorageFeesReport-" + System.DateTime.Now.ToString("dd/MM/yyyy") + ".csv"; adlsFileSystemClient.FileSystem.UploadFile(AdlsAccountName, Azuresource, Azuredestination, 1, false, true); Console.WriteLine("Uploaded Amazon MWS FBA_StorageFees Report"); break; } } else { continue; // Only concerning about the requested report, not all the reports being generated } } // Closing the Browser driver.Quit(); }
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); }
private void DownloadSalesData() { this.StatusDescription = string.Format("Creating MWS client"); // Set up MWS client string accessKey = System.Configuration.ConfigurationManager.AppSettings["MwsAccK"]; string secretKey = System.Configuration.ConfigurationManager.AppSettings["MwsSecK"]; string sellerId = System.Configuration.ConfigurationManager.AppSettings["MwsSeller"]; string marketplaceId = System.Configuration.ConfigurationManager.AppSettings["MwsMktpl"]; MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); config.ServiceURL = "https://mws.amazonservices.com "; config.SetUserAgentHeader("CMA", "1.0", "C#", new string[] { }); MarketplaceWebServiceClient client = new MarketplaceWebServiceClient(accessKey, secretKey, config); // Submit the report request MarketplaceWebService.Model.RequestReportRequest request = new MarketplaceWebService.Model.RequestReportRequest(); request.ReportType = "_GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_"; request.Merchant = sellerId; request.StartDate = DateTime.Now.AddDays(-30).AddHours(-6); request.EndDate = DateTime.Now.AddHours(-6); this.StatusDescription = string.Format("Requesting Report Type {0} for {1} through {2}", request.ReportType, request.StartDate.ToShortDateString(), request.EndDate.ToShortDateString()); var responseToRequestReport = client.RequestReport(request); Thread.Sleep(1000); string reportRequestId = ""; if (responseToRequestReport.IsSetRequestReportResult()) { if (responseToRequestReport.RequestReportResult.IsSetReportRequestInfo()) { if (responseToRequestReport.RequestReportResult.ReportRequestInfo.IsSetReportRequestId()) { reportRequestId = responseToRequestReport.RequestReportResult.ReportRequestInfo.ReportRequestId; } else { // Would be good to implement wait-and-retry here throw new Exception("ReportRequestId was not returned from RequestReport()"); } } } this.StatusDescription = string.Format("Report Request ID: {0}", reportRequestId); Thread.Sleep(1000); // Check for the report to have a _DONE_ status string reportId = ""; bool reportDone = false; do { this.StatusDescription = string.Format("Checking report status"); MarketplaceWebService.Model.GetReportRequestListRequest requestGetReportRequestList = new MarketplaceWebService.Model.GetReportRequestListRequest(); requestGetReportRequestList.ReportRequestIdList = new MarketplaceWebService.Model.IdList(); requestGetReportRequestList.ReportRequestIdList.Id = new List<string>(); requestGetReportRequestList.ReportRequestIdList.Id.Add(reportRequestId); requestGetReportRequestList.Merchant = sellerId; var responseToGetReportRequestList = client.GetReportRequestList(requestGetReportRequestList); if (responseToGetReportRequestList.IsSetGetReportRequestListResult() && responseToGetReportRequestList.GetReportRequestListResult.IsSetReportRequestInfo() && responseToGetReportRequestList.GetReportRequestListResult.ReportRequestInfo.Count != 0) { this.StatusDescription = string.Format("Report status: {0}", responseToGetReportRequestList.GetReportRequestListResult.ReportRequestInfo[0].ReportProcessingStatus); Thread.Sleep(500); if (responseToGetReportRequestList.GetReportRequestListResult.ReportRequestInfo[0].ReportProcessingStatus.Equals("_DONE_")) { reportDone = true; if (responseToGetReportRequestList.GetReportRequestListResult.ReportRequestInfo[0].IsSetGeneratedReportId()) { reportId = responseToGetReportRequestList.GetReportRequestListResult.ReportRequestInfo[0].GeneratedReportId; this.StatusDescription = string.Format("Report ID: {0}", reportId); } else { // ReportId was not returned, call GetReportList() this.StatusDescription = string.Format("Report ID was not returned. Trying GetReportList()"); var requestGetReportList = new MarketplaceWebService.Model.GetReportListRequest(); requestGetReportList.ReportRequestIdList = new MarketplaceWebService.Model.IdList(); requestGetReportList.ReportRequestIdList.Id = new List<string>(); requestGetReportList.ReportRequestIdList.Id.Add(reportRequestId); requestGetReportList.Merchant = sellerId; var responseToGetReportList = client.GetReportList(requestGetReportList); if (responseToGetReportList.IsSetGetReportListResult() && responseToGetReportList.GetReportListResult.IsSetReportInfo() && responseToGetReportList.GetReportListResult.ReportInfo.Count != 0) { reportId = responseToGetReportList.GetReportListResult.ReportInfo[0].ReportId; this.StatusDescription = string.Format("Report ID: {0}", reportId); } else { throw new Exception("ReportId could not be retrieved."); } } } else if (responseToGetReportRequestList.GetReportRequestListResult.ReportRequestInfo[0].ReportProcessingStatus.Equals("_DONE_NO_DATA_")) { throw new Exception("Report returned with status _DONE_NO_DATA_"); } else { for (int secondsTilRetry = 60; secondsTilRetry > 0; secondsTilRetry--) { this.StatusDescription = string.Format("Report status: {0} (Will check again in {1}s)", responseToGetReportRequestList.GetReportRequestListResult.ReportRequestInfo[0].ReportProcessingStatus, secondsTilRetry); Thread.Sleep(1000); } } } } while (!reportDone); Thread.Sleep(1000); // Retrieve the report string saveFileName = reportId + ".txt"; this.StatusDescription = string.Format("Downloading report to {0}", saveFileName); MarketplaceWebService.Model.GetReportRequest requestGetReport = new MarketplaceWebService.Model.GetReportRequest(); requestGetReport.ReportId = reportId; requestGetReport.Merchant = sellerId; using (Stream file = File.Open(saveFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { requestGetReport.Report = file; var responseToGetReport = client.GetReport(requestGetReport); } }
/** * Samples for Marketplace Web Service functionality */ public static void GetReport(string reportType, string fileName) { /************************************************************************ * Instantiate Implementation of Marketplace Web Service ***********************************************************************/ MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); /************************************************************************ * The application name and version are included in each MWS call's * HTTP User-Agent field. These are required fields. ***********************************************************************/ /************************************************************************ * All MWS requests must contain the seller's merchant ID and * marketplace ID. ***********************************************************************/ config.ServiceURL = GlobalConfig.Instance.ServiceURL; config.SetUserAgentHeader(GlobalConfig.Instance.AppName, GlobalConfig.Instance.AppVersion, "C#"); MarketplaceWebService service = new MarketplaceWebServiceClient(GlobalConfig.Instance.AccessKey, GlobalConfig.Instance.SecretKey, config); //*** 1. Submit a report request using the RequestReport operation. This is a request to Amazon MWS to generate a specific report. RequestReportRequest reportRequest = new RequestReportRequest(); reportRequest.Merchant = GlobalConfig.Instance.SellerId; // request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional reportRequest.MarketplaceIdList = new IdList(); reportRequest.MarketplaceIdList.Id = new List<string>( new string [] { GlobalConfig.Instance.MarketplaceId } ); reportRequest.ReportType = reportType; reportRequest.StartDate = new DateTime(2015, 8, 1); reportRequest.EndDate = new DateTime(2015, 9, 21); // @TODO: set additional request parameters here // request.ReportOptions = "ShowSalesChannel=true"; string reportRequestId = RequestReportSample.InvokeRequestReport(service, reportRequest); Dictionary<string, string> requestInfo = new Dictionary<string, string>(); requestInfo["ReportProcessingStatus"] = ""; requestInfo["GeneratedReportId"] = ""; /************************************************************************ * Uncomment to invoke Get Report Request List Action ***********************************************************************/ { GetReportRequestListRequest request = new GetReportRequestListRequest(); request.Merchant = GlobalConfig.Instance.SellerId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here request.ReportRequestIdList = new IdList(); request.ReportRequestIdList.Id = new List<string>(new string[] { reportRequestId }); while(requestInfo["ReportProcessingStatus"] != "_DONE_" && requestInfo["GeneratedReportId"] == "") { if(!GetReportRequestListSample.InvokeGetReportRequestList(service, request, requestInfo)) { // todo �쳣���� } //*** Request every 60s System.Threading.Thread.Sleep(1 * 60 * 1000); } } //*** 2. Using the GetReportList operation and include the ReportRequestId for the report requested. //*** The operation returns a ReportId that you can then pass to the GetReport operation 50193016685 { if (requestInfo["ReportProcessingStatus"] == "_DONE_" && requestInfo["GeneratedReportId"] == "") { GetReportListRequest getReportListRequest = new GetReportListRequest(); getReportListRequest.Merchant = GlobalConfig.Instance.SellerId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional getReportListRequest.ReportRequestIdList = new IdList(); getReportListRequest.ReportRequestIdList.Id = new List<string>(new string[] { reportRequestId }); string reportId = ""; while (reportId == "") { //*** Request every 60s System.Threading.Thread.Sleep(1 * 60 * 1000); reportId = GetReportListSample.InvokeGetReportList(service, getReportListRequest); } requestInfo["reportId"] = reportId; } } //*** 3. Submit a request using the GetReport operation to receive a specific report. //*** You include in the request the GeneratedReportId or the ReportId for the report you want to receive. //*** You then process the Content-MD5 header to confirm that the report was not corrupted during transmission. GetReportRequest getReportRequest = new GetReportRequest(); getReportRequest.Merchant = GlobalConfig.Instance.SellerId; // 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. if (requestInfo["GeneratedReportId"] != "" || requestInfo["reportId"] != "") { getReportRequest.ReportId = requestInfo["GeneratedReportId"] != "" ? requestInfo["GeneratedReportId"] : requestInfo["reportId"]; getReportRequest.Report = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); GetReportSample.InvokeGetReport(service, getReportRequest); getReportRequest.Report.Close(); } }
public static void GetFeedSubmissionResult(string market_id, string feedSubmissionId, string fileName) { //IniReader iniReader = new IniReader(System.Environment.CurrentDirectory + "\\config.ini"); //string awsSection = "AWS_US"; String accessKeyId = GlobalConfig.Instance.GetConfigValue(market_id, "accessKey"); String secretAccessKey = GlobalConfig.Instance.GetConfigValue(market_id, "secretKey"); /************************************************************************ * Instantiate Implementation of Marketplace Web Service ***********************************************************************/ MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); /************************************************************************ * The application name and version are included in each MWS call's * HTTP User-Agent field. These are required fields. ***********************************************************************/ string applicationName = GlobalConfig.Instance.GetCommonConfigValue("appName"); string applicationVersion = GlobalConfig.Instance.GetCommonConfigValue("appVersion"); /************************************************************************ * All MWS requests must contain the seller's merchant ID and * marketplace ID. ***********************************************************************/ string merchantId = GlobalConfig.Instance.GetConfigValue(market_id, "sellerId"); string marketplaceId = GlobalConfig.Instance.GetConfigValue(market_id, "marketplaceId"); // United States: config.ServiceURL = GlobalConfig.Instance.GetConfigValue(market_id, "serviceURL"); // // 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 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 = feedSubmissionId; request.FeedSubmissionResult = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); GetFeedSubmissionResultSample.InvokeGetFeedSubmissionResult(service, request); request.FeedSubmissionResult.Close(); } }
public SubmitFeedController(MarketplaceWebServiceClient amazonClient, string merchantId, string marketplaceId) { _AmazonClient = amazonClient; _MerchantId = merchantId; _MarketplaceId = marketplaceId; }
/** * Samples for Marketplace Web Service functionality */ public static void Main(string[] args) { 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. ***********************************************************************/ String accessKeyId = "AKIAIKYYTE7TYRWSAIEA"; String secretAccessKey = "jFA0WUoRP1yJty5pp8BXWfHN/UwMOecXQ6grn2D9"; /************************************************************************ * Instantiate Implementation of Marketplace Web Service ***********************************************************************/ //MarketplaceWebServiceConfig 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 = "T-Tek Seller Tool"; const string applicationVersion = "0.1"; /*MarketplaceWebService service = * new MarketplaceWebServiceClient( * accessKeyId, * secretAccessKey, * applicationName, * applicationVersion, * config);*/ /************************************************************************ * All MWS requests must contain the seller's merchant ID and * marketplace ID. ***********************************************************************/ const string merchantId = "A380610PV1XE6A"; const string marketplaceId = "ATVPDKIKX0DER"; /************************************************************************ * 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#", "<Parameter 1>", "<Parameter 2>"); 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 ***********************************************************************/ { GetReportScheduleCountRequest request = new GetReportScheduleCountRequest(); request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here 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 void RunSample() { 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. ***********************************************************************/ IniReader iniReader = new IniReader(System.Environment.CurrentDirectory + "\\config.ini"); string awsSection = "AWS_US"; String accessKeyId = iniReader.ReadValue(awsSection, "accessKey"); String secretAccessKey = iniReader.ReadValue(awsSection, "secretKey"); /************************************************************************ * Instantiate Implementation of Marketplace Web Service ***********************************************************************/ MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); /************************************************************************ * The application name and version are included in each MWS call's * HTTP User-Agent field. These are required fields. ***********************************************************************/ string applicationName = iniReader.ReadValue(awsSection, "appName"); ; string applicationVersion = iniReader.ReadValue(awsSection, "appVersion"); ; //MarketplaceWebService service = // new MarketplaceWebServiceClient( // accessKeyId, // secretAccessKey, // applicationName, // applicationVersion, // config); /************************************************************************ * All MWS requests must contain the seller's merchant ID and * marketplace ID. ***********************************************************************/ string merchantId = iniReader.ReadValue(awsSection, "sellerId"); string marketplaceId = iniReader.ReadValue(awsSection, "marketplaceId"); /************************************************************************ * 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 ***********************************************************************/ { //GetReportScheduleCountRequest request = new GetReportScheduleCountRequest(); //request.Merchant = merchantId; //request.MWSAuthToken = "<Your MWS Auth Token>"; // Optional // @TODO: set additional request parameters here //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 = iniReader.ReadValue(awsSection, "MWSAuthToken"); // 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 = "_POST_PRODUCT_PRICING_DATA_"; //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 = "51635016699"; request.FeedSubmissionResult = File.Open("feedSubmissionResult1.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite); GetFeedSubmissionResultSample.InvokeGetFeedSubmissionResult(service, request); request.FeedSubmissionResult.Close(); } /************************************************************************ * 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 void SubmitFeed(string fileName, string feedType) { //IniReader iniReader = new IniReader(System.Environment.CurrentDirectory + "\\config.ini"); //string awsSection = "AWS_US"; //String accessKeyId = iniReader.ReadValue(awsSection, "accessKey"); //String secretAccessKey = iniReader.ReadValue(awsSection, "secretKey"); /************************************************************************ * Instantiate Implementation of Marketplace Web Service ***********************************************************************/ MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig(); /************************************************************************ * The application name and version are included in each MWS call's * HTTP User-Agent field. These are required fields. ***********************************************************************/ //string applicationName = iniReader.ReadValue(awsSection, "appName"); ; //string applicationVersion = iniReader.ReadValue(awsSection, "appVersion"); /************************************************************************ * All MWS requests must contain the seller's merchant ID and * marketplace ID. ***********************************************************************/ //string merchantId = iniReader.ReadValue(awsSection, "sellerId"); //string marketplaceId = iniReader.ReadValue(awsSection, "marketplaceId"); // United States: config.ServiceURL = GlobalConfig.Instance.ServiceURL; config.SetUserAgentHeader(GlobalConfig.Instance.AppName, GlobalConfig.Instance.AppVersion, "C#"); MarketplaceWebService service = new MarketplaceWebServiceClient(GlobalConfig.Instance.AccessKey, GlobalConfig.Instance.SecretKey, config); SubmitFeedRequest request = new SubmitFeedRequest(); request.Merchant = GlobalConfig.Instance.SellerId; // request.MWSAuthToken = iniReader.ReadValue(awsSection, "MWSAuthToken"); // Optional request.MarketplaceIdList = new IdList(); request.MarketplaceIdList.Id = new List<string>(new string[] { GlobalConfig.Instance.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(fileName, 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 = feedType; SubmitFeedSample.InvokeSubmitFeed(service, request); request.FeedContent.Close(); }