private void ReadStockFile() { var ftpManager = new FtpManager(_ftpSetting.FtpUri, null, false, true); var regex = FileNameRegex; foreach (var fileName in ftpManager.GetFiles()) { if (!regex.IsMatch(fileName)) { continue; } using (var stream = ftpManager.Download(Path.GetFileName(fileName))) { using (var streamReader = new StreamReader(stream)) { var engine = new FileHelperEngine(typeof(DatColStock)); var listOfVendorStock = engine.ReadStream(streamReader) as DatColStock[]; ProcessStock(listOfVendorStock); try { ftpManager.Upload(stream, Path.Combine("History", fileName)); } catch (Exception e) { } } } _archiveService.CopyToArchive(ftpManager.BaseUri.AbsoluteUri, SaveTo.StockDirectory, fileName); ftpManager.Delete(fileName); } }
private void ProcessFiles() { var ftpManager = new FtpManager(_ftpSetting.FtpUri, null, false, true); var regex = FileNameRegex; foreach (var fileName in ftpManager.GetFiles()) { if (!regex.IsMatch(fileName)) { continue; } using (var stream = ftpManager.Download(Path.GetFileName(fileName))) { using (var streamReader = new StreamReader(stream)) { try { var engine = new FileHelperEngine(typeof(DatColPurchaseOrder)); var listofPickTickets = engine.ReadStream(streamReader) as DatColPurchaseOrder[]; ProcessFile(listofPickTickets); _archiveService.CopyToArchive(ftpManager.BaseUri.AbsoluteUri, SaveTo.PurchaseOrderDirectory, fileName); ftpManager.Delete(fileName); } catch (Exception) { _log.AuditError(string.Format("Failed to process the Purchase order file. File name: '{0}'", fileName)); } } } } }
//private const int UnMappedID = -1; protected override void SyncProducts() { var config = GetConfiguration(); FtpManager downloader = new FtpManager( config.AppSettings.Settings["AlphaFtpUrl"].Value, config.AppSettings.Settings["AlphaStockPath"].Value, config.AppSettings.Settings["AlphaUserName"].Value, config.AppSettings.Settings["AlphaPassword"].Value, false, true, log);//new FtpDownloader("test/"); log.AuditInfo("Starting stock import process"); using (var unit = GetUnitOfWork()) { // log.DebugFormat("Found {0} files for Alpha process", downloader.Count()); foreach (var file in downloader) { if (!Running) { break; } log.InfoFormat("Processing file: {0}", file.FileName); XDocument doc = null; using (file) { try { using (var reader = XmlReader.Create(file.Data)) { reader.MoveToContent(); doc = XDocument.Load(reader); if (ProcessXML(doc, unit.Scope)) { log.InfoFormat("Succesfully processed file: {0}", file.FileName); downloader.Delete(file.FileName); } else { log.InfoFormat("Failed to process file: {0}", file.FileName); downloader.MarkAsError(file.FileName); } } } catch (Exception ex) { log.AuditError(String.Format("Failed to load xml for file: {0}", file.FileName), ex); downloader.MarkAsError(file.FileName); continue; } } } unit.Save(); } }
private void ReadCustomerInformation() { _ftpSetting.Path = _vendorSettingRepo.GetVendorSetting(SapphVendorID, CustomerInformationDirectorySettingKey); var ftpManager = new FtpManager(_ftpSetting.FtpUri, null, false, usePassive: true); var regex = FileNameRegex; foreach (var fileName in ftpManager.GetFiles()) { if (!regex.IsMatch(fileName)) { continue; } try { _log.Info(string.Format("Processing file: {0}", fileName)); using (var stream = ftpManager.Download(Path.GetFileName(fileName))) { using (var excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream)) { excelReader.IsFirstRowAsColumnNames = true; var result = excelReader.AsDataSet(); var dt = result.Tables[0]; var customerInformationList = ( from ci in dt.AsEnumerable() select new DatColCustomerInformation { CustomerNumber = ci.Field <string>(ColumnCustomerNumber), SupplierName = ci.Field <string>(ColumnSupplierName), SupplierAdress = ci.Field <string>(ColumnSupplierAdress), ExpeditionCity = ci.Field <string>(ColumnExpeditionCity), ExpeditionPc = ci.Field <string>(ColumnExpeditionZip), ExpeditionCountry = ci.Field <string>(ColumnExpeditionCountry) }) .ToList(); UploadCustomerInformationToTnt(customerInformationList); } } _archiveService.CopyToArchive(ftpManager.BaseUri.AbsoluteUri, SaveTo.CustomerInformationDirectory, fileName); ftpManager.Delete(Path.GetFileName(fileName)); } catch (Exception e) { _log.Info(string.Format("Failed to process file {0}. Error: {1}", fileName, e.Message)); } } }
public static void Upload(string connectionString, string accountName, string accountKey, string containerName) { int numSongs = 100; /* String[] desiredGenres = { "trance", "techno", "electronic", "ambient" ,"house", * "beats", "big beat", "chill", "dub", "Electro", "grime", "hard psyche", * "illbient", "jungle", "leftfield", "plunderphonic", "trip", "turn"}; */ try { Console.WriteLine("Starting"); var azureService = new AzureService(accountName, accountKey); var uploadProcessor = new UploadProcessor(containerName, accountName, accountKey); var musicDao = new MusicDao(connectionString, null, uploadProcessor, azureService); IEnumerable <String> songs = FtpManager.List(); foreach (String song in songs) { if (song.Length > 0) { Console.WriteLine("Deleting: {0}", song); FtpManager.Delete(song); String songIdString = song.Substring(5); songIdString = songIdString.Substring(0, songIdString.IndexOf('.')); int songId = Convert.ToInt32(songIdString); var song1 = new SONG() { ID = songId, UPLOADED = false }; musicDao.UpdateSongUploadStatus(song1); } } musicDao.UploadSongs(numSongs); Console.WriteLine("Done"); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); throw; } }
public void DeleteSongs() { try { IEnumerable <String> songs = FtpManager.List(); foreach (String song in songs) { if (song.Length > 0) { FtpManager.Delete(song); } } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); throw; } }
private void ProcessNotifications(FtpManager manager, OrderResponseTypes responseType, IAuditLogAdapter log, Vendor vendor, string logPath, IUnitOfWork unit) { foreach (var file in manager) { try { using (MemoryStream fileStream = new MemoryStream(ReadFully(file.Data))) { string fileName = "VSN_" + responseType.ToString() + "_" + Guid.NewGuid() + ".csv"; using (FileStream s = File.Create(Path.Combine(logPath, fileName))) { s.Write(fileStream.ToArray(), 0, (int)fileStream.Length); } int orderID = 0; var parser = GetCSVFile(fileStream, responseType); var groupedOrders = (from p in parser group p by p["CustomerReference"] into od select new { OrderID = od.Key, OrderInf = od.ToList() }).ToDictionary(x => x.OrderID, x => x.OrderInf); string vsnResponseType = responseType.ToString(); foreach (var orderResp in groupedOrders) { int.TryParse(orderResp.Key, out orderID); var order = unit.Scope.Repository <Concentrator.Objects.Models.Orders.Order>().GetSingle(o => o.OrderID == orderID); OrderResponse response = null; if (order != null) { var responseHeader = orderResp.Value.FirstOrDefault(); int orderLineCounter = 0; switch (responseType) { case OrderResponseTypes.Acknowledgement: #region Acknowledgement response = new OrderResponse() { Currency = "EUR", ResponseType = responseType.ToString(), OrderID = orderID, OrderDate = DateTime.ParseExact(responseHeader[VSNAcknowledgement.OrderDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture), VendorDocumentNumber = responseHeader[VSNAcknowledgement.SalesOrderID.ToString()] }; foreach (var line in orderResp.Value) { int lineReference = 0; string referenceField = line[VSNAcknowledgement.CustomerLineReference.ToString()]; if (referenceField.Contains('/')) { int.TryParse(referenceField.Split('/')[0], out lineReference); } else { int.TryParse(referenceField, out lineReference); } //int.TryParse(line[VSNAcknowledgement.CustomerLineReference.ToString()], out lineReference); OrderLine oLine = order.OrderLines.Where(x => x.OrderLineID == lineReference).FirstOrDefault(); if (oLine == null) { string vendorItemNumber = line[VSNAcknowledgement.EANNumber.ToString()]; oLine = order.OrderLines.Where(x => x.Product != null && x.Product.VendorItemNumber == vendorItemNumber).FirstOrDefault(); } if (oLine != null && !oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == vsnResponseType)) { OrderResponseLine rLine = new OrderResponseLine() { OrderResponse = response, Backordered = StatusCodes(line[VSNAcknowledgement.StatusCode.ToString()]) == VSNStatusCode.Backorder ? int.Parse(line[VSNAcknowledgement.Quantity.ToString()]) : 0, Cancelled = StatusCodes(line[VSNAcknowledgement.StatusCode.ToString()]) == VSNStatusCode.Canceled ? int.Parse(line[VSNAcknowledgement.Quantity.ToString()]) : 0, Ordered = oLine.GetDispatchQuantity(), Description = line[VSNAcknowledgement.ProductName.ToString()], Invoiced = 0, Barcode = line[VSNAcknowledgement.EANNumber.ToString()], OrderLine = oLine, Price = ((decimal)(oLine.Price.HasValue ? oLine.Price.Value : 0)), Processed = false, Shipped = StatusCodes(line[VSNAcknowledgement.StatusCode.ToString()]) == VSNStatusCode.Picklist ? int.Parse(line[VSNAcknowledgement.Quantity.ToString()]) : 0, VendorItemNumber = line[VSNAcknowledgement.ProductCode.ToString()], Remark = string.Format("ReleaseDate {0}", line[VSNAcknowledgement.ReleaseDate.ToString()]) }; unit.Scope.Repository <OrderResponseLine>().Add(rLine); orderLineCounter++; } else { continue; } } #endregion break; case OrderResponseTypes.CancelNotification: #region CancelNotification response = new OrderResponse() { Currency = "EUR", ResponseType = responseType.ToString(), OrderID = orderID, OrderDate = DateTime.ParseExact(responseHeader[VSNCancel.OrderDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture), VendorDocumentNumber = responseHeader[VSNCancel.SalesOrderID.ToString()], VendorDocumentDate = DateTime.ParseExact(responseHeader[VSNCancel.Timestamp.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture) }; foreach (var line in orderResp.Value) { int lineReference = 0; string referenceField = line[VSNCancel.CustomerLineReference.ToString()]; if (referenceField.Contains('/')) { int.TryParse(referenceField.Split('/')[0], out lineReference); } else { int.TryParse(referenceField, out lineReference); } OrderLine oLine = order.OrderLines.Where(x => x.OrderLineID == lineReference).FirstOrDefault(); if (oLine == null) { string vendorItemNumber = line[VSNAcknowledgement.EANNumber.ToString()]; oLine = order.OrderLines.Where(x => x.Product != null && x.Product.VendorItemNumber == vendorItemNumber).FirstOrDefault(); } if (oLine != null && !oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == vsnResponseType)) { OrderResponseLine rLine = new OrderResponseLine() { OrderResponse = response, Backordered = 0, Cancelled = int.Parse(line[VSNCancel.Quantity.ToString()]), Ordered = oLine.GetDispatchQuantity(), Description = line[VSNCancel.ProductName.ToString()], Invoiced = 0, Barcode = line[VSNCancel.EANNumber.ToString()], OrderLine = oLine, Price = ((decimal)(oLine.Price.HasValue ? oLine.Price.Value : 0)), Processed = false, Shipped = 0, VendorItemNumber = line[VSNCancel.ProductCode.ToString()], Remark = line[VSNCancel.SalesOrderLineCancelReason.ToString()] }; unit.Scope.Repository <OrderResponseLine>().Add(rLine); orderLineCounter++; } else { continue; } } #endregion break; case OrderResponseTypes.ShipmentNotification: #region ShipmentNotification response = new OrderResponse() { Currency = "EUR", ResponseType = responseType.ToString(), OrderID = orderID, OrderDate = DateTime.ParseExact(responseHeader[VSNShipment.OrderDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture), VendorDocumentNumber = responseHeader[VSNShipment.SalesOrderID.ToString()], ShippingNumber = responseHeader[VSNShipment.PackListID.ToString()], ReqDeliveryDate = DateTime.ParseExact(responseHeader[VSNShipment.PacklistDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture) }; Customer cus = order.ShippedToCustomer; if (cus.CustomerName != responseHeader[VSNShipment.AddressName.ToString()] || cus.CustomerAddressLine1 != responseHeader[VSNShipment.Street.ToString()] || cus.HouseNumber != responseHeader[VSNShipment.HouseNumber.ToString()] || cus.PostCode.Replace(" ", "").ToUpper() != responseHeader[VSNShipment.ZipCode.ToString()].Replace(" ", "").ToUpper() || cus.City.ToUpper() != responseHeader[VSNShipment.City.ToString()] || (!string.IsNullOrEmpty(responseHeader[VSNShipment.CountryName.ToString()]) && cus.Country != responseHeader[VSNShipment.CountryName.ToString()])) { cus = new Customer() { CustomerName = responseHeader[VSNShipment.AddressName.ToString()], CustomerAddressLine1 = responseHeader[VSNShipment.Street.ToString()], HouseNumber = responseHeader[VSNShipment.HouseNumber.ToString()], PostCode = responseHeader[VSNShipment.ZipCode.ToString()], Country = responseHeader[VSNShipment.CountryName.ToString()], City = responseHeader[VSNShipment.City.ToString()] } } ; response.ShippedToCustomer = cus; foreach (var line in orderResp.Value) { int lineReference = 0; string referenceField = line[VSNShipment.CustomerLineReference.ToString()]; if (referenceField.Contains('/')) { int.TryParse(referenceField.Split('/')[0], out lineReference); } else { int.TryParse(referenceField, out lineReference); } OrderLine oLine = order.OrderLines.Where(x => x.OrderLineID == lineReference).FirstOrDefault(); if (oLine == null) { string vendorItemNumber = line[VSNAcknowledgement.EANNumber.ToString()]; oLine = order.OrderLines.Where(x => x.Product != null && x.Product.VendorItemNumber == vendorItemNumber).FirstOrDefault(); } if (oLine != null && (!oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == vsnResponseType) || (!string.IsNullOrEmpty(line[VSNShipment.LabelReference.ToString()]) && !oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == responseType.ToString() && !string.IsNullOrEmpty(x.TrackAndTrace))))) { OrderResponseLine rLine = new OrderResponseLine() { OrderResponse = response, Backordered = 0, Cancelled = 0, Ordered = oLine.GetDispatchQuantity(), Description = line[VSNShipment.ProductName.ToString()], Invoiced = 0, Barcode = line[VSNShipment.EANNumber.ToString()], OrderLine = oLine, Price = ((decimal)(oLine.Price.HasValue ? oLine.Price.Value : 0)), Processed = false, Shipped = int.Parse(line[VSNShipment.Quantity.ToString()]), VendorItemNumber = line[VSNShipment.ProductCode.ToString()], NumberOfUnits = line[VSNShipment.PackageType.ToString()] == "Doos" ? int.Parse(line[VSNShipment.PackageCount.ToString()]) : 0, NumberOfPallets = line[VSNShipment.PackageType.ToString()] != "Doos" ? int.Parse(line[VSNShipment.PackageCount.ToString()]) : 0, Unit = line[VSNShipment.PackageType.ToString()], Remark = string.Format("ReleaseDate {0}", line[VSNShipment.ReleaseDate.ToString()]), TrackAndTrace = line[VSNShipment.LabelReference.ToString()], TrackAndTraceLink = string.IsNullOrEmpty(line[VSNShipment.LabelReference.ToString()]) ? string.Empty : BuildTrackAndTraceNumber(line[VSNShipment.LabelReference.ToString()], responseHeader[VSNShipment.ZipCode.ToString()].Replace(" ", "").ToUpper()) }; unit.Scope.Repository <OrderResponseLine>().Add(rLine); orderLineCounter++; } else { continue; } } #endregion break; } if (orderLineCounter > 0) { response.VendorID = vendor.VendorID; response.ReceiveDate = DateTime.Now; response.VendorDocument = parser.Document; response.DocumentName = fileName; if (!response.VendorDocumentDate.HasValue) { response.VendorDocumentDate = DateTime.Now; } response.ReceiveDate = DateTime.Now; unit.Scope.Repository <OrderResponse>().Add(response); } } } unit.Save(); manager.Delete(file.FileName); } } catch (Exception ex) { log.AuditError("Error reading file", ex); } } }
private void ProcessInvoiceNotifications(FtpManager manager, OrderResponseTypes responseType, IAuditLogAdapter log, Vendor vendor, string logPath, IUnitOfWork unit) { foreach (var file in manager) { try { using (MemoryStream fileStream = new MemoryStream(ReadFully(file.Data))) { string fileName = "VSN_" + responseType.ToString() + "_" + Guid.NewGuid() + ".csv"; string filePath = Path.Combine(logPath, fileName); using (FileStream s = File.Create(filePath)) { s.Write(fileStream.ToArray(), 0, (int)fileStream.Length); } using (System.IO.TextReader readFile = new StreamReader(filePath)) { string line = string.Empty; using (MemoryStream salesLines = new MemoryStream(), salesInvoiceTotal = new MemoryStream(), salesInvoiceGrandTotal = new MemoryStream()) { using ( StreamWriter sw = new StreamWriter(salesLines), sw2 = new StreamWriter(salesInvoiceTotal), sw3 = new StreamWriter(salesInvoiceGrandTotal)) { int lineCount = 0; while ((line = readFile.ReadLine()) != null) { lineCount++; if (line.Contains("SalesInvoiceLine") || lineCount == 1) { sw.WriteLine(line); } else if (line.Contains("SalesInvoiceTotal")) { sw2.WriteLine(line); } else if (line.Contains("SalesInvoiceGrandTotal")) { sw3.WriteLine(line); } else if (!line.Contains("SalesInvoiceLine") && lineCount > 1 && !line.Contains("SalesInvoiceGrandTotal")) { sw3.WriteLine(line); } } sw.Flush(); salesLines.Position = 0; sw2.Flush(); salesInvoiceTotal.Position = 0; sw3.Flush(); salesInvoiceGrandTotal.Position = 0; var parser = GetInvoiceCSVFile(salesLines, typeof(VSNInvoice)).ToList(); var invoiveTotalParser = GetInvoiceCSVFile(salesInvoiceTotal, typeof(VSNInvoiceTotal)); var invoiceGrandTotalParser = GetInvoiceCSVFile(salesInvoiceGrandTotal, typeof(VSNInvoiceGrandTotal)); var firstOrderInInvoice = parser.FirstOrDefault(); var invoiceTotals = invoiveTotalParser.ToList(); int orderLineCounter = 0; var totalAmount = invoiceTotals.Sum(x => decimal.Parse(x[VSNInvoiceTotal.AmountVATIncluded.ToString()])); var totalExVat = invoiceTotals.Sum(x => decimal.Parse(x[VSNInvoiceTotal.AmountVATExcluded.ToString()])); var vatAmount = invoiceTotals.Sum(x => decimal.Parse(x[VSNInvoiceTotal.AmountVAT.ToString()])); var vatPercentage = invoiceTotals.Sum(x => decimal.Parse(x[VSNInvoiceTotal.VATPercentage.ToString()])); var shipmentCost = invoiceTotals.Where(x => x[VSNInvoiceTotal.SalesInvoiceTotal.ToString()].Trim().ToLower() == "orderkosten").Sum(x => decimal.Parse(x[VSNInvoiceTotal.AmountVATExcluded.ToString()])); #region InvoiceNotification var vsnResponseType = responseType.ToString(); var vsnInvoiceID = firstOrderInInvoice[VSNInvoice.SalesInvoiceID.ToString()]; OrderResponse response = unit.Scope.Repository <OrderResponse>().GetSingle(x => x.VendorID == vendor.VendorID && x.InvoiceDocumentNumber == vsnInvoiceID && x.ResponseType == vsnResponseType); if (response == null) { response = new OrderResponse() { Currency = "EUR", ResponseType = responseType.ToString(), //OrderID = orderID, VendorDocumentNumber = string.Empty, InvoiceDate = DateTime.ParseExact(firstOrderInInvoice[VSNInvoice.InvoiceDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture), InvoiceDocumentNumber = firstOrderInInvoice[VSNInvoice.SalesInvoiceID.ToString()], ShippingNumber = firstOrderInInvoice[VSNInvoice.PacklistID.ToString()], PaymentConditionCode = firstOrderInInvoice[VSNInvoice.PatymentConditionName.ToString()], ReqDeliveryDate = DateTime.ParseExact(firstOrderInInvoice[VSNInvoice.PacklistDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture), PaymentConditionDiscount = firstOrderInInvoice[VSNInvoice.DiscountPercentage.ToString()], TotalAmount = totalAmount, TotalExVat = totalExVat, VatAmount = vatAmount, VatPercentage = vatPercentage, ShipmentCost = shipmentCost }; } foreach (var p in parser) { try { int lineReference = 0; string referenceField = p[VSNInvoice.LineCustomerReference.ToString()]; if (referenceField.Contains('/')) { int.TryParse(referenceField.Split('/')[0], out lineReference); } else { int.TryParse(referenceField, out lineReference); } OrderLine oLine = unit.Scope.Repository <OrderLine>().GetSingle(x => x.OrderLineID == lineReference); if (oLine != null && !oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == vsnResponseType)) { OrderResponseLine rLine = new OrderResponseLine() { OrderResponse = response, Backordered = 0, Cancelled = 0, Ordered = oLine.GetDispatchQuantity(), Invoiced = int.Parse(p[VSNInvoice.Quantity.ToString()]), Barcode = p[VSNInvoice.EANNumberProduct.ToString()], OrderLine = oLine, Price = decimal.Parse(p[VSNInvoice.PriceDiscountIncluded.ToString()]), VatAmount = decimal.Parse(p[VSNInvoice.LineTotal.ToString()]), vatPercentage = decimal.Parse(p[VSNInvoice.VATPercentage.ToString()]), CarrierCode = p[VSNInvoice.DeliveryMethodName.ToString()], Processed = false, Shipped = 0, Remark = p[VSNInvoice.CustomerReference.ToString()] }; unit.Scope.Repository <OrderResponseLine>().Add(rLine); orderLineCounter++; } #endregion } catch (Exception) { log.AuditError("Failed to invoice line for VSN"); } } if (orderLineCounter > 0) { response.VendorID = vendor.VendorID; response.ReceiveDate = DateTime.Now; response.VendorDocument = parser + invoiveTotalParser.Document + invoiceGrandTotalParser.Document; response.DocumentName = fileName; if (!response.VendorDocumentDate.HasValue) { response.VendorDocumentDate = DateTime.Now; } response.ReceiveDate = DateTime.Now; unit.Scope.Repository <OrderResponse>().Add(response); } unit.Save(); manager.Delete(file.FileName); } } } } } catch (Exception ex) { log.AuditError("Error reading file", ex); } } }
private void CopyArticleInformationToTnt(string fileNameToCopy) { try { Vendor vendor; using (var unit = GetUnitOfWork()) { vendor = unit.Scope.Repository <Vendor>().GetSingle(x => x.Name.Equals("Sapph")); } var ftpAddress = vendor.VendorSettings.GetValueByKey("FtpAddress", string.Empty); var ftpUsername = HttpUtility.UrlEncode(vendor.VendorSettings.GetValueByKey("FtpUsername", string.Empty)); var ftpPassword = HttpUtility.UrlEncode(vendor.VendorSettings.GetValueByKey("FtpPassword", string.Empty)); var ftpPath = vendor.VendorSettings.GetValueByKey("Ax Ftp Dir ArticleInformation", string.Empty); var ftpUri = string.Format("ftp://{0}:{1}@{2}/{3}", ftpUsername, ftpPassword, ftpAddress, ftpPath); var tntFtpSetting = vendor.VendorSettings.GetValueByKey("TNTDestinationURI", string.Empty); var archiveDirectoryPath = vendor.VendorSettings.GetValueByKey("Archive Directory", string.Empty); var fileNameRegex = new Regex(".*\\.xml$", RegexOptions.IgnoreCase); var axaptaFtpManager = new FtpManager(ftpUri, null, false, usePassive: true); var tnTftpManager = new FtpManager(tntFtpSetting, log, usePassive: true); foreach (var articleInformatioFile in axaptaFtpManager.GetFiles()) { var fileName = Path.GetFileName(articleInformatioFile); if (!fileNameRegex.IsMatch(articleInformatioFile)) { continue; } if (fileName != null && !fileName.Equals(Path.GetFileName(fileNameToCopy))) { continue; } try { log.InfoFormat("Processing file {0}", articleInformatioFile); using (var stream = axaptaFtpManager.Download(fileName)) { tnTftpManager.Upload(stream, fileName); var archiveDirectory = SetArchiveDirectoryPath(archiveDirectoryPath, ftpPath); SaveStreamToFile(Path.Combine(archiveDirectory, fileName), stream); axaptaFtpManager.Delete(fileName); } return; } catch (Exception e) { log.ErrorFormat("Could not process file {0}! Error: {1}", articleInformatioFile, e.Message); } } } catch (Exception e) { log.AuditError("Sapph passthrough product information to TNT Failed", e); } }
private void ProcessNotifications(FtpManager manager, OrderResponseTypes responseType, IAuditLogAdapter log, Vendor vendor, string logPath, IUnitOfWork unit) { foreach (var file in manager) { bool error = false; try { if (!file.FileName.EndsWith(".XML")) { continue; } using (var reader = XmlReader.Create(file.Data)) { reader.MoveToContent(); XDocument xdoc = XDocument.Load(reader); string fileName = "Alpha_" + responseType.ToString() + "_" + Guid.NewGuid() + ".xml"; xdoc.Save(Path.Combine(logPath, fileName)); var orderDocuments = xdoc.Root.Elements("Order"); if (responseType == OrderResponseTypes.InvoiceNotification) { orderDocuments = xdoc.Root.Element("Invoice").Element("Orders").Elements("Order"); } int orderID = 0; foreach (var orderDocument in orderDocuments) { if (orderDocument.Element("Reference").Value.Contains('/')) { int.TryParse(orderDocument.Element("Reference").Value.Split('/')[0], out orderID); } else { int.TryParse(orderDocument.Element("Reference").Value, out orderID); } var order = unit.Scope.Repository <Concentrator.Objects.Models.Orders.Order>().GetSingle(o => o.OrderID == orderID); if (order != null) { OrderResponse response = null; if (responseType == OrderResponseTypes.InvoiceNotification) { response = new OrderResponse() { OrderID = order.OrderID, ResponseType = responseType.ToString(), VendorDocument = xdoc.ToString(), InvoiceDocumentNumber = xdoc.Root.Element("Invoice").Attribute("ID").Value, InvoiceDate = DateTime.Parse(xdoc.Root.Element("Invoice").Element("InvDate").Value), VatPercentage = decimal.Parse(xdoc.Root.Element("Invoice").Element("VatPercentage").Value), VatAmount = decimal.Parse(xdoc.Root.Element("Invoice").Element("VatAmount").Value), TotalGoods = decimal.Parse(xdoc.Root.Element("Invoice").Element("TotalGoods").Value), AdministrationCost = decimal.Parse(xdoc.Root.Element("Invoice").Element("AdministrationCost").Value), DropShipmentCost = decimal.Parse(xdoc.Root.Element("Invoice").Element("DropShipmentCost").Value), ShipmentCost = decimal.Parse(xdoc.Root.Element("Invoice").Element("ShipmentCost").Value), TotalExVat = decimal.Parse(xdoc.Root.Element("Invoice").Element("TotalExVat").Value), TotalAmount = decimal.Parse(xdoc.Root.Element("Invoice").Element("TotalAmount").Value), PaymentConditionDays = int.Parse(xdoc.Root.Element("Invoice").Element("PaymentConditionDays").Value), PaymentConditionDiscount = xdoc.Root.Element("Invoice").Element("PaymentConditionDiscount").Value, PaymentConditionDiscountDescription = xdoc.Root.Element("Invoice").Element("PaymentConditionDescription").Value, DespAdvice = orderDocument.Element("DespAdvice").Value, VendorDocumentNumber = orderDocument.Attribute("ID").Value }; } else { if (responseType == OrderResponseTypes.Acknowledgement) { response = new OrderResponse() { OrderID = order.OrderID, ResponseType = responseType.ToString(), VendorDocument = xdoc.ToString(), AdministrationCost = decimal.Parse(orderDocument.Element("AdministrationCost").Value), DropShipmentCost = decimal.Parse(orderDocument.Element("DropShipmentCost").Value), ShipmentCost = decimal.Parse(orderDocument.Element("ShipmentCost").Value), OrderDate = DateTime.Parse(orderDocument.Element("OrderDate").Value), VendorDocumentNumber = orderDocument.Attribute("ID").Value }; } if (responseType == OrderResponseTypes.ShipmentNotification) { response = new OrderResponse() { OrderID = order.OrderID, ResponseType = responseType.ToString(), VendorDocument = xdoc.ToString(), OrderDate = DateTime.Parse(orderDocument.Element("OrderDate").Value), ReqDeliveryDate = DateTime.Parse(orderDocument.Element("ReqDelDate").Value), ShippingNumber = orderDocument.Element("ShippingNr").Value, DespAdvice = orderDocument.Element("DespAdvice").Value, TrackAndTrace = orderDocument.Element("TrackAndTrace").Element("TrackAndTraceID").Value, TrackAndTraceLink = orderDocument.Element("TrackAndTrace").Element("TrackAndTraceURL").Value, VendorDocumentNumber = orderDocument.Attribute("ID").Value }; } } response.VendorID = vendor.VendorID; response.ReceiveDate = DateTime.Now; response.VendorDocument = orderDocument.ToString(); response.VendorDocumentDate = DateTime.Now; response.DocumentName = fileName; unit.Scope.Repository <OrderResponse>().Add(response); foreach (var line in orderDocument.Elements("OrderLines").Elements("OrderLine")) { OrderLine orderLine = null; if (line.Element("ReferenceOrderLine") != null) { orderLine = order.OrderLines.Where(x => x.OrderLineID == int.Parse(line.Element("ReferenceOrderLine").Value)).FirstOrDefault(); } if (orderLine == null) { string vendorItemNumber = line.Elements("Item").Where(x => x.Attribute("Type").Value == "O").Try(x => x.FirstOrDefault().Value, string.Empty); orderLine = order.OrderLines.Where(x => x.Product != null && x.Product.VendorItemNumber == vendorItemNumber.Replace("\n", "")).FirstOrDefault(); } if (orderLine != null) { int invoiced = 0; int ordered = 0; int backordered = 0; int shipped = 0; int deliverd = 0; if (responseType != OrderResponseTypes.InvoiceNotification) { ordered = line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Ordered") != null? int.Parse(line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Ordered").FirstOrDefault().Value) : 0; if (responseType == OrderResponseTypes.ShipmentNotification) { shipped = line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Shipped") != null? int.Parse(line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Shipped").FirstOrDefault().Value) : 0; } if (responseType == OrderResponseTypes.Acknowledgement) { int reserved = line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Reserved") != null? int.Parse(line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Reserved").FirstOrDefault().Value) : 0; backordered = ordered - reserved; } deliverd = line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Delivered") != null? int.Parse(line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Delivered").FirstOrDefault().Value) : 0; } else { invoiced = line.Elements("Quantity").Where(x => x.Attribute("Type") == null) != null? int.Parse(line.Elements("Quantity").Where(x => x.Attribute("Type") == null).FirstOrDefault().Value) : 0; } //Type of itemnumber: //"S" = Internal itemnumber //"O" = OEM number //"C" = Customer number //"E" = "EAN number" OrderResponseLine responseLine = new OrderResponseLine() { OrderResponse = response, OrderLineID = orderLine.OrderLineID, Ordered = ordered != 0 ? ordered : orderLine.Quantity, Backordered = backordered, Delivered = deliverd, Cancelled = responseType != OrderResponseTypes.InvoiceNotification ? orderLine.GetDispatchQuantity() - ordered : 0, Shipped = shipped, Invoiced = invoiced, Unit = line.Element("Unit").Value, Price = line.Element("Price") != null?decimal.Parse(line.Element("Price").Value) : 0, VendorLineNumber = line.Attribute("ID").Value, VendorItemNumber = line.Elements("Item").Where(x => x.Attribute("Type").Value == "S").Try(x => x.FirstOrDefault().Value, string.Empty), OEMNumber = line.Elements("Item").Where(x => x.Attribute("Type").Value == "O").Try(x => x.FirstOrDefault().Value, string.Empty), Barcode = line.Elements("Item").Where(x => x.Attribute("Type").Value == "E").Try(x => x.FirstOrDefault().Value, string.Empty), Description = line.Element("Description").Value }; if (line.Element("ReqDelDate") != null) { responseLine.DeliveryDate = DateTime.Parse(line.Element("ReqDelDate").Value); } unit.Scope.Repository <OrderResponseLine>().Add(responseLine); } } } else { log.AuditInfo("Received response does not match any order, ignore response"); manager.MarkAsError(file.FileName); error = true; continue; } } unit.Save(); if (!error) { manager.Delete(file.FileName); } } } catch (Exception e) { log.AuditError("Error reading file", e); //manager.MarkAsError(file.FileName); } } }
private void ProcessNotifications(FtpManager manager, OrderResponseTypes responseType, IAuditLogAdapter log, Vendor vendor, string logPath, IUnitOfWork unit) { //DataLoadOptions options = new DataLoadOptions(); //options.LoadWith<Concentrator.Objects.Orders.Order>(x => x.OrderLines); foreach (var file in manager) { bool error = false; try { using (var reader = XmlReader.Create(file.Data)) { reader.MoveToContent(); XDocument xdoc = XDocument.Load(reader); Guid vendorDocumentReference = Guid.NewGuid(); string fileName = "Lenmar_" + responseType.ToString() + "_" + vendorDocumentReference + ".xml"; xdoc.Save(Path.Combine(logPath, fileName)); XNamespace xName = "http://logictec.com/schemas/internaldocuments"; OrderResponse orderResponse = null; List <OrderResponseLine> orderResponseLines = null; IEnumerable <XElement> orderDocuments = null; if (responseType == OrderResponseTypes.InvoiceNotification) { orderDocuments = xdoc.Elements(xName + "Envelope").Elements("Messages").Elements(xName + "Invoice"); } else if (responseType == OrderResponseTypes.ShipmentNotification) { orderDocuments = xdoc.Elements(xName + "Envelope").Elements("Messages").Elements(xName + "AdvancedShipNotice"); } else if (responseType == OrderResponseTypes.Acknowledgement) { orderDocuments = xdoc.Elements(xName + "Envelope").Elements("Messages").Elements(xName + "POAck"); } foreach (var orderDocument in orderDocuments) { if (responseType == OrderResponseTypes.ShipmentNotification) { orderResponse = new OrderResponse { InvoiceDocumentNumber = orderDocument.Element("ASNHeader").Element("InvoiceNumber").Value, VendorDocumentNumber = orderDocument.Element("ASNHeader").Element("OrderID").Value, OrderID = int.Parse(orderDocument.Element("ASNHeader").Element("PartnerPO").Value), AdministrationCost = Decimal.Parse(orderDocument.Element("ASNHeader").Element("HandlingAmt").Value), TrackAndTrace = orderDocument.Element("ASNTrackingNumbers").Element("ASNTrackingNumberItem").Element("TrackingNumber").Value, OrderDate = DateTime.Parse(orderDocument.Element("ASNHeader").Element("PODateTime").Value), ResponseType = responseType.ToString() }; orderResponseLines = (from d in orderDocument.Elements("ASNItems").Elements("ASNItem") select new OrderResponseLine { OrderResponse = orderResponse, VendorLineNumber = d.Element("LineID").Value, OrderLineID = int.Parse(d.Element("PartnerLineID").Value), Ordered = int.Parse(d.Element("Qty").Value), Shipped = int.Parse(d.Element("QtyShipped").Value), VendorItemNumber = d.Element("SupplierSKU").Value, Price = decimal.Parse(d.Element("ItemPrice").Value) / 100, Barcode = d.Element("UPCCode").Value, Description = d.Element("Description").Value, OEMNumber = d.Element("MfgSKU").Value, DeliveryDate = DateTime.Parse(d.Element("ExpectedDeliveryDate").Value), TrackAndTrace = orderDocument.Element("ASNTrackingNumbers").Element("ASNTrackingNumberItem").Element("TrackingNumber").Value, RequestDate = DateTime.Parse(d.Element("RequestedShipDate").Value) }).ToList(); } else if (responseType == OrderResponseTypes.InvoiceNotification) { orderResponse = new OrderResponse { InvoiceDocumentNumber = orderDocument.Element("InvoiceHeader").Element("InvoiceNumber").Value, InvoiceDate = DateTime.Parse(orderDocument.Element("InvoiceHeader").Element("InvoiceDateTime").Value), PaymentConditionDays = int.Parse(orderDocument.Element("InvoiceHeader").Element("InvoiceDaysDue").Value), PaymentConditionDiscount = orderDocument.Element("InvoiceHeader").Element("DiscountDaysDue").Value, PaymentConditionDiscountDescription = orderDocument.Element("InvoiceHeader").Element("DiscountPercent").Value, TotalExVat = decimal.Parse(orderDocument.Element("InvoiceHeader").Element("InvoiceTotal").Value), VatAmount = decimal.Parse(orderDocument.Element("InvoiceHeader").Element("InvoiceTaxAmt").Value), VendorDocumentNumber = orderDocument.Element("InvoiceHeader").Element("OrderID").Value, OrderID = int.Parse(orderDocument.Element("InvoiceHeader").Element("PartnerPO").Value), AdministrationCost = Decimal.Parse(orderDocument.Element("InvoiceHeader").Element("HandlingAmt").Value), TrackAndTrace = orderDocument.Element("InvoiceTrackingNumbers").Element("InvoiceTrackingNumberItem").Element("TrackingNumber").Value, OrderDate = DateTime.Parse(orderDocument.Element("InvoiceHeader").Element("PODateTime").Value), ResponseType = responseType.ToString() }; orderResponseLines = (from d in orderDocument.Elements("InvoiceItems").Elements("InvoiceItem") select new OrderResponseLine { OrderResponse = orderResponse, VendorLineNumber = d.Element("LineID").Value, OrderLineID = int.Parse(d.Element("PartnerLineID").Value), Ordered = int.Parse(d.Element("Qty").Value), Invoiced = int.Parse(d.Element("QtyShipped").Value), VendorItemNumber = d.Element("SupplierSKU").Value, Price = decimal.Parse(d.Element("ItemPrice").Value) / 100, Barcode = d.Element("UPCCode").Value, Description = d.Element("Description").Value, OEMNumber = d.Element("MfgSKU").Value, DeliveryDate = DateTime.Parse(d.Element("ActualShipDate").Value), RequestDate = DateTime.Parse(d.Element("RequestedShipDate").Value) }).ToList(); } else if (responseType == OrderResponseTypes.Acknowledgement) { orderResponse = new OrderResponse { VendorDocumentNumber = orderDocument.Element("POAckHeader").Element("OrderID").Value, OrderID = int.Parse(orderDocument.Element("POAckHeader").Element("PartnerPO").Value), AdministrationCost = Decimal.Parse(orderDocument.Element("POAckHeader").Element("HandlingAmt").Value), OrderDate = DateTime.Parse(orderDocument.Element("POAckHeader").Element("PODateTime").Value), ResponseType = responseType.ToString() }; orderResponseLines = (from d in orderDocument.Elements("POAckItems").Elements("POAckItem") select new OrderResponseLine { OrderResponse = orderResponse, VendorLineNumber = d.Element("LineID").Value, OrderLineID = int.Parse(d.Element("PartnerLineID").Value), Ordered = int.Parse(d.Element("Qty").Value), Backordered = int.Parse(d.Element("QtyBackOrdered").Value), VendorItemNumber = d.Element("SupplierSKU").Value, Price = decimal.Parse(d.Element("ItemPrice").Value) / 100, Barcode = d.Element("UPCCode").Value, Description = d.Element("Description").Value, RequestDate = DateTime.Parse(d.Element("RequestedShipDate").Value) }).ToList(); } var order = unit.Scope.Repository <Concentrator.Objects.Models.Orders.Order>().GetSingle(o => o.OrderID == orderResponse.OrderID); if (order != null) { orderResponse.VendorID = vendor.VendorID; orderResponse.ReceiveDate = DateTime.Now; orderResponse.VendorDocument = xdoc.ToString(); orderResponse.VendorDocumentDate = DateTime.Now; orderResponse.DocumentName = fileName; unit.Scope.Repository <OrderResponse>().Add(orderResponse); unit.Scope.Repository <OrderResponseLine>().Add(orderResponseLines); } else { log.AuditInfo("Received response does not match any order, ignore response"); manager.MarkAsError(file.FileName); error = true; continue; } } } unit.Save(); if (!error) { manager.Delete(file.FileName); } } catch (Exception e) { throw e; } } }
protected override void Process() { var config = GetConfiguration(); FtpManager downloader = new FtpManager( config.AppSettings.Settings["AlphaFtpUrl"].Value, config.AppSettings.Settings["AlphaPath"].Value, config.AppSettings.Settings["AlphaUserName"].Value, config.AppSettings.Settings["AlphaPassword"].Value, false, true, log); log.AuditInfo("Starting import process"); var timer = Stopwatch.StartNew(); Dictionary <string, ProductIdentifier> relations = new Dictionary <string, ProductIdentifier>(); using (var unit = GetUnitOfWork()) { var inactiveVendorAssortment = unit.Scope.Repository <VendorAssortment>().GetAll(x => x.VendorID == VendorID).ToList(); bool processedSuceeded = true; foreach (var file in downloader) { if (!Running) { break; } log.InfoFormat("Processing file: {0}", file.FileName); var innerTime = Stopwatch.StartNew(); XDocument doc = null; using (file) { try { using (var reader = XmlReader.Create(file.Data)) { reader.MoveToContent(); doc = XDocument.Load(reader); } } catch (Exception ex) { log.AuditError(String.Format("Failed to load xml for file: {0}", file.FileName), ex); downloader.MarkAsError(file.FileName); continue; } } if (ProcessXml(doc, relations)) // Delete file if it is succesfully processed { log.InfoFormat("Succesfully processed file: {0}", file.FileName); downloader.Delete(file.FileName); } else { log.InfoFormat("Failed to process file: {0}", file.FileName); downloader.MarkAsError(file.FileName); processedSuceeded = false; } log.InfoFormat("File: {0} took: {1}", file.FileName, innerTime.Elapsed); } if (processedSuceeded) { inactiveVendorAssortment.ForEach(x => x.IsActive = false); } unit.Save(); SyncRelatedProducts(relations); timer.Stop(); log.AuditSuccess(string.Format("Total import process finished in: {0}", timer.Elapsed), "Alha International Import"); } }