public string GetTargetFileName(FileTransferConfigurationModel config,
                                        string qualSourceFile,
                                        int pickNo,
                                        int orderNo   = 0,
                                        int invoiceNo = 0)
        {
            string rc       = config.TargetFolder,
                   tempExtn = "CSV";

            if (config.TransferType == FileTransferType.Send)
            {
                rc = rc.AddString("/");
            }
            else
            {
                rc = rc.AddString("\\");
            }
            if (!string.IsNullOrEmpty(config.TargetFileNameFormat))
            {
                // If the template specifies a format, use it
                rc      += config.TargetFileNameFormat;
                tempExtn = config.TargetFileNameFormat.FileExtension();
            }
            else
            {
                // Otherwise, use the filename provided
                rc += qualSourceFile.FileName();
            }
            rc = rc.Replace("{PICKNO}", pickNo.ToString());
            rc = rc.Replace("{ORDERNO}", orderNo.ToString());
            rc = rc.Replace("{INVOICENO}", invoiceNo.ToString());
            rc = rc.Replace("{EXTN}", tempExtn);

            return(rc);
        }
Esempio n. 2
0
        private FileTransferConfigurationModel getFileTransferConfigurationModel(PurchaseOrderHeader poh,
                                                                                 FileRecipient fileRecipient)
        {
            FileTransferConfigurationModel template = null;

            switch (fileRecipient)
            {
            case FileRecipient.Warehouse:
                LocationModel warehouse = null;
                if (poh.LocationId != null)
                {
                    warehouse = LookupService.FindLocationModel(poh.LocationId.Value, false);
                }
                if (warehouse != null)
                {
                    template = DataTransferService.FindFileTransferConfigurationForWarehouseModel(warehouse, FileTransferDataType.WarehousePurchase);
                }
                break;

            case FileRecipient.FreightForwarder:
                FreightForwarderModel freightForwarder = null;
                if (poh.FreightForwarderId != null)
                {
                    freightForwarder = LookupService.FindFreightForwarderModel(poh.FreightForwarderId.Value, false);
                }
                if (freightForwarder != null)
                {
                    template = DataTransferService.FindFileTransferConfigurationForFreightForwarder(freightForwarder, FileTransferDataType.FreightForwarderPurchase);
                }
                break;
            }

            return(template);
        }
Esempio n. 3
0
        private FileTransferConfigurationModel createDataTransfer(CompanyModel company, UserModel user)
        {
            var dataType = LookupService.FindLOVItemByValueModel(LOVName.FileTransferDataType, ((int)FileTransferDataType.WarehousePick).ToString());

            var config = new FileTransferConfigurationModel {
                CompanyId        = company.Id,
                TransferType     = FileTransferType.Send,
                TransferTypeText = FileTransferType.Send.ToString(),
                DataTypeId       = dataType.Id,
                DataTypeText     = dataType.ItemText,
                CreatedDate      = DateTimeOffset.Now,
                CreatedById      = user.Id,
                CreatedByText    = user.Name,
                TransferName     = RandomString(),
                Protocol         = FTPProtocol.FTP,
                ProtocolText     = FTPProtocol.FTP.ToString(),
                ArchiveFolder    = Path.GetTempPath() + "Archive",
                ErrorFolder      = Path.GetTempPath() + "Error",
            };

            db.AddFolderToLog(config.ArchiveFolder, 10);
            db.AddFolderToLog(config.ErrorFolder, 10);

            return(config);
        }
        private string getTemplateFileName(FileTransferConfigurationModel template)
        {
            string fileName = GetConfigurationSetting("SiteFolder", "");

            fileName += "\\App_Data\\DataTransferTemplates\\" + template.ConfigurationTemplate;

            return(fileName);
        }
Esempio n. 5
0
        private Error processPick(PickHeaderModel pickH,
                                  FileTransferConfigurationModel template)
        {
            var error = new Error();

            // Load the template configuration file
            var configFile = getTemplateFileName(template);

            XElement doc  = XElement.Load(configFile);
            var      file = doc.Element("File");
            var      extn = file.Attribute("DataFileExtension").Value;

            var tempFile = Path.GetTempPath() + pickH.Id + ".CSV";   // extn;
            var zipFile  = "";

            // Check if the pick's files are to be compressed and sent in a ZIP.
            // A pick can be a single CSV file or a CSV with onr or more PDF's.
            // A single file can optionally be compressed whereas multiple files must be compressed
            // as a package of files.
            // The requirement is that a single file is dropped for FTP.
            bool bCompress = file.Attribute("CompressFile").Value.ParseBool();

            if (bCompress || pickH.PickFiles.Count() > 1)
            {
                // File(s) are to be compressed/combined
                zipFile = tempFile.ChangeExtension(".zip");

                error = Zip.ZipFiles(pickH.PickFiles, zipFile);

                if (error.IsError)
                {
                    FileManagerService.FileManagerService.DeleteFile(zipFile);
                }
                else
                {
                    tempFile = zipFile;
                }
            }

            if (!error.IsError)
            {
                if (file.Attribute("FTPFile").Value.ParseBool())
                {
                    // Copy the file to the FTP pickup folder
                    error = moveFileToFTPFolder(tempFile,
                                                template.SourceFolder,
                                                DataTransferService.GetTargetFileName(template,
                                                                                      tempFile,
                                                                                      pickH.Id));
                }
            }
            FileManagerService.FileManagerService.DeleteFile(tempFile);

            return(error);
        }
Esempio n. 6
0
        public Error SendPurchaseOrderToFreightForwarder(int purchaseOrderHeaderTempId)
        {
            var error = new Error();

            var poht = db.FindPurchaseOrderHeaderTemp(purchaseOrderHeaderTempId);

            if (poht == null)
            {
                error.SetError(EvolutionResources.errRecordError, "", "PurchaseOrderHeaderTemp", purchaseOrderHeaderTempId.ToString());
            }
            else
            {
                var purchaseOrderHeaderId = (poht.OriginalRowId == null ? 0 : poht.OriginalRowId.Value);
                var poh = db.FindPurchaseOrderHeader(purchaseOrderHeaderId);
                if (poh == null)
                {
                    error.SetError(EvolutionResources.errRecordError, "", "PurchaseOrderHeader", purchaseOrderHeaderId.ToString());
                }
                else
                {
                    if (poh.FreightForwarder == null)
                    {
                        error.SetError(EvolutionResources.errOrderHasNoFreightForwarderSet);
                    }
                    else
                    {
                        var fileRecipient = FileRecipient.FreightForwarder;
                        FileTransferConfigurationModel template = getFileTransferConfigurationModel(poh, fileRecipient);
                        if (template == null)
                        {
                            error.SetError(EvolutionResources.errFailedToFindFileTransferConfigForFreightForwarder,
                                           "", poh.FreightForwarder.Name);
                        }
                        else
                        {
                            error = processPurchaseOrder(poh, template, fileRecipient);

                            if (!error.IsError)
                            {
                                poh.DateSentToFF = DateTimeOffset.Now;
                                db.InsertOrUpdatePurchaseOrderHeader(poh);

                                poht.DateSentToFF = poh.DateSentToFF;
                                db.InsertOrUpdatePurchaseOrderHeaderTemp(poht);
                            }
                        }
                    }
                }
            }

            return(error);
        }
        public Error InsertOrUpdateDataTransferConfiguration(FileTransferConfigurationModel config, UserModel user, string lockGuid = "")
        {
            var error = validateModel(config);

            if (!error.IsError)
            {
                // Check that the lock is still current
                if (!db.IsLockStillValid(typeof(FileTransferConfiguration).ToString(), config.Id, lockGuid))
                {
                    error.SetError(EvolutionResources.errRecordChangedByAnotherUser, "TransferName");
                }
                else
                {
                    FileTransferConfiguration temp = null;
                    if (config.Id != 0)
                    {
                        temp = db.FindFileTransferConfiguration(config.Id);
                    }
                    else
                    {
                        temp = db.FindFileTransferConfiguration(config.TransferName);
                    }
                    if (temp == null)
                    {
                        temp = new FileTransferConfiguration();
                    }

                    mapToEntity(config, temp);

                    if (temp.CreatedById == 0)
                    {
                        temp.CreatedById = user.Id;
                        temp.CreatedDate = DateTimeOffset.Now;
                    }

                    temp.Location         = db.FindLocation(temp.LocationId ?? 0);
                    temp.FreightForwarder = db.FindFreightForwarder(temp.FreightForwarderId ?? 0);
                    if (temp.ConfigurationTemplate == "0")
                    {
                        temp.ConfigurationTemplate = "";
                    }

                    db.InsertOrUpdateFileTransferConfiguration(temp);
                    config.Id = temp.Id;
                }
            }
            return(error);
        }
        private Error validateModel(FileTransferConfigurationModel model)
        {
            var error = isValidRequiredString(getFieldValue(model.TransferName), 50, "TransferName", EvolutionResources.errTextDataRequiredInField);

            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.FTPHost), 100, "FTPHost", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.UserId), 50, "UserId", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.Password), 50, "Password", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.SourceFolder), 255, "SourceFolder", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.TargetFolder), 64, "TargetFileNameFormat", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.TargetFolder), 255, "TargetFolder", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.ArchiveFolder), 255, "ArchiveFolder", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.ConfigurationTemplate), 64, "ConfigurationTemplate", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.PostTransferCommand), 128, "PostTransferCommand", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.PostTransferParameters), 128, "PostTransferParameters", EvolutionResources.errTextDataRequiredInField);
            }

            return(error);
        }
        private bool moveFile(FileTransferConfigurationModel transferConfig,
                              string sourceQualName, string targetFolder,
                              ref string errorMsg)
        {
            bool bRc = false;

            // Create the folder
            FileManagerService.FileManagerService.CreateFolder(targetFolder);

            // Move the file
            var error = FileManagerService.FileManagerService.MoveFile(sourceQualName, targetFolder, true);

            if (error.IsError)
            {
                errorMsg = error.Message;
                bRc      = true;
            }

            return(bRc);
        }
Esempio n. 10
0
        private void receiveFiles(FileTransferConfigurationModel config)
        {
            int numFiles   = 0,
                numSuccess = 0,
                numErrors  = 0;

            WriteTaskLog($"Receiving file(s) from '{config.SourceFolder}' to '{config.TargetFolder}'");

            // Start the FTP service
            var ftpService = new FTPService.FTPService(config.FTPHost, config.UserId, config.Password, config.Protocol);

            // Get a list of files on the remote folder to receive
            string        errorMsg = "";
            List <string> fileList = new List <string>();

            if (ftpService.GetFTPFileList(config.SourceFolder, ref fileList, ref errorMsg))
            {
                WriteTaskLog(errorMsg, LogSeverity.Severe);
            }
            else
            {
                if (fileList != null)
                {
                    numFiles = fileList.Count();

                    string targetFolder = config.TargetFolder;
                    FileManagerService.FileManagerService.CreateFolder(targetFolder);

                    foreach (var fileName in fileList)
                    {
                        // Receiving a file
                        string targetFile = targetFolder + "\\" + fileName.FileName();

                        WriteTaskLog($"Receiving '{fileName}' to '{targetFile}'");

                        if (ftpService.DownloadFile(fileName,
                                                    targetFile,
                                                    null,
                                                    ref errorMsg))
                        {
                            // Failed to perform transfer
                            WriteTaskLog(errorMsg, LogSeverity.Severe);
                            numErrors++;

                            // Upon error, delete or archive remote file
                            bool bError;
                            if (!string.IsNullOrEmpty(config.ErrorFolder))
                            {
                                // File is configured to be archived
                                bError = ftpService.MoveFile(fileName, config.ErrorFolder, ref errorMsg);
                            }
                            else
                            {
                                // No archive configuration, so just delete the file
                                bError = ftpService.DeleteFile(fileName, ref errorMsg);
                            }
                            if (bError)
                            {
                                WriteTaskLog(errorMsg, LogSeverity.Severe);
                            }

                            // Delete the local file so we don't double-up
                            FileManagerService.FileManagerService.DeleteFile(targetFile);
                        }
                        else
                        {
                            // Transfer successful
                            WriteTaskLog(errorMsg, LogSeverity.Normal);
                            numSuccess++;

                            // Upon successful receipt, delete or archive remote file
                            bool bError;
                            if (!string.IsNullOrEmpty(config.ArchiveFolder))
                            {
                                // File is configured to be archived
                                bError = ftpService.MoveFile(fileName, config.ArchiveFolder, ref errorMsg);
                            }
                            else
                            {
                                // No archive configuration, so just delete the file
                                bError = ftpService.DeleteFile(fileName, ref errorMsg);
                            }
                            if (bError)
                            {
                                WriteTaskLog(errorMsg, LogSeverity.Severe);
                            }
                        }
                    }
                }
            }

            WriteTaskLog($"{numFiles} found, {numSuccess} received successfully, {numErrors} error(s)");
        }
Esempio n. 11
0
        private Error processPurchaseOrder(PurchaseOrderHeader poh,
                                           FileTransferConfigurationModel template,
                                           FileRecipient fileRecipient)
        {
            var error = new Error();

            // Load the template configuration file
            string configFile = getTemplateFileName(template),
                   tempFile   = "",
                   zipFile    = "";

            XElement doc = XElement.Load(configFile);

            var file = doc.Element("File");

            error = createPurchaseOrderDataFile(poh, file, ref tempFile);
            if (!error.IsError)
            {
                // Check if the file is compressed individually and sent
                bool bCompress = file.Attribute("CompressFile").Value.ParseBool();
                if (bCompress)
                {
                    // File is to be compressed
                    zipFile = tempFile.ChangeExtension(".zip");

                    error = Zip.ZipFile(tempFile, zipFile);

                    if (error.IsError)
                    {
                        FileManagerService.FileManagerService.DeleteFile(zipFile);
                    }
                    else
                    {
                        tempFile = zipFile;
                    }
                }

                bool bDelTempFile = true;
                if (!error.IsError)
                {
                    if (file.Attribute("FTPFile").Value.ParseBool())
                    {
                        // Copy the file to the FTP pickup folder
                        error = moveFileToFTPFolder(tempFile, template.SourceFolder, poh.OrderNumber + (bCompress ? ".zip" : ".txt"));
                    }
                    if (!error.IsError && file.Attribute("EMailFile").Value.ParseBool())
                    {
                        // Queue the file to be sent as an email
                        var company = CompanyService.FindCompanyModel(poh.CompanyId);

                        var purchaser = MembershipManagementService.FindUserModel(poh.SalespersonId.Value);

                        string email = "";
                        if (fileRecipient == FileRecipient.FreightForwarder)
                        {
                            var fforwarder = LookupService.FindFreightForwarderModel(poh.FreightForwarderId.Value);
                            if (string.IsNullOrEmpty(fforwarder.Email))
                            {
                                error.SetError(EvolutionResources.errCantSendEMailToBlankFreightForwarderAddress);
                            }
                            else
                            {
                                email = fforwarder.Email;
                            }
                        }
                        else
                        {
                            error.SetError(EvolutionResources.errEMailingWarehouseNotSupported);
                        }

                        if (!error.IsError)
                        {
                            var recipient = new UserModel {
                                EMail = email
                            };
                            var message = new EMailMessage(purchaser, recipient, MessageTemplateType.PurchaseOrderNotificationFF);

                            EMailService(company).AddOrganisationDetails(message.Dict);
                            EMailService().AddUserDetails(purchaser, message.Dict);
                            message.AddProperty("PURCHASEORDERNO", poh.OrderNumber.Value);

                            message.AddAttachment(tempFile);

                            error = EMailService().SendEMail(message);
                            if (!error.IsError)
                            {
                                bDelTempFile = false;
                            }
                        }
                    }
                }
                if (bDelTempFile)
                {
                    FileManagerService.FileManagerService.DeleteFile(tempFile);
                }
            }

            return(error);
        }
        void processFiles(FileTransferConfigurationModel config)
        {
            WriteTaskLog("Processing received files");

            foreach (var fileName in Directory.GetFiles(config.TargetFolder.TrimEnd('\\')))
            {
                bool   bError   = false;
                string errorMsg = "";

                // Open the file to get the purchase order number from the first data line
                CSVFileService.CSVReader reader = new CSVFileService.CSVReader();

                reader.OpenFile(fileName, true);
                Dictionary <string, string> firstLine = reader.ReadLine();
                reader.Close();

                int poNumber = -1;
                if (Int32.TryParse(firstLine["PO_NUMBER"], out poNumber))
                {
                    // Now we know what the PO Number is, attach the file to the purchase
                    // order notes/attachments so that it can be referenced in emails
                    CompanyModel company = new CompanyModel {
                        Id = config.CompanyId
                    };
                    var poh = PurchasingService.FindPurchaseOrderHeaderByPONumberModel(poNumber, company);
                    if (poh != null)
                    {
                        var note = new NoteModel();
                        bError = createNoteWithAttachment(poh, company, fileName, ref note, ref errorMsg);
                        if (!bError)
                        {
                            // A purchase order records who the 'sales person' was - actually the 'purchasor'.
                            // We need to email every user in the same team as the sales person to notify them
                            // of the slip file being received.

                            // To do this, we need to find what user groups the sales person is in and specifically
                            // look for one which has the name of the brand category of the order in it.
                            // We then email all users in that group. This ensures that when an order is received,
                            // the sales person's collegues are informed so that we don't create a situation where
                            // only one person knows about an order.

                            var userList = PurchasingService.FindOrderPurchasers(poh,
                                                                                 company,
                                                                                 poNumber,
                                                                                 ref errorMsg);
                            if (userList != null)
                            {
                                // Send emails to all the users in the list
                                var error = sendUnpackSlipMessage(poh, company, note, poNumber, userList);
                                if (error.IsError)
                                {
                                    errorMsg = error.Message;
                                    bError   = true;
                                }
                            }
                            else
                            {
                                bError = true;
                            }
                        }
                    }
                    else
                    {
                        errorMsg = $"Error: Failed to find the PurchaseOrderHeaderRecord corresponding to Order Number {poNumber} !";
                        bError   = true;
                    }
                }
                else
                {
                    errorMsg = $"Error: Failed to read PO_NUMBER column from '{fileName}' !";
                    bError   = true;
                }

                if (bError)
                {
                    // Failed to process the file so move it to the error folder
                    // Move the file to an error location.
                    // It may not exist if note/attachment creation has already moved it.
                    // It can be moved back in for later re-processing.
                    WriteTaskLog(errorMsg, LogSeverity.Severe);

                    string moveTarget = fileName.FolderName() + "\\Errors";
                    FileManagerService.FileManagerService.DeleteFile(moveTarget + "\\" + fileName.FileName());
                    var error = FileManagerService.FileManagerService.MoveFile(fileName, moveTarget, false);
                    if (error.IsError)
                    {
                        WriteTaskLog(error.Message, LogSeverity.Severe);
                    }
                }
            }
        }
 public bool MoveToError(FileTransferConfigurationModel transferConfig, string fileName,
                         ref string errorMsg)
 {
     // Used to move a file to its transfer's Error folder
     return(moveFile(transferConfig, fileName, transferConfig.ErrorFolder, ref errorMsg));
 }
 public string LockDataTransferConfiguration(FileTransferConfigurationModel model)
 {
     return(db.LockRecord(typeof(FileTransferConfiguration).ToString(), model.Id));
 }
Esempio n. 15
0
        private void sendFiles(FileTransferConfigurationModel config)
        {
            int numFiles   = 0,
                numSuccess = 0,
                numErrors  = 0;
            var error      = new Error();

            WriteTaskLog($"Sending file(s) from '{config.SourceFolder}' to '{config.TargetFolder}'");

            // Start the FTP service
            var ftpService = new FTPService.FTPService(config.FTPHost, config.UserId, config.Password, config.Protocol);

            // Get a list of files on the local folder to send
            FileManagerService.FileManagerService.CreateFolder(config.SourceFolder);

            string[] fileList = null;
            try {
                fileList = Directory.GetFiles(config.SourceFolder);
                numFiles = fileList.Length;
            } catch (Exception e1) {
                WriteTaskLog(e1.Message, LogSeverity.Severe);
            }

            if (fileList != null)
            {
                foreach (var fileName in fileList)
                {
                    WriteTaskLog($"Sending '{fileName}' to '{config.TargetFolder}'");

                    string errorMsg = "";
                    if (ftpService.UploadFile(fileName, config.TargetFolder, ref errorMsg))
                    {
                        // Transfer failed
                        WriteTaskLog(errorMsg, LogSeverity.Severe);
                        numErrors++;

                        // Upon error, delete or archive local file
                        if (!string.IsNullOrEmpty(config.ErrorFolder))
                        {
                            // File is configured to be archived
                            error = FileManagerService.FileManagerService.MoveFile(fileName, config.ErrorFolder, true);
                        }
                        else
                        {
                            // No archive configuration, so just delete the file
                            error = FileManagerService.FileManagerService.DeleteFile(fileName);
                        }
                        if (error.IsError)
                        {
                            WriteTaskLog(error.Message, LogSeverity.Severe);
                        }
                    }
                    else
                    {
                        // Transfer successful
                        WriteTaskLog(errorMsg, LogSeverity.Normal);
                        numSuccess++;

                        // Upon successful send, delete or archive local file
                        if (!string.IsNullOrEmpty(config.ArchiveFolder))
                        {
                            // File is configured to be archived
                            error = FileManagerService.FileManagerService.MoveFile(fileName, config.ArchiveFolder, true);
                        }
                        else
                        {
                            // No archive configuration, so just delete the file
                            error = FileManagerService.FileManagerService.DeleteFile(fileName);
                        }
                        if (error.IsError)
                        {
                            WriteTaskLog(error.Message, LogSeverity.Severe);
                        }
                    }
                }
            }

            WriteTaskLog($"{numFiles} found, {numSuccess} sent successfully, {numErrors} error(s)");
        }
Esempio n. 16
0
        private void MoveFileToErrorFolder(DataTransferService.DataTransferService dts, FileTransferConfigurationModel config, string fileName)
        {
            string errorMsg = "";

            if (dts.MoveToError(config, fileName, ref errorMsg))
            {
                TaskService.WriteTaskLog(this.Task, $"Failed to move to Error folder\r\n{errorMsg}", LogSeverity.Severe);
            }
            else
            {
                TaskService.WriteTaskLog(this.Task, $"File '{fileName}' has been moved to the Error folder", LogSeverity.Severe);
            }
        }
 private void mapToEntity(FileTransferConfigurationModel model, FileTransferConfiguration entity)
 {
     Mapper.Map <FileTransferConfigurationModel, FileTransferConfiguration>(model, entity);
 }