public void FillBookInformationTest() { var item = new Item { ItemAttributes = new ItemAttributes { Title = "TestBookTitle", Author = new [] { "TestAuthor" }, Label = "TestEdition", PublicationDate = "2003", NumberOfPages = "122", ISBN = "TESTISBN", }, LargeImage = new Image { URL = "MediumImageURL" } }; var itemAttributes = item.ItemAttributes; var authorList = itemAttributes.Author.ToList(); var book = AmazonApi.FillBookInformation(item); Assert.AreEqual(itemAttributes.Title, book.Title); Assert.AreEqual(authorList.First(), book.Author); Assert.AreEqual(itemAttributes.Label, book.Editor); Assert.AreEqual(itemAttributes.PublicationDate, book.PublishedYear); Assert.AreEqual(itemAttributes.NumberOfPages, book.PagesNumber.ToString()); Assert.AreEqual(itemAttributes.EAN, book.Isbn); //Assert.AreEqual(item.LargeImage.URL, book.CoverImage); }
public static CallResult <string> Export(IDbFactory dbFactory, ILogService log, ITime time, long companyId, BargainSearchFilterViewModel filter) { var service = new BargainSearchService(dbFactory, log, time); var marketplaceManager = new MarketplaceKeeper(dbFactory, false); marketplaceManager.Init(); AmazonApi api = (AmazonApi) new MarketFactory(marketplaceManager.GetAll(), time, log, dbFactory, null) .GetApi(companyId, MarketType.Amazon, MarketplaceKeeper.AmazonComMarketplaceId); var result = service.Search(filter.GetModel(), api); var fileName = "BargainsSearch_" + DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss") + ".xls"; var filePath = UrlHelper.GetBargainExportFilePath(fileName); service.ExportBargains(result.Bargains.Where(bi => bi.AvailableOnWalmart).ToList(), filePath); var fileUrl = UrlHelper.GetBargainExportUrl(fileName); return(CallResult <string> .Success(fileUrl)); }
public void ProcessAllMarketASINs(AmazonApi advApi) { var asinToProcess = new List <string>(); var fromDate = _time.GetAppNowTime().AddHours(-12); using (var db = _dbFactory.GetRWDb()) { var freshBBQuery = from bb in db.BuyBoxQuantities.GetAll() where bb.CreateDate > fromDate && bb.Market == (int)advApi.Market && bb.MarketplaceId == advApi.MarketplaceId select bb; var asinToProcessQuery = from i in db.Items.GetAllViewAsDto(advApi.Market, advApi.MarketplaceId) join bb in freshBBQuery on new { i.ASIN, i.Market, i.MarketplaceId } equals new { bb.ASIN, bb.Market, bb.MarketplaceId } into withBB from bb in withBB.DefaultIfEmpty() where bb == null select i.ASIN; asinToProcess = asinToProcessQuery.ToList(); } _log.Info("Total asin to process=" + asinToProcess.Count + ", market=" + advApi.Market + ", marketplaceId=" + advApi.MarketplaceId); CartInfo currentCartInfo = null; var index = 0; var step = 50; while (index < asinToProcess.Count) { var stepAsinList = asinToProcess.Skip(index).Take(step).ToList(); _log.Info("ASIN to process: " + String.Join(", ", stepAsinList)); var results = RequestQuantities(advApi, stepAsinList.ToList(), ref currentCartInfo); using (var db = _dbFactory.GetRWDb()) { foreach (var item in results) { _log.Info("Processed ASIN=" + item.ASIN + ", qty=" + item.Quantity + ", seller=" + item.SellerNickname); db.BuyBoxQuantities.Add(new BuyBoxQuantity() { ASIN = item.ASIN, Market = (int)advApi.Market, MarketplaceId = advApi.MarketplaceId, Quantity = item.Quantity, SellerNickname = item.SellerNickname, CreateDate = _time.GetAppNowTime() }); } _log.Info("Before commit"); db.Commit(); _log.Info("After commit"); } index += step; } }
public OurAmazonReports(IDbFactory dbFactory, ILogService log, ITime time, AmazonApi amazonApi) { _dbFactory = dbFactory; _log = log; _time = time; _amazonApi = amazonApi; }
public CallBargainsSearch(IDbFactory dbFactory, ILogService log, ITime time, AmazonApi amazonApi) { _log = log; _dbFactory = dbFactory; _time = time; _amazonApi = amazonApi; }
public UpdateAdjustmentDataThread(AmazonApi api, long companyId, ISystemMessageService messageService, TimeSpan?callbackInterval, TimeSpan betweenProcessingInverval) : base("UpdateAdjustmentData", companyId, messageService, callbackInterval) { _api = api; _betweenProcessingInverval = betweenProcessingInverval; }
public UpdateListingsQtyOnAmazonThread(string tag, AmazonApi api, long companyId, ISystemMessageService messageService, TimeSpan?interval, TimeSpan betweenProcessingInverval) : base(tag, companyId, messageService, interval) { _api = api; _betweenProcessingInverval = betweenProcessingInverval; }
public UpdateListingsPriceOnAmazonThread(string logTag, AmazonApi api, long companyId, ISystemMessageService messageService, TimeSpan?callbackInterval, TimeSpan betweenProcessingInverval) : base(logTag, companyId, messageService, callbackInterval) { _api = api; _betweenProcessingInverval = betweenProcessingInverval; }
public UpdateCancellationDataThread(AmazonApi api, long companyId, ISystemMessageService messageService, TimeSpan?callbackInterval, TimeSpan betweenProcessingInverval) : base("UpdateCancellationData", companyId, messageService, callbackInterval) { LogWrite("callbackInterval=" + callbackInterval); LogWrite("betweenProcessingInverval=" + betweenProcessingInverval); _api = api; _betweenProcessingInverval = betweenProcessingInverval; }
public void GetIsbnInformation(string isbn) { var informations = AmazonApi.GetBookInformation(isbn); if (isbn != string.Empty) { Assert.IsNotNull(informations); } else { Assert.IsNull(informations); } }
public void GetBook(string isbn) { var book = AmazonApi.GetBook(isbn); if (isbn != string.Empty) { Assert.IsNotNull(book); } else { Assert.IsNull(book); } }
public UpdateAmazonRequestedReportThread(string logTag, AmazonApi api, long companyId, ISystemMessageService messageService, IAmazonReportSettings reportSettings, TimeSpan callbackInterval) : base(logTag, companyId, messageService, callbackInterval) { _api = api; _reportSettings = reportSettings; LogWrite(reportSettings.ToString()); }
public AmazonReportService(AmazonReportType reportType, long companyId, AmazonApi api, ILogService log, ITime time, IDbFactory dbFactory, ISyncInformer syncInfo, IStyleManager styleManager, INotificationService notificationService, IStyleHistoryService styleHistoryService, IItemHistoryService itemHistoryService, ISystemActionService actionService, IReportParser parser, string path = "") { _log = log; _time = time; _dbFactory = dbFactory; _api = api; _reportInfo = new AmazonReportInfo(); _reportInfo.ReportRequestId = String.Empty; _path = path; _companyId = companyId; _syncInfo = syncInfo; _reportType = reportType; _parser = parser; _actionService = actionService; var parseContext = new ParseContext() { Log = log, Time = time, DbFactory = dbFactory, ActionService = actionService, StyleManager = styleManager, NotificationService = notificationService, StyleHistoryService = styleHistoryService, ItemHistoryService = itemHistoryService, SyncInformer = syncInfo, CompanyId = companyId }; _parser.Init(parseContext); _log.Info(string.Format("Path: {0}", path)); }
public void UpdateMyPrice(AmazonApi api, IUnitOfWork db) { var lastUpdate = _time.GetUtcTime().AddHours(-12); var allItems = db.Listings .GetAll() .Where(p => p.Market == (int)api.Market && p.MarketplaceId == api.MarketplaceId && !p.IsRemoved && (!p.PriceFromMarketUpdatedDate.HasValue || p.PriceFromMarketUpdatedDate < lastUpdate)) .ToList(); var index = 0; var stepSize = 20; var stepSleeper = new StepSleeper(TimeSpan.FromSeconds(1), 5); while (index < allItems.Count) { try { var itemsToUpdate = allItems.Skip(index).Take(stepSize).ToList(); var skuList = itemsToUpdate.Select(i => i.SKU).ToList(); var items = api.GetMyPriceBySKU(skuList); foreach (var item in items) { var toUpdate = itemsToUpdate.FirstOrDefault(pi => pi.SKU == item.SKU); if (toUpdate != null) { toUpdate.ListingPriceFromMarket = item.ListingPriceFromMarket; toUpdate.ShippingPriceFromMarket = item.ShippingPriceFromMarket; toUpdate.ReqularPriceFromMarket = item.ReqularPriceFromMarket; toUpdate.PriceFromMarketUpdatedDate = _time.GetUtcTime(); } } } catch (Exception ex) { _log.Error("Error when updating rank for index: " + index, ex); } index += stepSize; db.Commit(); stepSleeper.NextStep(); } }
public void FullTest() { //Arrange AmazonApi api = new AmazonApi(); api.setApiKeys(new ConfigFileKeystore().getKey(Provider.Amazon)); api.setUPC("033317198658"); //Act //display the data for the test foreach (IProduct prod in api.QueryProducts()) { System.Diagnostics.Trace.WriteLine("Product Information:" + prod.Name + " " + prod.Price + " " + prod.Condition + " " + prod.Description + " " + prod.FormattedPrice + " " + prod.CurrentCurrency + " " + prod.UPC); } //Assert Assert.Equal(0, 0); }
private async void metroButton5_Click(object sender, EventArgs e) { if (String.IsNullOrWhiteSpace(metroTextBox1.Text)) { return; } metroGrid1.Rows.Clear(); string store = metroComboBox2.SelectedIndex == -1 ? "DE" : metroComboBox2.Text; string categorie = metroComboBox1.SelectedIndex == -1 ? "All" : metroComboBox1.Text; int site = metroComboBox3.SelectedIndex == -1 ? 1 : Convert.ToInt16(metroComboBox3.Text); string searchwords = metroTextBox1.Text; metroComboBox2.Enabled = metroComboBox1.Enabled = metroTextBox1.Enabled = metroComboBox3.Enabled = metroButton5.Enabled = metroButton1.Enabled = false; var searchInfo = await Task.Run(() => AmazonApi.CustomItemSearch(store, categorie, searchwords, site)); if (searchInfo.Items.Request.Errors != null && searchInfo.Items.Request.Errors.Any()) { foreach (var error in searchInfo.Items.Request.Errors) { Logger.Write("AmazonAPI Abfrage Fehlgeschlagen - Grund: " + error.Message, LogLevel.Debug); metroLabel1.Text = error.Message; } } else { foreach (var item in searchInfo.Items.Item) { ResourceManager rm = Resources.ResourceManager; string asin_isbn = item.ASIN; var previewimage = item.SmallImage?.URL != null ? await Task.Run(() => WebUtils.GetImageFromUrl(item.SmallImage.URL)) : (Image)rm.GetObject("No_Image"); string name = item.ItemAttributes.Title; Price pricenew = item.OfferSummary.LowestNewPrice; Price priceused = item.OfferSummary.LowestUsedPrice; metroGrid1.Rows.Add(false, previewimage, asin_isbn, name, pricenew != null ? pricenew.FormattedPrice : string.Empty, priceused != null ? priceused.FormattedPrice : string.Empty); } _currentsearchstore = store; } metroComboBox2.Enabled = metroComboBox1.Enabled = metroTextBox1.Enabled = metroComboBox3.Enabled = metroButton5.Enabled = metroButton1.Enabled = true; }
private JArray MakeAmazonQuery(string searchString) { if (String.IsNullOrEmpty(searchString)) { return new JArray(); } JObject keysJObject = GetKeys(); string accessKey = keysJObject.GetValue("accessKey").ToString(); string secretKey = keysJObject.GetValue("secretKey").ToString(); string destination = keysJObject.GetValue("destination").ToString(); string associateTag = keysJObject.GetValue("associateTag").ToString(); string currId = keysJObject.GetValue("currId").ToString(); string requestString = "Service=AWSECommerceService" + "&Version=2009-03-31" + "&Operation=ItemSearch" + "&SearchIndex=All" + "&ResponseGroup=Medium" + "&AssociateTag=" + associateTag + "&Keywords=" + searchString ; AmazonApi amazon = new AmazonApi(accessKey, secretKey, destination); string requestUrl = amazon.Sign(requestString); JArray jArray = amazon.GetData(requestUrl, currId); JArray more = amazon.GetData(requestUrl, currId); JArray preloaded = amazon.GetData(requestUrl, currId); foreach (JObject moreObj in more) { jArray.Add(moreObj); } foreach (JObject preObj in preloaded) { jArray.Add(preObj); } /* Can't test what happens when the pages run out since we always get the same page and * therefor we always have more data to show */ return jArray; }
public void UpdateLowestPrice(AmazonApi api, IUnitOfWork db) { var allItems = db.Listings.GetAll().Where(p => p.Market == (int)api.Market && p.MarketplaceId == api.MarketplaceId && !p.IsRemoved).ToList(); var index = 0; var stepSize = 20; var stepSleeper = new StepSleeper(TimeSpan.FromSeconds(1), 10); while (index < allItems.Count) { try { var itemsToUpdate = allItems.Skip(index).Take(stepSize).ToList(); var skuList = itemsToUpdate.Select(i => i.SKU).ToList(); var items = api.GetCompetitivePricingForSKU(skuList); foreach (var item in items) { var toUpdate = itemsToUpdate.FirstOrDefault(pi => pi.SKU == item.SKU); if (toUpdate != null && item.LowestPrice.HasValue) { toUpdate.LowestPrice = item.LowestPrice; toUpdate.LowestPriceUpdateDate = _time.GetAppNowTime(); } } } catch (Exception ex) { _log.Error("Error when updating rank for index: " + index, ex); } index += stepSize; stepSleeper.NextStep(); } db.Commit(); }
public static BargainSearchResultViewModel GetAll(IDbFactory dbFactory, ILogService log, ITime time, long companyId, BargainSearchFilterViewModel filter) { var service = new BargainSearchService(dbFactory, log, time); var marketplaceManager = new MarketplaceKeeper(dbFactory, false); marketplaceManager.Init(); AmazonApi api = (AmazonApi) new MarketFactory(marketplaceManager.GetAll(), time, log, dbFactory, null) .GetApi(companyId, MarketType.Amazon, MarketplaceKeeper.AmazonComMarketplaceId); var result = service.Search(filter.GetModel(), api); return(new BargainSearchResultViewModel() { TotalResults = result.Total, Bargains = result.Bargains.Select(b => new BargainViewModel(b)).ToList() }); }
public void UpdateRatingByProductApi(AmazonApi api, IUnitOfWork db) { var allParentItems = db.ParentItems.GetAll().Where(p => p.Market == (int)api.Market && p.MarketplaceId == api.MarketplaceId).ToList(); var index = 0; var stepSize = 20; var stepSleeper = new StepSleeper(TimeSpan.FromSeconds(1), 10); while (index < allParentItems.Count) { try { var parentItems = allParentItems.Skip(index).Take(stepSize).ToList(); var asinList = parentItems.Select(i => i.ASIN).ToList(); var items = api.GetCompetitivePricingForSKU(asinList); foreach (var item in items) { var toUpdate = parentItems.FirstOrDefault(pi => pi.ASIN == item.ASIN); if (toUpdate != null) { toUpdate.Rank = (int?)item.Rank; } } } catch (Exception ex) { _log.Error("Error when updating rank for index: " + index, ex); } index += stepSize; stepSleeper.NextStep(); } db.Commit(); }
public void Update(AmazonApi api, string[] skuList) { using (var db = _dbFactory.GetRWDb()) { _log.Debug("BuyBoxService.Update begin"); var market = api.Market; var marketplaceId = api.MarketplaceId; var itemsQuery = db.Items.GetAllViewAsDto().Where(i => i.Market == (int)market && i.MarketplaceId == marketplaceId); if (skuList != null && skuList.Any()) { itemsQuery = itemsQuery.Where(i => skuList.Contains(i.SKU)); } var items = itemsQuery.ToList(); var buyBoxResponses = RequestItemsBuyBoxByProductApi(_log, items, api); db.BuyBoxStatus.UpdateBulk(_log, _time, buyBoxResponses.Select(b => new BuyBoxStatusDTO() { ASIN = b.ASIN, CheckedDate = b.CheckedDate, WinnerPrice = b.WinnerPrice, Status = b.Status, WinnerMerchantName = b.WinnerMerchantName, }).ToList(), market, marketplaceId); db.Commit(); _log.Debug("BuyBoxService.Update end"); } }
public BargainSearchResult Search(BargainSearchFilter filter, AmazonApi api) { //"id": "5438", //"name": "Apparel", var openApi = new WalmartOpenApi(_log, "trn9fdghvb8p9gjj9j6bvjwx"); var searchResult = openApi.SearchProducts(filter.Keywords, filter.CategoryId, filter.MinPrice, filter.MaxPrice, filter.StartIndex, filter.LimitCount); var results = new List <BargainItem>(); if (searchResult.IsSuccess) { var walmartItems = searchResult.Data.Where(i => //i.AvailableOnline && !String.IsNullOrEmpty(i.UPC)).ToList(); var index = 0; var step = 5; while (index < walmartItems.Count) { var stepWalmartItems = walmartItems.Skip(index).Take(step).ToList(); var amazonItems = api.GetProductForBarcode(stepWalmartItems.Select(i => i.UPC).ToList()); var newItems = new List <BargainItem>(); foreach (var walmartItem in stepWalmartItems) { var amazonItem = amazonItems.FirstOrDefault(i => i.Barcode == walmartItem.UPC); newItems.Add(new BargainItem() { Barcode = walmartItem.UPC, Name = walmartItem.Name, WalmartImage = walmartItem.ThumbnailImage, AmazonItem = amazonItem, AmazonPrice = amazonItem != null ? amazonItem.CurrentPrice : (decimal?)null, AvailableOnAmazon = amazonItem != null ? amazonItem.AmazonRealQuantity > 0 : false, WalmartPrice = walmartItem.SalePrice, AvailableOnWalmart = walmartItem.AvailableOnline, WalmartItem = new ItemDTO() { SourceMarketId = walmartItem.ItemId, CurrentPrice = walmartItem.SalePrice ?? 0, AmazonRealQuantity = walmartItem.Stock == "Available" ? 1 : 0, Size = walmartItem.Size, Color = walmartItem.Color, Name = walmartItem.Name, Barcode = walmartItem.UPC, } }); } var asinList = newItems.Where(i => i.AmazonItem != null && !String.IsNullOrEmpty(i.AmazonItem.ASIN)) .Select(i => i.AmazonItem.ASIN) .ToList(); if (asinList.Any()) { var amazonPrices = api.GetLowestOfferListingsForASIN(asinList).ToList(); foreach (var amazonPrice in amazonPrices) { var item = newItems.FirstOrDefault( i => i.AmazonItem != null && i.AmazonItem.ASIN == amazonPrice.ASIN); if (item != null) { item.AmazonPrice = amazonPrice.LowestPrice; item.AmazonItem.AmazonRealQuantity = 1; //NOTE: has offer => Available } } } results.AddRange(newItems); index += step; } } return(new BargainSearchResult() { Bargains = results, StartIndex = filter.StartIndex, Total = searchResult.Total, }); }
public void Update(AmazonApi api) { Update(api, null); }
public static async Task Add(string[] stores, string asin_isbn) { if (Tools.ArrayIsNullOrEmpty(stores)) { MetroMessageBox.Show(mf, "Eintrag konnte nicht hinzugefügt werden!" + Environment.NewLine + "Bitte wähle mind. 1 Store für dieses Produkt aus!", "Eintrag Hinzufügen Fehlgeschlagen", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (String.IsNullOrWhiteSpace(asin_isbn)) { MetroMessageBox.Show(mf, "Eintrag konnte nicht hinzugefügt werden!" + Environment.NewLine + "Bitte gebe die Produkt ASIN / ISBN ein.!", "Eintrag Hinzufügen Fehlgeschlagen", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } foreach (string store in stores) { Database.OpenConnection(); SQLiteCommand checkEntry = new SQLiteCommand( "SELECT COUNT(*) FROM Products WHERE Store = @store AND [ASIN / ISBN] = @asin_isbn", Database.Connection); checkEntry.Parameters.AddWithValue("@store", store); checkEntry.Parameters.AddWithValue("@asin_isbn", asin_isbn); int entryExist = Convert.ToInt32(checkEntry.ExecuteScalar()); if (entryExist > 0) { continue; } AmazonItemResponse itemInfo; try { itemInfo = await Task.Run(() => AmazonApi.ItemLookup(store, asin_isbn)); if (itemInfo.Items == null) { continue; } } catch (Exception ex) { Debug.WriteLine("Abfrage Fehler: " + ex.Message, LogLevel.Debug); continue; } if (itemInfo.Items.Request.Errors != null && itemInfo.Items.Request.Errors.Any()) { foreach (var error in itemInfo.Items.Request.Errors) { Logger.Write("AmazonAPI Abfrage Fehlgeschlagen - Grund: " + error.Message, LogLevel.Debug); } continue; } string name = itemInfo.Items.Item[0].ItemAttributes.Title; var shortUrl = await URLShortener.Generate(Amazon.MakeReferralLink(store, asin_isbn), name, store); if (shortUrl == null) { continue; } Database.OpenConnection(); SQLiteCommand insertEntry = new SQLiteCommand( "INSERT INTO Products (Store, [ASIN / ISBN], Name, URL) Values (@store, @asin_isbn, @name, @shorturl)", Database.Connection); insertEntry.Parameters.AddWithValue("@store", store); insertEntry.Parameters.AddWithValue("@asin_isbn", asin_isbn); insertEntry.Parameters.AddWithValue("@name", name); insertEntry.Parameters.AddWithValue("@shorturl", shortUrl); insertEntry.ExecuteNonQuery(); } mf.metroTextBox1.Clear(); Display(mf.metroComboBox2.SelectedIndex == -1 ? "ALLE" : mf.metroComboBox2.Text); }
public long?SubmitFeed(AmazonApi api, long companyId, IList <string> skuList, string forRequestDirectory) { long?feedId = null; using (var db = DbFactory.GetRWDb()) { var documentInfo = ComposeDocument(db, companyId, api.Market, api.MarketplaceId, skuList); if (documentInfo != null && documentInfo.HasInfo) { Log.Info(api.MarketplaceId + ": Submit feed"); MemoryStream stream = null; string feedRequestId = ""; try { if (documentInfo.XmlDocument != null) { stream = StreamHelper.GetStreamFromXml(documentInfo.XmlDocument); } if (documentInfo.TextDocument != null) { stream = StreamHelper.GetStreamFromString(documentInfo.TextDocument); } feedRequestId = api.SubmitFeed(Log, stream, AmazonFeedName, Type == AmazonFeedType.OrderFulfillment); if (!string.IsNullOrEmpty(feedRequestId)) { Log.Info(string.Format("Insert new feed {0}, messages: {1}", feedRequestId, documentInfo.NodesCount)); feedId = db.Feeds.InsertFeed(feedRequestId, documentInfo.NodesCount, (int)Type, (int)FeedStatus.Submitted, api.Market, api.MarketplaceId); if (documentInfo.FeedItems != null) { documentInfo.FeedItems.ForEach(f => f.FeedId = feedId.Value); db.FeedItems.Insert(documentInfo.FeedItems); } UpdateEntitiesBeforeSubmitFeed(db, feedId.Value); Log.Info("Commit"); db.Commit(); Log.Info("Save submitted feed into file"); var toDirectory = FileHelper.ToDirectoryNameWithBackslash(forRequestDirectory) + Time.GetAppNowTime().ToString("yyyy_MM_dd"); if (!Directory.Exists(toDirectory)) { Directory.CreateDirectory(toDirectory); } var saveToFilepath = toDirectory + "/" + string.Format("{0}_{1}_{2}.xml", api.MarketplaceId ?? "", Type, feedId); using (var fileStream = File.Create(saveToFilepath)) { stream.WriteTo(fileStream); } } } finally { if (stream != null) { stream.Close(); } } } } return(feedId); }
public void UpdateSubmittedFeed(AmazonApi api, string feedId, string forResponseDirectory) { var marketplaceId = api.MarketplaceId; Stream result = null; try { result = api.GetFeedSubmissionResult(feedId); } catch (MarketplaceWebServiceReportsException ex) { //Feed Submission Result not available. Feed Submission has been canceled for Feed: 67659017019 if (ex.Message.Contains("Feed Submission has been canceled")) { Log.Error("GetFeedSubmissionResult", ex); using (var db = new UnitOfWork(Log)) { var feed = db.Feeds.GetFiltered(f => f.AmazonIdentifier == feedId && f.MarketplaceId == marketplaceId) .First(); feed.Status = (int)FeedStatus.Cancelled; db.Commit(); Log.Info("Feed market as deleted, feedId=" + feedId); } } else { throw ex; } } if (result != null) { //var now = DateHelper.GetAppNowTime(); Log.Info("Stream to document"); XmlDocument document = null; try { document = StreamHelper.GetXmlFromStream(result); } catch (Exception ex) { Log.Error("GetDocumentXml", ex); } IList <FeedResultMessage> errorList = new List <FeedResultMessage>(); long dbFeedId = 0; using (var db = DbFactory.GetRWDb()) { Log.Info("Get feed"); var feed = db.Feeds.GetFiltered(f => f.AmazonIdentifier == feedId && f.MarketplaceId == marketplaceId).First(); errorList = FeedHelper.GetErrorMessageList(document); dbFeedId = feed.Id; //Save file var toDirectory = FileHelper.ToDirectoryNameWithBackslash(forResponseDirectory) + Time.GetAppNowTime().ToString("yyyy_MM_dd"); if (!Directory.Exists(toDirectory)) { Directory.CreateDirectory(toDirectory); } using (var errorfileStream = File.Open(toDirectory + "/" + string.Format("{0}_{1}_{2}.xml", marketplaceId ?? "", Type, feedId), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { result.Position = 0; result.CopyTo(errorfileStream); } if (errorList.Any()) { Log.Info("Errors found"); } else { Log.Info("No errors"); } if (errorList.Any()) { feed.Status = (int)FeedStatus.ProcessedWithErrors; } else { feed.Status = (int)FeedStatus.Processed; } db.FeedMessages.Insert(errorList.Select(e => new FeedMessageDTO() { FeedId = feed.Id, Message = e.Message, MessageId = e.MessageId, MessageCode = e.MessageCode, ResultCode = e.ResultCode, CreateDate = Time.GetAppNowTime(), }).ToList()); db.Commit(); } try { UpdateEntitiesAfterResponse(dbFeedId, errorList); } catch (Exception ex) { Log.Fatal("Amazon: error when processing feed submission result", ex); } } else { Log.Info(string.Format("No result by api for feed type: {0}; feedId {1}!", Type, feedId)); } }
private void metroGrid1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex <= -1 || e.ColumnIndex == metroGrid1.Columns["DG3_CheckBox"].Index) { return; } string store = _currentsearchstore; string asin_isbn = Convert.ToString(metroGrid1.Rows[e.RowIndex].Cells["DG3_ASIN_ISBN"].Value); if (String.IsNullOrEmpty(asin_isbn)) { return; } Process.Start($"https://www.amazon.{Amazon.GetTld(store)}/dp/{asin_isbn}/&tag=" + AmazonApi.AssociateTag(store)); }
public void Setup() { Database.SetInitializer <AmazonContext>(null); XmlConfigurator.Configure(new FileInfo(AppSettings.log4net_Config)); _dbFactory = new DbFactory(); _time = new TimeService(_dbFactory); _settings = new SettingsService(_dbFactory); _styleHistoryService = new StyleHistoryService(_log, _time, _dbFactory); _styleManager = new StyleManager(_log, _time, _styleHistoryService); _actionService = new SystemActionService(_log, _time); _quantityManager = new QuantityManager(_log, _time); _priceManager = new PriceManager(_log, _time, _dbFactory, _actionService, _settings); _cacheService = new CacheService(_log, _time, _actionService, _quantityManager); _barcodeService = new BarcodeService(_log, _time, _dbFactory); _weightService = new WeightService(); IEmailSmtpSettings smtpSettings = new EmailSmtpSettings(); using (var db = new UnitOfWork()) { _company = db.Companies.GetFirstWithSettingsAsDto(); if (AppSettings.IsDebug) { smtpSettings = SettingsBuilder.GetSmtpSettingsFromAppSettings(); } else { smtpSettings = SettingsBuilder.GetSmtpSettingsFromCompany(_company); } _addressService = AddressService.Default; _emailService = new EmailService(_log, smtpSettings, _addressService); //todo check itemHist _autoCreateNonameListingService = new AutoCreateNonameListingService(_log, _time, _dbFactory, _cacheService, _barcodeService, _emailService, null, AppSettings.IsDebug); var marketplaces = new MarketplaceKeeper(_dbFactory, true); marketplaces.Init(); var shipmentPrividers = db.ShipmentProviders.GetByCompanyId(_company.Id); var apiFactory = new MarketFactory(marketplaces.GetAll(), _time, _log, _dbFactory, AppSettings.JavaPath); var weightService = new WeightService(); var serviceFactory = new ServiceFactory(); var rateProviders = serviceFactory.GetShipmentProviders(_log, _time, _dbFactory, weightService, shipmentPrividers, null, null, null, null); _magentoApi = (Magento20MarketApi)apiFactory.GetApi(_company.Id, MarketType.Magento, MarketplaceKeeper.ShopifyDWS); _shopifyDWSApi = (ShopifyApi)apiFactory.GetApi(_company.Id, MarketType.Shopify, MarketplaceKeeper.ShopifyDWS); _eBayApi = (eBayApi)apiFactory.GetApi(_company.Id, MarketType.eBay, ""); _amazonApi = (AmazonApi)apiFactory.GetApi(_company.Id, MarketType.Amazon, MarketplaceKeeper.AmazonComMarketplaceId); _walmartApi = (WalmartApi)apiFactory.GetApi(_company.Id, MarketType.Walmart, ""); } }
private IList <ItemBuyBoxResponse> RequestItemsBuyBoxByProductApi(ILogService logger, IList <ItemDTO> items, AmazonApi api) { var results = new List <ItemBuyBoxResponse>(); var index = 0; var step = 20; var sleep = new StepSleeper(TimeSpan.FromSeconds(1), 10); /* * Maximum request quota Restore rate Hourly request quota * 20 requests 10 items every second 36000 requests per hour */ while (index < items.Count) { var checkedItems = items.Skip(index).Take(step).ToList(); var resp = RetryHelper.ActionWithRetriesWithCallResult(() => api.GetCompetitivePricingForSKU(checkedItems.Select(i => i.SKU).ToList()), logger); if (resp.IsFail) { var message = resp.Message ?? ""; //Request is throttled ---> Amazon.OrdersApi.Runtime.MwsException: Request is throttled //... if (message.IndexOf("ServiceUnavailable", StringComparison.InvariantCultureIgnoreCase) >= 0 || message.IndexOf("throttled", StringComparison.InvariantCultureIgnoreCase) >= 0) { //do sleep } //NOTE: temporary do always _log.Info("Sleep 5 min"); Thread.Sleep(5 * 60 * 1000); } else { foreach (var item in resp.Data) { results.Add(new ItemBuyBoxResponse() { ASIN = item.ASIN, CheckedDate = DateTime.UtcNow, Status = item.BuyBoxStatus ?? BuyBoxStatusCode.NoWinner, WinnerPrice = item.LowestPrice, }); } index += step; sleep.NextStep(); } } return(results); }
public AmazonReadPriceThread(long companyId, ISystemMessageService messageService, AmazonApi api, IList <TimeSpan> callTimeStamps, ITime time) : base("AmazonReadPrice", companyId, messageService, callTimeStamps, time) { _api = api; }
private JArray MakeAmazonQuery(string searchString, string oldCurrency, string newCurrency) { if (String.IsNullOrEmpty(searchString)) { return new JArray(); } JObject keysJObject = GetKeys(); string accessKey = keysJObject.GetValue("accessKey").ToString(); string secretKey = keysJObject.GetValue("secretKey").ToString(); string destination = "ecs.amazonaws.co.uk"; string requestString = "Service=AWSECommerceService" + "&Version=2009-03-31" + "&Operation=ItemSearch" + "&SearchIndex=All" + "&ResponseGroup=Medium" + "&AssociateTag=212437046868" + "&Keywords=" + searchString ; AmazonApi amazon = new AmazonApi(accessKey, secretKey, destination); string requestUrl = amazon.Sign(requestString); JArray jArray = amazon.GetData(requestUrl); return jArray; }
public void GetAuthenticationTest() { var authentication = AmazonApi.GetAuthentication(); Assert.IsNotNull(authentication); }