private static void SetDummyProductsAsSentAsDummyToWehkamp(List <int> productIDs, PetaPoco.Database db = null) { var sentToWehkampAsDummyAttributeID = VendorSettingsHelper.GetSentToWehkampAsDummyAttributeID(); var disposeDatabase = (db == null); if (db == null) { db = new PetaPoco.Database(Environments.Current.Connection, "System.Data.SqlClient"); db.CommandTimeout = 5 * 60; } foreach (var productID in productIDs) { var actualProductID = db.ExecuteScalar <int>(@"select isnull(ParentProductID, productID) as ProductID from Product where productid = @0", productID); var sql = string.Format("IF EXISTS (SELECT * FROM [ProductAttributeValue] WHERE AttributeID = {0} AND ProductID = {1}) UPDATE [ProductAttributeValue] SET [Value] = 'true' WHERE AttributeID = {0} AND ProductID = {1} ELSE INSERT INTO [ProductAttributeValue] (AttributeID, ProductID, [Value], CreatedBy, CreationTime) VALUES ({0}, {1}, 'true', 1, getdate())", sentToWehkampAsDummyAttributeID, actualProductID); db.Execute(sql); } if (disposeDatabase) { db.Dispose(); } }
private bool SaveProductAttributes(int vendorID, artikelEigenschap artikelEigenschapData) { var alliantieName = VendorSettingsHelper.GetAlliantieName(vendorID); var retailPartnerCode = VendorSettingsHelper.GetRetailPartnerCode(vendorID); var sequenceNumberArtikelEigenschap = CommunicatorHelper.GetSequenceNumber(vendorID); artikelEigenschapData.header.berichtDatumTijd = DateTime.Now; artikelEigenschapData.header.berichtNaam = "artikelEigenschap"; artikelEigenschapData.header.retailPartnerCode = retailPartnerCode; artikelEigenschapData.header.bestandsNaam = string.Format("{0}{1}artikelEigenschap.xml", sequenceNumberArtikelEigenschap, alliantieName); var messageIDArtAttr = MessageHelper.InsertMessage(MessageHelper.WehkampMessageType.ProductAttribute, artikelEigenschapData.header.bestandsNaam, vendorID); try { artikelEigenschapData.SaveToFile(string.Format(Path.Combine(ConfigurationHelper.ProductAttributesRootFolder, vendorID.ToString(CultureInfo.InvariantCulture), artikelEigenschapData.header.bestandsNaam))); MessageHelper.UpdateMessageStatus(messageIDArtAttr, WehkampMessageStatus.Success); } catch (Exception ex) { log.Fatal("Error while saving artikelEigenschap file", ex); MessageHelper.UpdateMessageStatus(messageIDArtAttr, WehkampMessageStatus.Error); return(false); } return(true); }
protected override void Process() { _monitoring.Notify(Name, 0); using (var db = new Database(Environments.Current.Connection, "System.Data.SqlClient")) { foreach (var vendorID in ConfigurationHelper.VendorIdsToDownload) { _monitoring.Notify(Name, vendorID); DateTime lastRun; var runStart = DateTime.Now; if (!DateTime.TryParse(db.SingleOrDefault <string>(string.Format("SELECT Value FROM VendorSetting WHERE VendorID='{0}' AND SettingKey='{1}'", vendorID, VendorSettingKey)), out lastRun)) { log.Info(string.Format("VendorSetting for \"{1}\" does not exist or has invalid data for vendorID {0} , doing a media export from the beginning of time", vendorID, VendorSettingKey)); } // if setting not present if (lastRun == DateTime.MinValue) { lastRun = SqlDateTime.MinValue.Value; // new DateTime(1753, 1, 1, 0, 0, 0); // tsql minimum date value db.Execute(string.Format("INSERT INTO VendorSetting (VendorID, SettingKey, Value) Values ({0}, '{1}', '{2}')", vendorID, VendorSettingKey, runStart.ToString(MessageHelper.ISO8601, CultureInfo.InvariantCulture))); } else { lastRun = lastRun.ToUniversalTime(); } const string query = "SELECT MediaID, BrandID, ProductID, ManufacturerID, ImagePath, LastChanged FROM ImageView WHERE ConnectorID=@0 AND (@1 IS NULL OR LastChanged > @1)"; var images = db.Fetch <ProductMedia>(query, VendorSettingsHelper.GetConnectorIDByVendorID(vendorID), lastRun); var processed = ProcessProductImages(db, images, vendorID); // finished if (processed) { db.Execute(string.Format("UPDATE VendorSetting SET Value='{2}' WHERE VendorID={0} AND SettingKey='{1}'", vendorID, VendorSettingKey, runStart.ToString(MessageHelper.ISO8601, CultureInfo.InvariantCulture))); } } } _monitoring.Notify(Name, 1); }
protected override void Process() { _monitoring.Notify(Name, 0); log.InfoFormat("Start processing Product Price Update"); var vendorIDsToProcess = VendorSettingsHelper.GetVendorIDsToExportToWehkamp(log); foreach (var vendorID in vendorIDsToProcess) { _monitoring.Notify(Name, vendorID); log.InfoFormat("Start processing Product Price Update for VendorID {0}", vendorID); var runDateTime = DateTime.Now; //Get all price updates that we need to export to Wehkamp var products = GetProductsWithChangedPricesData(vendorID); if (products == null || products.Count == 0) { log.InfoFormat("There are no price updates for VendorID {0}", vendorID); //Update last processed datetime for vendor VendorSettingsHelper.SetLastPriceExportDateTime(vendorID, runDateTime); continue; } log.InfoFormat("Processing {0} Product Price Updates records for VendorID {1}", products.Count, vendorID); //Add all products to the artikelInformatie file var priceChange = new prijsAanpassing { aanpassing = new List <prijsAanpassingAanpassing>() }; foreach (var product in products) { priceChange.aanpassing.Add(CreateNewPrijsAanpassingItem(product)); } //Save data to disk SavePriceChanges(vendorID, priceChange); //Process products which needs a price update file ProcessResendProductInformationToWehkampProducts(products); //Update last processed datetime for vendor VendorSettingsHelper.SetLastPriceExportDateTime(vendorID, runDateTime); log.InfoFormat("Finished processing Product Price Update for VendorID {0}", vendorID); } //end foreach (var vendorID in vendorIDsToProcess) log.InfoFormat("Finished processing Product Price Update"); _monitoring.Notify(Name, 1); }
private static aankomstAankomsten CreateNewShipmentItem(ProductInformationShipmentNotification product, int vendorID) { return(new aankomstAankomsten { artikelNummer = product.Artikelnummer, kleurNummer = product.Kleurnummer, maat = product.WehkampMagazijnmaat, aantalOpgegeven = product.NumberToReceive, verwachteAankomstDatum = DateTime.Now.AddDays(VendorSettingsHelper.GetDaysToAddForShipmentDate(vendorID)), ggb = product.PackingSlipNumber, goederenSoort = "V" }); }
protected override void Process() { _monitoring.Notify(Name, 0); log.InfoFormat("Start processing Stock Return Request"); var vendorIDsToProcess = VendorSettingsHelper.GetVendorIDsToExportToWehkamp(log); foreach (var vendorID in vendorIDsToProcess) { _monitoring.Notify(Name, vendorID); log.InfoFormat("Start processing Stock Return Request for VendorID {0}", vendorID); //Get all stock return request that we need to export to Wehkamp var stockReturns = GetStockReturnRequestData(vendorID); if (stockReturns == null || stockReturns.Count == 0) { continue; } //Add all return requests to the retourAanvraag file var returnRequest = new retourAanvraag(); log.InfoFormat("Start processing {0} Stock Return Requests for VendorID {1}", stockReturns.Count, vendorID); var start = DateTime.Now; var processedCount = 0; foreach (var stockReturn in stockReturns) { returnRequest.aanvraag.Add(CreateNewReturnRequestItem(stockReturn)); processedCount++; if (DateTime.Now > start.AddSeconds(30)) { log.InfoFormat("Processed {0} Stock Return Requests for VendorID {1}", processedCount, vendorID); start = DateTime.Now; } } //Save data to disk log.InfoFormat("Start saving Stock Return Requests"); SaveStockReturn(vendorID, returnRequest); //Set all orders and orderlines as dispatched log.InfoFormat("Start setting Stock Return Requests as dispatched"); SetReturnRequestsAsExportedToWehkamp(stockReturns); log.InfoFormat("Finished processing Stock Return Requests for VendorID {0}", vendorID); } //end foreach (var vendorID in vendorIDsToProcess) log.InfoFormat("Finished processing Stock Return Requests"); _monitoring.Notify(Name, 1); }
private static void RemoveSentAsDummy(List <int> productIDs) { var sentToWehkampAsDummyAttributeID = VendorSettingsHelper.GetSentToWehkampAsDummyAttributeID(); using (var db = new PetaPoco.Database(Environments.Current.Connection, "System.Data.SqlClient")) { db.CommandTimeout = 30; var sql = string.Format("DELETE FROM ProductAttributeValue WHERE AttributeID = {0} AND ProductID IN ({1})", sentToWehkampAsDummyAttributeID, string.Join(",", productIDs.ToArray())); db.Execute(sql); var sqlParents = string.Format("DELETE FROM ProductAttributeValue WHERE AttributeID = {0} AND ProductID IN (SELECT ParentProductID FROM Product WHERE ProductID IN ({1}))", sentToWehkampAsDummyAttributeID, string.Join(",", productIDs.ToArray())); db.Execute(sqlParents); } }
private static void SetProductsAsSentToWehkamp(List <int> productIDs) { var sentToWehkampAttributeID = VendorSettingsHelper.GetSentToWehkampAttributeID(); using (var db = new PetaPoco.Database(Environments.Current.Connection, "System.Data.SqlClient")) { db.CommandTimeout = 30; foreach (var productID in productIDs) { var sql = string.Format("IF EXISTS (SELECT * FROM [ProductAttributeValue] WHERE AttributeID = {0} AND ProductID = {1}) UPDATE [ProductAttributeValue] SET [Value] = 'true' WHERE AttributeID = {0} AND ProductID = {1} ELSE INSERT INTO [ProductAttributeValue] (AttributeID, ProductID, [Value], CreatedBy, CreationTime) VALUES ({0}, {1}, 'true', 1, getdate())", sentToWehkampAttributeID, productID); db.Execute(sql); } } }
private void SavePriceChanges(int vendorID, prijsAanpassing priceChange) { var alliantieName = VendorSettingsHelper.GetAlliantieName(vendorID); var retailPartnerCode = VendorSettingsHelper.GetRetailPartnerCode(vendorID); var sequenceNumber = CommunicatorHelper.GetSequenceNumber(vendorID); priceChange.header.berichtDatumTijd = DateTime.Now; priceChange.header.berichtNaam = "prijsAanpassing"; priceChange.header.retailPartnerCode = retailPartnerCode; priceChange.header.bestandsNaam = string.Format("{0}{1}prijsAanpassing.xml", sequenceNumber, alliantieName); var messageIDPriceChange = MessageHelper.InsertMessage(MessageHelper.WehkampMessageType.ProductPriceUpdate, priceChange.header.bestandsNaam, vendorID); try { priceChange.SaveToFile(string.Format(Path.Combine(ConfigurationHelper.ProductPricesRootFolder, vendorID.ToString(CultureInfo.InvariantCulture), priceChange.header.bestandsNaam))); MessageHelper.UpdateMessageStatus(messageIDPriceChange, WehkampMessageStatus.Success); } catch (Exception ex) { log.Fatal("Error while saving Price Change file", ex); MessageHelper.UpdateMessageStatus(messageIDPriceChange, WehkampMessageStatus.Error); } }
private void SaveStockReturn(int vendorID, retourAanvraag stockReturnRequest) { var alliantieName = VendorSettingsHelper.GetAlliantieName(vendorID); var retailPartnerCode = VendorSettingsHelper.GetRetailPartnerCode(vendorID); var sequenceNumber = CommunicatorHelper.GetSequenceNumber(vendorID); stockReturnRequest.header.berichtDatumTijd = DateTime.Now; stockReturnRequest.header.berichtNaam = "retourAanvraag"; stockReturnRequest.header.retailPartnerCode = retailPartnerCode; stockReturnRequest.header.bestandsNaam = string.Format("{0}{1}retourAanvraag.xml", sequenceNumber, alliantieName); var messageID = MessageHelper.InsertMessage(MessageHelper.WehkampMessageType.StockReturnRequest, stockReturnRequest.header.bestandsNaam, vendorID); try { stockReturnRequest.SaveToFile(string.Format(Path.Combine(ConfigurationHelper.StockReturnRequestRootFolder, vendorID.ToString(CultureInfo.InvariantCulture), stockReturnRequest.header.bestandsNaam))); MessageHelper.UpdateMessageStatus(messageID, WehkampMessageStatus.Success); } catch (Exception ex) { log.Fatal("Error while saving retourAanvraag file", ex); MessageHelper.UpdateMessageStatus(messageID, WehkampMessageStatus.Error); } }
private void SaveShipmentInformation(int vendorID, aankomst shipment, PetaPoco.Database db = null) { var alliantieName = VendorSettingsHelper.GetAlliantieName(vendorID); var retailPartnerCode = VendorSettingsHelper.GetRetailPartnerCode(vendorID); var sequenceNumberShipment = CommunicatorHelper.GetSequenceNumber(vendorID); shipment.header.berichtDatumTijd = DateTime.Now; shipment.header.berichtNaam = "aankomst"; shipment.header.retailPartnerCode = retailPartnerCode; shipment.header.bestandsNaam = string.Format("{0}{1}aankomst.xml", sequenceNumberShipment, alliantieName); var messageIDShipment = MessageHelper.InsertMessage(MessageHelper.WehkampMessageType.ShipmentNotification, shipment.header.bestandsNaam, vendorID, db); try { shipment.SaveToFile(Path.Combine(ConfigurationHelper.ShipmentNotificationRootFolder, vendorID.ToString(CultureInfo.InvariantCulture), shipment.header.bestandsNaam)); MessageHelper.UpdateMessageStatus(messageIDShipment, WehkampMessageStatus.Success, db); } catch (Exception ex) { log.Fatal("Error while saving aankomst file", ex); MessageHelper.UpdateMessageStatus(messageIDShipment, WehkampMessageStatus.Error); } }
private void SaveProductInformation(int vendorID, artikelInformatie artInfo, PetaPoco.Database db = null) { var alliantieName = VendorSettingsHelper.GetAlliantieName(vendorID); var retailPartnerCode = VendorSettingsHelper.GetRetailPartnerCode(vendorID); var sequenceNumberArtikelInformatie = CommunicatorHelper.GetSequenceNumber(vendorID); artInfo.header.berichtDatumTijd = DateTime.Now; artInfo.header.berichtNaam = "artikelInformatie"; artInfo.header.retailPartnerCode = retailPartnerCode; artInfo.header.bestandsNaam = string.Format("{0}{1}artikelInformatie.xml", sequenceNumberArtikelInformatie, alliantieName); var messageIDArtInfo = MessageHelper.InsertMessage(MessageHelper.WehkampMessageType.ProductInformation, artInfo.header.bestandsNaam, vendorID, db); try { artInfo.SaveToFile(string.Format(Path.Combine(ConfigurationHelper.ProductInformationRootFolder, vendorID.ToString(CultureInfo.InvariantCulture), artInfo.header.bestandsNaam))); MessageHelper.UpdateMessageStatus(messageIDArtInfo, WehkampMessageStatus.Success, db); } catch (Exception ex) { log.Fatal("Error while saving artikelInfo file", ex); MessageHelper.UpdateMessageStatus(messageIDArtInfo, WehkampMessageStatus.Error); } }
protected override void Process() { _monitoring.Notify(Name, 0); log.InfoFormat("Start processing Shipment Notification"); var vendorIDsToProcess = VendorSettingsHelper.GetVendorIDsToExportToWehkamp(log); foreach (var vendorID in vendorIDsToProcess) { _monitoring.Notify(Name, vendorID); log.InfoFormat("Start processing Shipment Notification for VendorID {0}", vendorID); var dummyProductIDsInFile = new List <int>(); //Get all products in shipment notification that we need to export to Wehkamp var products = GetShipmentNotificationProductInformationData(vendorID); if (products == null || products.Count == 0) { continue; } //Add all products to the artikelInformatie file that aren't sent to Wehkamp before var artInfo = new artikelInformatie(); //Add all products to the aankomst file var shipmentInfo = new aankomst(); foreach (var product in products) { shipmentInfo.aankomsten.Add(CreateNewShipmentItem(product, vendorID)); //Create dummy product if parentproduct isn't sent to Wehkamp (as dummy or regular product) if ((string.IsNullOrEmpty(product.ParentSentToWehkamp) || product.ParentSentToWehkamp.ToLower(CultureInfo.InvariantCulture) == "false") && (string.IsNullOrEmpty(product.ParentSentToWehkampAsDummy) || product.ParentSentToWehkampAsDummy.ToLower(CultureInfo.InvariantCulture) == "false") && !dummyProductIDsInFile.Contains(product.ParentProductID)) { var artikel = CreateNewDummyArtikelInformatieArtikel(product); var sizes = GetDummyProductSizes(vendorID, product.ParentProductID); foreach (var size in sizes) { artikel.maatlijst.Add(CreateNewDummyArtikelInformatieMaatGegevens(size)); } artInfo.artikel.Add(artikel); if (!dummyProductIDsInFile.Contains(product.ParentProductID)) { dummyProductIDsInFile.Add(product.ParentProductID); } if (!dummyProductIDsInFile.Contains(product.ProductID)) { dummyProductIDsInFile.Add(product.ProductID); } } } var orderIDs = products.Select(p => p.OrderID).Distinct().ToList(); using (var db = new PetaPoco.Database(Environments.Current.Connection, "System.Data.SqlClient")) { db.BeginTransaction(System.Data.IsolationLevel.ReadCommitted); db.CommandTimeout = 60; try { var updateOrdersSql = string.Format("UPDATE [Order] SET IsDispatched = 1, DispatchToVendorDate = getdate() WHERE OrderID IN ({0})", string.Join(",", orderIDs.ToArray())); db.Execute(updateOrdersSql); foreach (var orderID in orderIDs) { var id = orderID; var item = from p in products where p.OrderID == id select p; var orderLineIDs = item.Select(p => p.OrderLineID).Distinct().ToList(); var updateOrderLinesSql = string.Format("UPDATE [OrderLine] SET IsDispatched = 1, DispatchedToVendorID = {1} WHERE OrderLineID IN ({0})", string.Join(",", orderLineIDs.ToArray()), vendorID); db.Execute(updateOrderLinesSql); } //Save data to disk if (artInfo.artikel.Count != 0) { SaveProductInformation(vendorID, artInfo, db); //Set all dummy products as SentToAsDummyWehkamp = true SetDummyProductsAsSentAsDummyToWehkamp(dummyProductIDsInFile, db); } SaveShipmentInformation(vendorID, shipmentInfo, db); db.CompleteTransaction(); } catch (Exception e) { db.AbortTransaction(); log.AuditError("Something went wrong while updating the order dispatched status or saving the files in the wehkamp drives", e); } } log.InfoFormat("Finished processing Shipment Notification for VendorID {0}", vendorID); } //end foreach (var vendorID in vendorIDsToProcess) log.InfoFormat("Finished processing Shipment Notification"); _monitoring.Notify(Name, 1); }
private List <ProductInformation> GetProductInformationData(int vendorID) { try { using (var db = new PetaPoco.Database(Environments.Current.Connection, "System.Data.SqlClient")) { db.CommandTimeout = 600; //10 minutes var products = db.Fetch <ProductInformation>(string.Format(QueryHelper.GetProductInformationQuery(), vendorID, VendorSettingsHelper.ExportOnlyProductsOlderThanXXXMinutes(vendorID))); return(products); } } catch (Exception ex) { log.Error("Error while retrieving products to export to Wehkamp.", ex); return(null); } }
protected override void Process() { _monitoring.Notify(Name, 0); log.InfoFormat("Start processing Product Information"); var vendorIDsToProcess = VendorSettingsHelper.GetVendorIDsToExportToWehkamp(log); foreach (var vendorID in vendorIDsToProcess) { _monitoring.Notify(Name, vendorID); log.InfoFormat("Start processing Product Information for VendorID {0}", vendorID); var productIDsInFile = new List <int>(); //Get all products that we need to export to Wehkamp var products = GetProductInformationData(vendorID); if (products == null || products.Count == 0) { log.InfoFormat("No 'export to wehkamp' products found for VendorID {0}", vendorID); continue; } //Add all products to the artikelInformatie file var artInfo = new artikelInformatie(); log.InfoFormat("Start processing {0} products for VendorID {1}", products.Count, vendorID); var start = DateTime.Now; var processedCount = 0; foreach (var product in products) { artikelInformatieArtikel artikel; try { artikel = CreateNewArtikelInformatieArtikel(product); productIDsInFile.Add(product.ProductID); } catch (Exception e) { log.AuditError(string.Format("Can't create Wehkamp article for product: id='{0}' - vendoritemnumber='{1}'. Product isn't exported to Wehkamp", product.ProductID, product.VendorItemNumber), e); continue; } var sizes = GetProductSizes(vendorID, product.ProductID); foreach (var size in sizes) { artikel.maatlijst.Add(CreateNewArtikelInformatieMaatGegevens(size)); } artInfo.artikel.Add(artikel); processedCount++; if (DateTime.Now > start.AddSeconds(30)) { log.InfoFormat("Processed {0} products for VendorID {1}", processedCount, vendorID); start = DateTime.Now; } } //Create productattributes (artikelEigenschap) for all products in artikelInformatie file var artikelEigenschapData = CreateProductAttributes(products); //Save data to disk log.InfoFormat("Start saving Product Information"); var productInformationSaved = SaveProductInformation(vendorID, artInfo); log.InfoFormat("Start saving Product Attributes"); var productAttributesSaved = SaveProductAttributes(vendorID, artikelEigenschapData); if (productInformationSaved && productAttributesSaved) { //Set all products as SentToWehkamp = true log.InfoFormat("Start setting products as SentToWehkamp"); SetProductsAsSentToWehkamp(productIDsInFile); //Remove SentAsDummy attribute if sent before as a dummy product log.InfoFormat("Start cleaning SentAsDummy attribute"); RemoveSentAsDummy(productIDsInFile); //Process products which needs a price update file ProcessResendPriceUpdateToWehkampProducts(products, vendorID); } log.InfoFormat("Finished processing Product Information for VendorID {0}", vendorID); } //end foreach (var vendorID in vendorIDsToProcess) log.InfoFormat("Finished processing Product Information"); _monitoring.Notify(Name, 1); }
private static artikelEigenschap CreateProductAttributes(List <ProductInformation> products) { var eigenschap = new artikelEigenschap(); foreach (var information in products) { var artEigenschap = new artikelEigenschapArtikel { artikelNummer = information.Artikelnummer, kleurNummer = information.Kleurnummer, eigenschaplijst = new List <artikelEigenschapArtikelEigenschapGegevens>() }; artEigenschap.eigenschaplijst.Add(new artikelEigenschapArtikelEigenschapGegevens { eigenschap = "Geslacht", eigenschapWaarde = VendorItemHelper.GetWehkampGender(information.VendorItemNumber, information.VendorID) }); artEigenschap.eigenschaplijst.Add(new artikelEigenschapArtikelEigenschapGegevens { eigenschap = "Kleur", eigenschapWaarde = information.WehkampKleuromschrijving }); artEigenschap.eigenschaplijst.Add(new artikelEigenschapArtikelEigenschapGegevens { eigenschap = "Materiaal", eigenschapWaarde = information.MateriaalomschrijvingWehkamp }); artEigenschap.eigenschaplijst.Add(new artikelEigenschapArtikelEigenschapGegevens { eigenschap = "Merk", eigenschapWaarde = VendorSettingsHelper.GetMerkName(information.VendorID) }); var wehkampSleeveLength = VendorItemHelper.GetWehkampSleeveLength(information.VendorItemNumber, information.VendorID); if (!string.IsNullOrEmpty(wehkampSleeveLength)) { artEigenschap.eigenschaplijst.Add(new artikelEigenschapArtikelEigenschapGegevens { eigenschap = "Mouwlengte", eigenschapWaarde = wehkampSleeveLength }); } if (information.VendorID == 25) { if (!string.IsNullOrEmpty(information.Dessin)) { artEigenschap.eigenschaplijst.Add(new artikelEigenschapArtikelEigenschapGegevens { eigenschap = "Dessin", eigenschapWaarde = information.Dessin }); } if (!string.IsNullOrEmpty(information.Kraagvorm)) { artEigenschap.eigenschaplijst.Add(new artikelEigenschapArtikelEigenschapGegevens { eigenschap = "Kraagvorm", eigenschapWaarde = information.Kraagvorm }); } if (!string.IsNullOrEmpty(information.Pijpwijdte)) { artEigenschap.eigenschaplijst.Add(new artikelEigenschapArtikelEigenschapGegevens { eigenschap = "Pijpwijdte", eigenschapWaarde = information.Pijpwijdte }); } } eigenschap.artikel.Add(artEigenschap); } return(eigenschap); }
protected override void Process() { _monitoring.Notify(Name, 0); log.InfoFormat("Start processing Stock Return Request Confirmation Import"); log.InfoFormat("Get messages to process"); var files = MessageHelper.GetMessagesByStatusAndType(WehkampMessageStatus.Created, MessageHelper.WehkampMessageType.StockReturnRequestConfirmation); log.InfoFormat("Found {0} messages to process", files.Count); foreach (var file in files) { var wehkampOrderID = -1; try { log.Info(string.Format("{0} - Loading file: {1}", Name, file.Filename)); retourUitslag stockReturnRequestConfirmation; var result = retourUitslag.LoadFromFile(Path.Combine(file.Path, file.Filename), out stockReturnRequestConfirmation); //Set message status MessageHelper.UpdateMessageStatus(file.MessageID, result ? WehkampMessageStatus.InProgress : WehkampMessageStatus.Error); if (result) { var vendorID = file.VendorID; var defaultWarehouseCode = VendorHelper.GetReturnDifferenceShopNumber(vendorID); var confirmationItems = new List <StockReturnRequestConfirmationLineObject>(); #region foreach (var confirmation in stockReturnRequestConfirmation.bevestiging) log.InfoFormat("Found {0} confirmations to process", stockReturnRequestConfirmation.uitslag.Count); var counter = 0; var sendingTime = DateTime.ParseExact(string.Format("{0} {1}", stockReturnRequestConfirmation.header.berichtDatumTijd.ToString("yyyy-MM-dd"), DateTime.Now.ToString("HH:mm:ss")), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); var groupedUitslag = from u in stockReturnRequestConfirmation.uitslag group u by new { u.artikelNummer, u.kleurNummer, u.maat } into gu select new retourUitslagUitslag { artikelNummer = gu.Key.artikelNummer, kleurNummer = gu.Key.kleurNummer, maat = gu.Key.maat, locusStatus = "not used", verzondenAantal = gu.Sum(u => int.Parse(u.verzondenAantal)).ToString(CultureInfo.InvariantCulture) }; //foreach (var confirmation in stockReturnRequestConfirmation.uitslag) foreach (var confirmation in groupedUitslag) { int orderID; int orderLineID; //create object var productID = Helpers.ProductHelper.GetProductIDByWehkampData(confirmation.artikelNummer, confirmation.kleurNummer, confirmation.maat, vendorID); if (StockReturnHelper.OrderLineExistForProductAndOrderType((int)OrderTypes.ReturnOrder, productID)) { orderLineID = StockReturnHelper.GetLastOrderLineIDByOrderTypeAndProductID((int)OrderTypes.ReturnOrder, productID); orderID = StockReturnHelper.GetOrderIDByOrderLineID(orderLineID); } else { //Order doesn't exists in the database. //Create order and orderline for this product. //Check if we already created an order for this file if (wehkampOrderID == -1) { var receivedDate = DateTime.ParseExact(string.Format("{0} {1}", stockReturnRequestConfirmation.header.berichtDatumTijd.ToString("yyyy-MM-dd"), DateTime.Now.ToString("HH:mm:ss")), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); wehkampOrderID = StockReturnHelper.CreateOrderRowForWehkampReturns(VendorSettingsHelper.GetConnectorIDByVendorID(vendorID), Path.GetFileNameWithoutExtension(file.Filename), file.Filename, receivedDate.ToUniversalTime()); } orderLineID = StockReturnHelper.CreateOrderLineRow(wehkampOrderID, productID, vendorID, defaultWarehouseCode.ToString(CultureInfo.InvariantCulture)); orderID = wehkampOrderID; } var c = new StockReturnRequestConfirmationLineObject { OrderID = orderID, OrderLineID = orderLineID, ProductID = productID, Quantity = int.Parse(confirmation.verzondenAantal) }; confirmationItems.Add(c); if (counter % 25 == 0) { log.Debug(string.Format("Loaded {0} confirmations from file", counter)); } counter++; } counter = 0; foreach (var item in confirmationItems) { StockReturnHelper.CreateOrderLedgerRow(item.OrderLineID, item.Quantity, sendingTime.ToUniversalTime()); if (counter % 25 == 0) { log.Debug(string.Format("Inserted {0} confirmations into database", counter)); } counter++; } #endregion MessageHelper.Archive(file.MessageID); } } catch (Exception exFile) { log.Fatal(string.Format("Error processing file {0} ", file.Filename), exFile); MessageHelper.Error(file.MessageID); } } log.InfoFormat("Finished processing Stock Return Request Confirmation Import"); _monitoring.Notify(Name, 1); }
private void UploadMessageFiles(int vendorID) { var pluginLocation = GetPluginLocation(); var typesXsdPath = Path.Combine(pluginLocation, "XSD", "wdpTypes.xsd"); // first move all files to the outgoing directory var directories = MessageHelper.GetMessageFolders("To", vendorID); foreach (var directory in directories) { foreach (var file in Directory.EnumerateFiles(directory)) { var filename = Path.GetFileName(file); if (filename == null) { continue; } var wkm = MessageHelper.GetMessageByFilename(filename); if (wkm != null && (wkm.MessageType == MessageHelper.WehkampMessageType.ProductAttribute || wkm.MessageType == MessageHelper.WehkampMessageType.ShipmentNotification) && wkm.LastModified.HasValue && wkm.LastModified.Value.AddMinutes(20) > DateTime.Now.ToUniversalTime()) { continue; } //Only export files with the status Success if (wkm == null || wkm.Status != WehkampMessageStatus.Success) { continue; } File.Move(Path.Combine(directory, filename), Path.Combine(ConfigurationHelper.OutgoingFilesRootFolder, vendorID.ToString(CultureInfo.InvariantCulture), filename)); } } var ftpClient = SftpHelper.CreateClient(VendorSettingsHelper.GetSFTPSetting(vendorID), CommunicatorHelper.GetWehkampPrivateKeyFilename(vendorID), "D1r@ct379"); if (ftpClient == null) { log.AuditCritical("SFTP failed to connect"); return; } // then we upload all of them var remoteFileList = new ArrayList(); if (ConfigurationHelper.ListFTPFilesCheck) { ftpClient.ListDirectory("TO_WK", remoteFileList); } var remoteFiles = (TElSftpFileInfo[])remoteFileList.ToArray(typeof(TElSftpFileInfo)); foreach (var file in Directory.EnumerateFiles(Path.Combine(ConfigurationHelper.OutgoingFilesRootFolder, vendorID.ToString(CultureInfo.InvariantCulture)))) { var filename = Path.GetFileName(file); var message = MessageHelper.GetMessageByFilename(filename); if (message == null || (message.Status != WehkampMessageStatus.ErrorUpload && message.Status != WehkampMessageStatus.Success)) { continue; } if (message.Status == WehkampMessageStatus.Success) { MessageHelper.ResetMessageAttempt(message.MessageID); } var error = false; MessageHelper.UpdateMessageAttempt(message.MessageID); if (!ConfigurationHelper.ListFTPFilesCheck || remoteFiles.All(c => c.Name != file)) { try { var path = Path.Combine(ConfigurationHelper.OutgoingFilesRootFolder, message.VendorID.ToString(CultureInfo.InvariantCulture), filename); var doc = XDocument.Load(path); if (doc.Root == null) { continue; } if (_downloadedFiles.ContainsKey(filename)) { _downloadedFiles[filename] = message.MessageID; } else { _downloadedFiles.Add(filename, message.MessageID); } MessageHelper.UpdateMessageRecieved(message.MessageID, DateTime.Now.ToUniversalTime()); var xsdPath = Path.Combine(pluginLocation, "XSD", string.Format("{0}.xsd", doc.Root.Name.LocalName)); if (!File.Exists(xsdPath) || !File.Exists(typesXsdPath)) { throw new FileNotFoundException(String.Format("Cannot find Xsd validation files\n{0}\n{1}", xsdPath, typesXsdPath)); } var schemas = new XmlSchemaSet(); schemas.Add(null, XElement.Load(xsdPath).CreateReader()); schemas.Add(null, XElement.Load(typesXsdPath).CreateReader()); schemas.Compile(); doc.Validate(schemas, null); ftpClient.UploadFile(path, Path.Combine("TO_WK", filename).ToUnixPath(), TSBFileTransferMode.ftmOverwrite); File.Move(Path.Combine(ConfigurationHelper.OutgoingFilesRootFolder, message.VendorID.ToString(CultureInfo.InvariantCulture), filename), Path.Combine(ConfigurationHelper.ArchivedRootFolder, message.VendorID.ToString(CultureInfo.InvariantCulture), filename)); MessageHelper.UpdateMessageStatus(message.MessageID, WehkampMessageStatus.Archived); MessageHelper.UpdateMessagePath(message.MessageID, ConfigurationHelper.ArchivedRootFolder); MessageHelper.UpdateMessageSent(message.MessageID, DateTime.Now.ToUniversalTime()); } catch (Exception e) { if (e is XmlSchemaValidationException) { MessageHelper.UpdateMessageStatus(_downloadedFiles[filename], WehkampMessageStatus.ValidationFailed); log.AuditError(string.Format("XML validation failed for file {0} : {1}\n{2}", filename, e.Message, e.StackTrace)); } else { MessageHelper.UpdateMessageStatus(message.MessageID, WehkampMessageStatus.ErrorUpload); log.AuditError(string.Format("Cannot upload file {0}", filename), e); } MessageHelper.UpdateMessagePath(message.MessageID, ConfigurationHelper.OutgoingFilesRootFolder); error = true; } } else { MessageHelper.UpdateMessageStatus(message.MessageID, WehkampMessageStatus.ErrorUpload); MessageHelper.UpdateMessagePath(message.MessageID, ConfigurationHelper.OutgoingFilesRootFolder); log.AuditError(string.Format("Cannot upload file {0}, File already exists on remote server.", filename)); error = true; } if (error && message.Attempts + 1 > 10) { MessageHelper.UpdateMessageStatus(message.MessageID, WehkampMessageStatus.MaxRetryExceeded); File.Move(Path.Combine(ConfigurationHelper.OutgoingFilesRootFolder, filename), Path.Combine(ConfigurationHelper.FailedFilesRootFolder, filename)); MessageHelper.UpdateMessagePath(message.MessageID, ConfigurationHelper.FailedFilesRootFolder); } } ftpClient.Dispose(); }
private bool ProcessProductImages(Database db, List <ProductMedia> productMedias, int vendorID) { if (!productMedias.Any()) { return(true); } var attributeid = db.FirstOrDefault <int>("SELECT AttributeID FROM ProductAttributeMetaData WHERE AttributeCode = @0", "WehkampProductNumber"); if (attributeid == 0) { throw new ConfigurationErrorsException("Attribute \"WehkampProductNumber\" is missing from the ProductAttributeMetadata table"); } var wehkampPids = new Dictionary <int, string>(); if (productMedias.Count <= 500) { var productMediaArray = string.Join(",", productMedias.Select(c => c.ProductID).ToArray()); wehkampPids = db.Dictionary <int, string>(string.Format("SELECT ProductID, Value FROM ProductAttributeValue WHERE AttributeID = {1} AND ProductID IN ({0})", productMediaArray, attributeid)); } else { for (var i = 0; i < productMedias.Count; i += 500) { var productMediaArray = string.Join(",", productMedias.Skip(i).Take(Math.Min(500, productMedias.Count - i)).Select(c => c.ProductID).ToArray()); var temp = db.Dictionary <int, string>(string.Format("SELECT ProductID, Value FROM ProductAttributeValue WHERE AttributeID = {1} AND ProductID IN ({0})", productMediaArray, attributeid)); foreach (var pm in temp) { if (!wehkampPids.ContainsKey(pm.Key)) { wehkampPids.Add(pm.Key, pm.Value); } } } } var ftpClient = SftpHelper.CreateClient(VendorSettingsHelper.GetSFTPSetting(vendorID), CommunicatorHelper.GetWehkampPrivateKeyFilename(vendorID), "D1r@ct379"); if (ftpClient == null) { log.AuditCritical("SFTP failed to connect"); return(false); } string manid, path, newFilename; int index; foreach (var media in productMedias) { if (!wehkampPids.ContainsKey(media.ProductID)) { continue; } manid = media.ManufacturerID.Split(' ')[0]; if (string.IsNullOrEmpty(manid)) { continue; } index = media.ImagePath.LastIndexOf(manid, StringComparison.InvariantCultureIgnoreCase); if (index < 0) { continue; } path = Path.Combine(ConfigurationHelper.FTPMediaDirectory, media.ImagePath); if (!File.Exists(path)) { log.Error(string.Format("Could not find image file {0}", path)); continue; } newFilename = string.Format("{0}_{1}", wehkampPids[media.ProductID], media.ImagePath.Substring(index)); try { //Only upload files ending on: //1. _b.png - Back //2. _f.png - Front //3. _h.png - Hoover //if (newFilename.ToLowerInvariant().EndsWith("_b.png") || newFilename.ToLowerInvariant().EndsWith("_f.png") || newFilename.ToLowerInvariant().EndsWith("_h.png")) if (newFilename.ToLowerInvariant().EndsWith("_b.png") || newFilename.ToLowerInvariant().EndsWith("_f.png") || newFilename.ToLowerInvariant().EndsWith("_h.png")) { ftpClient.UploadFile(path, Path.Combine("TO_WK", "Pictures", newFilename).ToUnixPath(), TSBFileTransferMode.ftmOverwrite); } } catch (Exception e) { log.Error(string.Format("Cannot upload file : {0}", media.ImagePath), e); return(false); } } return(true); }
private void ProcessResendProductInformationToWehkampProducts(IEnumerable <ProductInformationSize> products) { var productIDs = products.Where(p => p.ResendProductInformationToWehkamp != null && p.ResendProductInformationToWehkamp.ToLowerInvariant() == "true").Select(product => product.ProductID).ToList(); if (productIDs.Count == 0) { return; } var sql = string.Empty; try { using (var db = new PetaPoco.Database(Environments.Current.Connection, "System.Data.SqlClient")) { db.CommandTimeout = 600; //10 minutes sql = string.Format("UPDATE ProductAttributeValue SET Value = 'false' WHERE AttributeID = (SELECT AttributeID FROM ProductAttributeMetaData pamd WHERE pamd.AttributeCode = 'SentToWehkamp') AND ProductID IN (SELECT DISTINCT ParentProductID FROM Product WHERE ProductID IN ({0}))", string.Join(",", productIDs.ToArray())); db.Execute(sql); sql = string.Format("DELETE FROM ProductAttributeValue WHERE AttributeID = {0} AND ProductID IN (SELECT DISTINCT ParentProductID FROM Product WHERE ProductID IN ({1}))", VendorSettingsHelper.GetResendProductInformationToWehkampAttributeID(), string.Join(",", productIDs.ToArray())); db.Execute(sql); } } catch (Exception ex) { log.AuditError(String.Format("ProcessResendPriceUpdateToWehkampProducts. ProductID's : {0}; SQL used: {1}", string.Join(",", productIDs.ToArray()), sql), ex); } }
protected override void Process() { _monitoring.Notify(Name, 0); var vendorIDsToProcess = VendorSettingsHelper.GetVendorIDsToExportToWehkamp(log); foreach (var vendorID in vendorIDsToProcess) { _monitoring.Notify(Name, vendorID); var productIDs = new List <int>(); var id = vendorID; var messages = MessageHelper.GetMessagesByStatusAndType(Enums.WehkampMessageStatus.Created, MessageHelper.WehkampMessageType.ProductRelation).Where(m => m.VendorID == id); foreach (var message in messages) { log.Info(string.Format("{0} - Loading file: {1}", Name, message.Filename)); MessageHelper.UpdateMessageStatus(message.MessageID, Enums.WehkampMessageStatus.InProgress); artikelRelatie relatieData; var loaded = artikelRelatie.LoadFromFile(Path.Combine(message.Path, message.Filename), out relatieData); if (!loaded) { log.AuditError(string.Format("Error while loading file {0}", message.Filename)); MessageHelper.Error(message); continue; } try { using (var db = new Database(Environments.Current.Connection, "System.Data.SqlClient")) { var attributeID = db.FirstOrDefault <int>(string.Format("SELECT AttributeID FROM ProductAttributeMetaData WHERE AttributeCode = '{0}'", "WehkampProductNumber")); if (attributeID == 0) { throw new ConfigurationErrorsException("Attribute \"WehkampProductNumber\" is missing from the ProductAttributeMetadata table"); } foreach (var rel in relatieData.relatie) { var productID = ProductHelper.GetProductIDByWehkampData(rel.artikelNummer, rel.kleurNummer, message.VendorID); if (productID == 0) { log.Error(string.Format("No product could be found with VendorItemNumber containing {0} and {1}", rel.artikelNummer, rel.kleurNummer)); continue; } productIDs.Add(productID); var attributevalueid = db.FirstOrDefault <int>(string.Format("SELECT AttributeValueID FROM ProductAttributeValue WHERE AttributeID = '{0}' AND ProductID = '{1}'", attributeID, productID)); if (attributevalueid == 0) { db.Execute(string.Format("INSERT INTO ProductAttributeValue (AttributeID, ProductID, Value, CreatedBy, CreationTime) VALUES ('{0}', '{1}', '{2}', '{3}', getdate())", attributeID, productID, rel.wehkampArtikelNummer, 1)); } else { db.Execute(string.Format("UPDATE ProductAttributeValue SET Value = '{1}', LastModifiedBy = '{2}', LastModificationTime = getdate() WHERE AttributeValueID = '{0}'", attributevalueid, rel.wehkampArtikelNummer, 1)); } } } } catch (Exception ex) { log.Fatal(string.Format("Error while processing file {0}", message.Filename), ex); MessageHelper.Error(message); continue; } MessageHelper.Archive(message); } //Process Images for all found products var pme = new ProductMediaExport(); pme.ProcessProductImages(productIDs, vendorID); } _monitoring.Notify(Name, 1); }
protected override void Process() { _monitoring.Notify(Name, 0); log.InfoFormat("Start processing Sales Order Import"); log.InfoFormat("Get messages to process"); var salesOrderFiles = MessageHelper.GetMessagesByStatusAndType(WehkampMessageStatus.Created, MessageHelper.WehkampMessageType.SalesOrder); log.InfoFormat("Found {0} messages to process", salesOrderFiles.Count); foreach (var file in salesOrderFiles) { log.Info(string.Format("{0} - Loading file: {1}", Name, file.Filename)); kassaInformatie salesOrder; var result = kassaInformatie.LoadFromFile(Path.Combine(file.Path, file.Filename), out salesOrder); //Set message status MessageHelper.UpdateMessageStatus(file.MessageID, result ? WehkampMessageStatus.InProgress : WehkampMessageStatus.Error); var salesOrdersImported = false; if (result) { var vendorID = file.VendorID; var connectorID = VendorSettingsHelper.GetConnectorIDByVendorID(vendorID); var orderItems = new List <SalesOrderObject>(); #region foreach (var so in salesOrder.kassabon) log.InfoFormat("Found {0} orders to process", salesOrder.kassabon.Count); var counter = 0; foreach (var so in salesOrder.kassabon) { var document = so.Serialize(); var receivedDate = DateTime.ParseExact(string.Format("{0} {1}", so.zendingDatum.ToString("yyyy-MM-dd"), DateTime.Now.ToString("HH:mm:ss")), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); var salesOrderItem = new SalesOrderObject { SalesOrderID = -1, Document = document, ConnectorID = connectorID, IsDispatched = 1, ReceivedDate = receivedDate.ToUniversalTime(), IsDropShipment = 1, HoldOrder = 0, WebsiteOrderNumber = so.kassabonNummer, OrderType = (int)OrderTypes.SalesOrder, IsSalesOrder = so.klantMutatie.ToLower(CultureInfo.InvariantCulture) == "verkoop" }; foreach (var r in so.kassabonregel) { var quantity = int.Parse(r.verkoopAantal, CultureInfo.InvariantCulture); var productID = ProductHelper.GetProductIDByWehkampData(r.artikelNummer, r.kleurNummer, r.maat, vendorID); if (productID != 0) //ProductHelper returns FirstOrDefault of the productid, which means it will have the value 0 when it can't be found in VendorAssortment. If we don't check for this here it will break when inserting an orderline. { var soLine = new SalesOrderLineObject { ProductID = productID, Quantity = quantity, BasePrice = -1, UnitPrice = r.factuurBedrag + r.kortingBedrag, // + korting bedrag per item Price = (r.factuurBedrag + r.kortingBedrag) * quantity, // + korting bedrag per item LineDiscount = r.kortingBedrag * quantity, //totaal korting bedrag (dus voor alle items totaal) IsDispatched = 1, }; salesOrderItem.SalesOrderLines.Add(soLine); } else { log.ErrorFormat("Unable to find ProductID in VendorAssortment for artikelNummer: {0} with kleurNummer: {1}, maat: {2} and vendorID: {3}. Aborting the processing of this Kassabon.", r.artikelNummer, r.kleurNummer, r.maat, vendorID); MessageHelper.UpdateMessageStatus(file.MessageID, WehkampMessageStatus.Error); return; } } orderItems.Add(salesOrderItem); counter++; if (counter % 25 == 0) { log.Debug(string.Format("Loaded {0} orders from file", counter)); } } log.Debug(string.Format("Loaded {0} orders from file", counter)); #endregion salesOrdersImported = ProcessSalesOrders(orderItems, vendorID); } else { log.Error(string.Format("Error loading file {0}", file.Filename)); MessageHelper.Error(file.MessageID); } if (salesOrdersImported) { MessageHelper.Archive(file.MessageID); } else { MessageHelper.UpdateMessageStatus(file.MessageID, WehkampMessageStatus.Error); } } log.InfoFormat("Finished processing Sales Order Import"); _monitoring.Notify(Name, 1); }
private void ProcessResendPriceUpdateToWehkampProducts(IEnumerable <ProductInformation> products, int vendorID) { var productIDs = products.Where(p => p.ResendPriceUpdateToWehkamp != null && p.ResendPriceUpdateToWehkamp.ToLowerInvariant() == "true").Select(product => product.ProductID).ToList(); if (productIDs.Count == 0) { return; } try { using (var db = new PetaPoco.Database(Environments.Current.Connection, "System.Data.SqlClient")) { db.CommandTimeout = 600; //10 minutes var sql = string.Format("UPDATE VendorPrice SET LastUpdated = GETDATE() WHERE VendorAssortmentID IN (SELECT VendorAssortmentID FROM VendorAssortment va INNER JOIN Product p ON p.ProductID = va.ProductID WHERE p.ParentProductID IN ({0}) AND va.VendorID = {1})", string.Join(",", productIDs.ToArray()), vendorID); db.Execute(sql); sql = string.Format("DELETE FROM ProductAttributeValue WHERE AttributeID = {0} AND ProductID IN ({1})", VendorSettingsHelper.GetResendPriceUpdateToWehkampAttributeID(), string.Join(",", productIDs.ToArray())); db.Execute(sql); } } catch (Exception ex) { log.AuditError(String.Format("ProcessResendPriceUpdateToWehkampProducts. ProductID's : {0}", string.Join(",", productIDs.ToArray())), ex); } }
private void DownloadMessageFiles(int vendorID) { var remoteFileList = new ArrayList(); _downloadedFiles = new Dictionary <string, decimal>(); var ftpClient = SftpHelper.CreateClient(VendorSettingsHelper.GetSFTPSetting(vendorID), CommunicatorHelper.GetWehkampPrivateKeyFilename(vendorID), "D1r@ct379"); if (ftpClient == null) { log.AuditCritical("SFTP failed to connect"); return; } remoteFileList.Clear(); var allianceDirectoryName = string.Format("TO_{0}", VendorSettingsHelper.GetAlliantieName(vendorID).ToUpperInvariant()); try { ftpClient.ListDirectory(allianceDirectoryName, remoteFileList); foreach (TElSftpFileInfo fileinfo in remoteFileList) { //log.Info(string.Format("Checking remote item '{0}'", fileinfo.Name)); if (fileinfo.Attributes.FileType != TSBSftpFileType.ftFile && (fileinfo.Attributes.FileType != TSBSftpFileType.ftUnknown && !fileinfo.Name.Contains(".xml"))) { //log.Info(string.Format("Not a file. Skip item '{0}'", fileinfo.Name)); continue; } var message = MessageHelper.GetMessageByFilename(fileinfo.Name); // if this is a second attempt, only try again if the validation has failed or there was an error downloading if (message != null && message.Status != WehkampMessageStatus.ErrorDownload && message.Status != WehkampMessageStatus.ValidationFailed) { //log.Info(string.Format("Skip downloading file '{0}'", fileinfo.Name)); continue; } try { //log.Info(string.Format("Start downloading file '{0}'", fileinfo.Name)); ftpClient.DownloadFile(Path.Combine(allianceDirectoryName, fileinfo.Name).ToUnixPath(), Path.Combine(ConfigurationHelper.IncomingFilesRootFolder, vendorID.ToString(CultureInfo.InvariantCulture), fileinfo.Name)); ftpClient.RemoveFile(Path.Combine(allianceDirectoryName, fileinfo.Name).ToUnixPath()); } catch (Exception e) { log.AuditError(string.Format("Cannot access {0} over SFTP: {1}\n{2}", allianceDirectoryName, e.Message, e.StackTrace)); if (message != null) { MessageHelper.UpdateMessageStatus(message.MessageID, WehkampMessageStatus.ErrorDownload); } } finally { if (message != null) { MessageHelper.UpdateMessageAttempt(message.MessageID); if (message.Attempts + 1 >= 10) { MessageHelper.UpdateMessageStatus(message.MessageID, WehkampMessageStatus.MaxRetryExceeded); } } } if (message == null || message.Attempts + 1 < 10) { _downloadedFiles.Add(fileinfo.Name, message != null ? message.MessageID : -1); } } } catch (Exception e) { log.AuditError(string.Format("Cannot access {0} over SFTP: {1}\n{2}", allianceDirectoryName, e.Message, e.StackTrace)); } CreateMessagesFromDownloadedFiles(vendorID); ftpClient.Dispose(); }
private List <ProductInformationSize> GetProductsWithChangedPricesData(int vendorID) { try { using (var db = new PetaPoco.Database(Environments.Current.Connection, "System.Data.SqlClient")) { db.CommandTimeout = 600; //10 minutes var products = db.Fetch <ProductInformationSize>(string.Format(QueryHelper.GetProductsWithPriceChangesQuery(), vendorID, VendorSettingsHelper.GetLastPriceExportDateTime(vendorID).ToUniversalTime().ToString(MessageHelper.ISO8601, CultureInfo.InvariantCulture))); return(products); } } catch (Exception ex) { log.Error("Error while retrieving products to export to Wehkamp.", ex); return(null); } }