private void SendEmail(string From, string[] To, string Subject, string Body, string AttachmentName)
        {
            MailMessage msg = new MailMessage();

            msg.Subject    = Subject;
            msg.Body       = Body;
            msg.From       = new MailAddress(From);
            msg.IsBodyHtml = true;
            if (!String.IsNullOrEmpty(AttachmentName))
            {
                msg.Attachments.Add(new Attachment(AttachmentName));
            }

            foreach (String addr in To)
            {
                msg.To.Add(addr);
            }

            try
            {
                SmtpClient smtp = new SmtpClient(PluginConfig.GetValue("MailServer"));
                smtp.Send(msg);
            }
            catch (Exception ex)
            {
                LogMessage("Unable to send email " + Subject + ". Check to make sure the \"MailServer\" value exists in the config section and is correct.\r\n" + ex.Message + "\r\n" + ex.StackTrace);
            }
        }
        protected override void Process()
        {
            FileInfo headerFileInfo = new FileInfo(_OrderHeaderFile);

            if (!headerFileInfo.Exists || headerFileInfo.Length == 0)
            {
                //if there are no addresses specified no need to continue sending the message.
                if (String.IsNullOrEmpty(PluginConfig.GetValue("NoOrdersEmail").Trim()))
                {
                    return;
                }

                SendEmail("*****@*****.**", PluginConfig.GetValue("NoOrdersEmail").Split(';'), "No Internet Orders", "There were no orders to process on " + DateTime.Now.ToString("MM/dd/yyyy"), null);

                LogMessage("No Orders to process");
                LogMessage("-------------------------------Translate Complete-------------------------------");
                return;
            }
            try
            {
                base.Process();
                Environment.ExitCode = 0;
            }
            catch (Exception ex)
            {
                LogMessage("Unable to process internet orders \r\n Message: " + ex.Message + "\r\nStackTrace: " + ex.StackTrace);

                if (ex.Message != "No valid records to translate")
                {
                    Environment.ExitCode = 1;
                }
            }
        }
        /// <summary>
        /// Backs up weblinc files
        /// </summary>
        private void MoveFilesToBackup()
        {
            DirectoryInfo dirinfo = new DirectoryInfo(base.SourceFileLocation);

            FileInfo[] files          = dirinfo.GetFiles("order*.*");
            string     BackupLocation = PluginConfig.GetValue("WebLincBackupFolder");

            LogMessage(String.Format("Backing up files. ({0})", BackupLocation));
            foreach (FileInfo file in files)
            {
                if (!System.IO.File.Exists(BackupLocation + "\\" + file.Name))
                {
                    file.MoveTo(BackupLocation + "\\" + file.Name);
                }
                else
                {
                    file.Delete();
                }
            }


            //Backup the store reg info file
            //We don't move it because it is needed on every run of the translate.
            FileInfo StoreRegInfoFile = new FileInfo(PluginConfig.GetValue("StoreRegTranConfig"));

            StoreRegInfoFile.CopyTo(PluginConfig.GetValue("WebLincBackupFolder") + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + StoreRegInfoFile.Name);
        }
        void SendTotalsReport(FileInfo rpt)
        {
            //if there are no addresses specified no need to send email
            if (String.IsNullOrEmpty(PluginConfig.GetValue("TotalsReportEmail").Trim()))
            {
                return;
            }

            SendEmail("*****@*****.**", PluginConfig.GetValue("TotalsReportEmail").Split(';'), "INTERNET ORDER COUNTS", "Attached are the counts from the internet files processed on " + DateTime.Now.ToString("MM/dd/yyyy"), rpt.FullName);
        }
Example #5
0
 private void InitializeThreadPool()
 {
     work = new WorkQueue();
     ((WorkThreadPool)work.WorkerPool).MaxThreads = Int32.Parse(PluginConfig.GetValue("MaxThreads"));
     ((WorkThreadPool)work.WorkerPool).MinThreads = Int32.Parse(PluginConfig.GetValue("MinThreads"));
     work.ConcurrentLimit   = Int32.Parse(PluginConfig.GetValue("ConcurrentThreads"));
     work.AllWorkCompleted += new EventHandler(work_AllWorkCompleted);
     work.WorkerException  += new ResourceExceptionEventHandler(work_WorkerException);
     work.FailedWorkItem   += new WorkItemEventHandler(work_FailedWorkItem);
 }
Example #6
0
        /// <summary>
        /// Used to move the translated file to the backup location.
        /// </summary>
        /// <param name="srcFile"></param>
        private void BackupFile(FileInfo srcFile)
        {
            string BackupFolder = PluginConfig.GetValue("BackupFolder");

            string BackupFile = String.Format("{0}\\{1}", BackupFolder, srcFile.Name);

            if (File.Exists(BackupFile))
            {
                DirectoryInfo backupDir = new DirectoryInfo(BackupFolder);
                FileInfo[]    filecount = backupDir.GetFiles(srcFile.Name + "*");
                int           NextNum   = 1;
                if (filecount != null)
                {
                    NextNum = filecount.GetUpperBound(0) + 1;
                }

                BackupFile = String.Format("{0}\\{1}.{2}", BackupFolder, srcFile.Name, NextNum.ToString().PadLeft(4, '0'));
            }
            srcFile.MoveTo(BackupFile);
        }
Example #7
0
        /// <summary>
        /// Load a list of stores to exlude from translating
        /// </summary>
        /// <exception cref="System.IO.FileNotFoundException"></exception>
        private void LoadConsignmentStores()
        {
            if (ConsignmentStoreFile == null)
            {
                ConsignmentStoreFile = new List <string>();
            }

            string ConsignmentFile = PluginConfig.GetValue("ConsignmentStoreFile");

            if (!File.Exists(ConsignmentFile))
            {
                throw new FileNotFoundException(ResourceHelper.Instance.GetString(ResFile, "NoConsignmentStoreFile"));
            }

            string[] ConsignmentStores = File.ReadAllLines(ConsignmentFile);
            for (int i = 0; i < ConsignmentStores.Length; i++)
            {
                string store = ConsignmentStores[i];
                ConsignmentStoreFile.Add(store.Substring(0, 5));
            }
        }
        protected override void SaveTranslatedFile(XmlDocument TranslatedDocument)
        {
            LogMessage("Creating Totals Report");
            XmlDocument ConvertedSourceDoc = new XmlDocument();

            ConvertedSourceDoc.Load(SourceDocument);
            SendTotalsReport(TranslateSupport.GenerateSummaryReport(ConvertedSourceDoc, TranslatedDocument));

            XmlNodeList list = TranslatedDocument.SelectNodes("//" + NewDocumentRoot + "/*");

            //// create a writer and open the file
            string OutFile = PluginConfig.GetValue("TemporaryWorkFolder") + "\\translated.tmp";

            using (TextWriter tw = new StreamWriter(OutFile, false))
            {
                foreach (XmlNode node in list)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int x = 0; x < node.Attributes.Count; x++)
                    {
                        sb.Append(node.Attributes[x].Value.ToString() + "\t");
                    }
                    tw.WriteLine(sb.ToString());
                }
                tw.Close();
            }
            if (storeRegInfo != null)
            {
                storeRegInfo.SaveTransactionInfo();
            }

            //Do out translate clean up tasks here
            SplitTranslatedFile(OutFile, 1);
            CopyToSiris();
            MoveFilesToBackup();
            LogMessage("-------------------------------Translate Complete-------------------------------");
        }
        void IOrderTranslateItem_OnPreProcess()
        {
            LogMessage("-------------------------------Translate Started-------------------------------");

            TranslateSupport support = new TranslateSupport(PluginConfig);

            SkuFile = support.SkuList();

            string TempFolder = PluginConfig.GetValue("TemporaryWorkFolder");

            _OrderHeaderFile  = TempFolder + "\\OrderHeaderMerge";
            _OrderDetailFile  = TempFolder + "\\OrderDetailMerge";
            _OrderPaymentFile = TempFolder + "\\OrderPaymentMerge";

            LogMessage("Removing old files.");
            if (File.Exists(_OrderHeaderFile))
            {
                File.Delete(_OrderHeaderFile);
            }
            if (File.Exists(_OrderDetailFile))
            {
                File.Delete(_OrderDetailFile);
            }
            if (File.Exists(_OrderPaymentFile))
            {
                File.Delete(_OrderPaymentFile);
            }

            DirectoryInfo dirinfo = new DirectoryInfo(base.SourceFileLocation);

            //if email field is left blank this check is skipped
            if (!String.IsNullOrEmpty(PluginConfig.GetValue("DuplicateFilesEmail")))
            {
                //Remove any files from the download directory if they have already been processed.  Reprocessing those files will cause problems if sent to SIRIS.
                List <string> FilesRemoved = new List <string>();
                List <string> FilesKept    = new List <string>();
                TranslateSupport.RemoveProcessedFiles(dirinfo.GetFiles(), PluginConfig.GetValue("WebLincBackupFolder"), out FilesRemoved, out FilesKept);
                if (FilesRemoved.Count != 0)
                {
                    StringBuilder Body = new StringBuilder();
                    Body.Append("Processing of the following files was skipped because they have been previously processed. <BR>");
                    foreach (string file in FilesRemoved)
                    {
                        Body.Append(file + "<BR>");
                    }

                    Body.Append("____________________________________________________________<BR>");
                    if (FilesKept.Count > 0)
                    {
                        Body.Append("The following files were still processed<BR>");
                        foreach (string file in FilesKept)
                        {
                            Body.Append(file + "<BR>");
                        }
                    }
                    else
                    {
                        Body.Append("NO other files were processed.<BR>");
                    }

                    SendEmail("*****@*****.**", PluginConfig.GetValue("DuplicateFilesEmail").Split(';'), "Duplicate Internet Order Files Found", Body.ToString(), null);
                    LogMessage(Body.ToString().Replace("<BR>", "\r\n"));

                    dirinfo = new DirectoryInfo(base.SourceFileLocation);
                }
            }


            LogMessage("Merging all OrderHeader files");
            TranslateSupport.MergeFiles(dirinfo.GetFiles("*orderheader*.*"), _OrderHeaderFile);
            LogMessage("Merging all OrderDetail files");
            TranslateSupport.MergeFiles(dirinfo.GetFiles("*orderdetail*.*"), _OrderDetailFile);
            LogMessage("Merging all OrderPayment files");
            TranslateSupport.MergeFiles(dirinfo.GetFiles("*orderpayment*.*"), _OrderPaymentFile);
        }
        /// <summary>
        /// Copies our merged files from weblinc over to the siris ftp directories
        /// </summary>
        private void CopyToSiris()
        {
            string SirisDir = PluginConfig.GetValue("SIRISFTP");
            string FileTime = DateTime.Now.ToString("yyyyMMddHHmmss");

            //Write out as ASCII so that any non standard characters get converted to question marks to account for a bug with IBM not being able to handle them.
            CopyAsASCII(_OrderDetailFile, GetSaveFile(String.Format("{0}\\OrderDetail", SirisDir), "OrderDetail", FileTime));
            CopyAsASCII(_OrderDetailFile, GetSaveFile(String.Format("{0}\\OrderDetail\\archive", SirisDir), "OrderDetail", FileTime));
            CopyAsASCII(_OrderHeaderFile, GetSaveFile(String.Format("{0}\\OrderHeader", SirisDir), "OrderHeader", FileTime));
            CopyAsASCII(_OrderHeaderFile, GetSaveFile(String.Format("{0}\\OrderHeader\\archive", SirisDir), "OrderHeader", FileTime));
            LogMessage(String.Format("Copied OrderHeader and OrderDetail to SIRIS ({0})", SirisDir));


            //Write out as ASCII so that any non standard characters get converted to question marks to account for a bug with IBM not being able to handle them.
            StreamReader paymentReader    = new StreamReader(_OrderPaymentFile, System.Text.Encoding.ASCII);
            string       OrderPaymentDir  = String.Format("{0}\\OrderPayment", SirisDir);
            string       OrderPaymentFile = "OrderPayment";

            string PaymentSaveFile = GetSaveFile(OrderPaymentDir, OrderPaymentFile, FileTime);

            FileStream   paymentWStream = new FileStream(PaymentSaveFile, FileMode.Create);
            StreamWriter paymentWriter  = new StreamWriter(paymentWStream);

            while (paymentReader.Peek() != -1)
            {
                string CurrentLine = paymentReader.ReadLine();
                //Remove the hashed account from the file that goes to SIRIS because they have no use for it.

                CurrentLine = CurrentLine.Substring(0, 631);


                if (String.IsNullOrEmpty(CurrentLine.Trim()))
                {
                    continue;
                }

                string HashedAccount = CurrentLine.Substring(602, 20);
                CurrentLine = CurrentLine.Replace(HashedAccount, "".PadLeft(HashedAccount.Length, 'X'));

                string CCType = CurrentLine.Substring(469, 4);
                if (CCType == "GIFT")
                {
                    paymentWriter.WriteLine(CurrentLine);
                    continue;
                }

                string CCRecord = CurrentLine.Substring(473, 24);
                int    CCLen    = CCRecord.Trim().Length;

                if (CCLen > 0 && CCLen > 4)
                {
                    string MaskedCC = CCRecord.Substring(CCLen - 4).PadLeft(CCRecord.Length, 'X');
                    CurrentLine = CurrentLine.Replace(CCRecord, MaskedCC);
                }

                if (!String.IsNullOrEmpty(CurrentLine))
                {
                    paymentWriter.WriteLine(CurrentLine);
                }
            }
            paymentWriter.Flush();
            paymentReader.Close();
            paymentWStream.Close();
            //Copy new file to archive folder
            File.Copy(PaymentSaveFile, GetSaveFile(String.Format("{0}\\archive", OrderPaymentDir), OrderPaymentFile, FileTime));
            LogMessage(String.Format("Copied OrderPayment File to SIRIS and masked CC info. ({0})", SirisDir));
        }
        /// <summary>
        /// Splits out the translated file into seperate files based off the store number
        /// </summary>
        /// <param name="FileName">FileName to split</param>
        /// <param name="ColDelimeter">The column in the file to use as the distinc seperator of files</param>
        private void SplitTranslatedFile(string FileName, int ColDelimeter)
        {
            string CurrentLine;

            string[]      splitLine;
            int           StoreLine;
            StringBuilder sbFile = new StringBuilder();
            StreamWriter  writer;
            string        DirToSave  = PluginConfig.GetValue("TranslatedFileLocation");
            string        FileToSave = "";
            int           TotalFiles = 0;

            using (FileStream stream = File.OpenRead(FileName))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    int CurrentStore = -1;
                    while (reader.Peek() != -1)
                    {
                        CurrentLine = reader.ReadLine();
                        if (String.IsNullOrEmpty(CurrentLine))
                        {
                            continue;
                        }

                        splitLine = CurrentLine.Split('\t');
                        StoreLine = Convert.ToInt32(splitLine[ColDelimeter]);
                        if (CurrentStore == -1)
                        {
                            CurrentStore = StoreLine;
                        }

                        if (StoreLine == CurrentStore)
                        {
                            sbFile.Append(CurrentLine + "\r\n");
                        }
                        else
                        {
                            LogMessage(String.Format("Saving Tlog for store {0} to polling server ({1})", CurrentStore.ToString(), DirToSave));
                            FileToSave = "TLog" + CurrentStore.ToString().PadLeft(5, '0');
                            TotalFiles = Directory.GetFiles(DirToSave, FileToSave + "*").Length;
                            if (TotalFiles > 0)
                            {
                                FileToSave = FileToSave + "." + TotalFiles.ToString().PadLeft(4, '0');
                            }

                            writer = new StreamWriter(DirToSave + "\\" + FileToSave);
                            writer.WriteLine(sbFile.ToString().TrimEnd("\r\n".ToCharArray()));
                            writer.Close();
                            sbFile = new StringBuilder();
                            sbFile.Append(CurrentLine + "\r\n");
                            CurrentStore = StoreLine;
                        }
                    }
                    LogMessage(String.Format("Saving Tlog for store {0} to polling server ({1})", CurrentStore.ToString(), DirToSave));
                    FileToSave = "TLog" + CurrentStore.ToString().PadLeft(5, '0');
                    TotalFiles = Directory.GetFiles(DirToSave, FileToSave + "*").Length;
                    if (TotalFiles > 0)
                    {
                        FileToSave = FileToSave + "." + TotalFiles.ToString().PadLeft(4, '0');
                    }

                    //writer = new StreamWriter(PluginConfig.GetValue("TranslatedFileLocation") + "\\TLog" + CurrentStore.ToString().PadLeft(5, '0'));
                    writer = new StreamWriter(DirToSave + "\\" + FileToSave);
                    writer.WriteLine(sbFile.ToString().TrimEnd("\r\n".ToCharArray()));
                    writer.Close();
                }
            }
        }
        void TLogTranslateItem_OnBeforeNodeAppended(object sender, EventArgs e)
        {
            FooterFound = false;
            XmlNode NodeToAppend = (XmlNode)sender;

            if (storeRegInfo == null || storeRegInfo.StoreNo != Int32.Parse(NodeToAppend.Attributes["store_num"].Value))
            {
                if (storeRegInfo != null)
                {
                    storeRegInfo.SaveTransactionInfo();
                }

                storeRegInfo = new StoreRegisterInfo(Int32.Parse(NodeToAppend.Attributes["store_num"].Value), PluginConfig.GetValue("StoreRegTranConfig"));
            }

            switch (NodeToAppend.Name)
            {
            case "L10":
                InitializeCounter(1);
                //reset transaction total amounts
                TransactionTotal  = 0;
                DiscountAmount    = 0;
                Handling          = 0;
                isSaleTransaction = NodeToAppend.Attributes["type"].Value == "0";
                _TransactionNo    = storeRegInfo.NextTransactionID;
                _RegisterNo       = storeRegInfo.CurrentRegisterNumber;
                NodeToAppend.Attributes["country"].Value = storeRegInfo.CountryCode.ToString();
                break;

            case "L30":
                //update the transaction total amount excluding the shipping and handling charge on a refund
                if (NodeToAppend.Attributes["item"].Value != "000000000001")
                {
                    TransactionTotal += (Convert.ToDouble(NodeToAppend.Attributes["extended"].Value));
                }

                //Set the journal key based off the SIRIS file provided
                string Sku = NodeToAppend.Attributes["item"].Value;

                if (Sku.Length >= 8)
                {
                    Sku = Sku.Substring(Sku.Length - 8);
                }

                XmlNode FoundNode = SkuFile.SelectSingleNode(String.Format("//SkuList/Sku[@SkuNum='{0}']", Sku));
                if (FoundNode != null)
                {
                    int JournalKey = Convert.ToInt32(FoundNode.Attributes["Journal_Key"].Value);
                    NodeToAppend.Attributes["journal_key"].Value = JournalKey.ToString();
                }
                break;

            case "L31":
                //update the discount amount for the transaction
                DiscountAmount += Math.Abs(Convert.ToDouble(NodeToAppend.Attributes["discount"].Value)) * -1;
                break;

            case "L32":
                DiscountAmount += Math.Abs(Convert.ToDouble(NodeToAppend.Attributes["grupdisc"].Value)) * -1;
                break;

            //case "L44":
            //case "L47":
            //  NodeToAppend.Attributes["account"].Value = NodeToAppend.Attributes["account"].Value.Replace('X', '0');
            //  break;
            case "L70":
                if (NodeToAppend.Attributes["field_type"].Value == "1")
                {
                    var split = NodeToAppend.Attributes["field"].Value.Split(' ');
                    if (NodeToAppend.Attributes["field"].Value.IndexOf(" ") > 0)
                    {
                        NodeToAppend.Attributes["field"].Value = NodeToAppend.Attributes["field"].Value.Split(' ')[1];
                    }
                    else
                    {
                        NodeToAppend.Attributes["field"].Value = "";
                    }
                }
                if (NodeToAppend.Attributes["field_type"].Value == "2")
                {
                    if (NodeToAppend.Attributes["field"].Value.IndexOf(" ") > 0)
                    {
                        NodeToAppend.Attributes["field"].Value = NodeToAppend.Attributes["field"].Value.Split(' ')[0];
                    }
                    else
                    {
                        NodeToAppend.Attributes["field"].Value = "";
                    }
                }
                break;

            case "L99":
                //double total = (TransactionTotal - DiscountAmount) + Shipping + Handling + Convert.ToDouble(NodeToAppend.Attributes["taxes"].Value);
                double total = 0;
                if (TransactionTotal >= 0)
                {
                    total = (TransactionTotal - Math.Abs(DiscountAmount)) + Shipping + TaxableShipping + Handling + Convert.ToDouble(NodeToAppend.Attributes["taxes"].Value);
                }
                if (TransactionTotal < 0)
                {
                    total = (TransactionTotal + Math.Abs(DiscountAmount)) + Shipping + TaxableShipping + Handling + Convert.ToDouble(NodeToAppend.Attributes["taxes"].Value);
                }

                //add the gross amount of the transaction to the trailer record
                NodeToAppend.Attributes["gross"].Value = total.ToString();
                FooterFound = true;
                break;

            default:
                IncrementCounter();
                break;
            }
            NodeToAppend.Attributes["trans_num"].Value = _TransactionNo.ToString();
            NodeToAppend.Attributes["reg_num"].Value   = _RegisterNo.ToString();
        }
Example #13
0
        /// <summary>
        /// This method does the validation and is the entry point for the translating.
        /// </summary>
        /// <param name="file">The file to be translated and validated</param>
        private void TranslateFile(FileInfo file)
        {
            ConvertedTLogDoc = null;
            this._SourceFile = file.FullName;
            if (ExcludeHelper == null)
            {
                ExcludeHelper = new ExcludeFileHelper(PluginConfig.GetValue("TranslateExludeFile"), PluginConfig.GetValue("TranslateExludePath"), PluginConfig.GetValue("TranslateExludeType_BeforeTrans").Split(','));
            }

            if (_SourceDocument == null)
            {
                _SourceDocument = new XmlDocument();
                using (XmlReader SourceReader = SourceDocument)
                {
                    SourceReader.MoveToContent();
                    _SourceDocument.LoadXml(SourceReader.ReadOuterXml());
                }
            }

            bool     isvalid            = true;
            Validate TranslateValidator = null;
            bool     validate           = (PluginConfig.GetValue("ValidateTLog") == "") ? false : Convert.ToBoolean(PluginConfig.GetValue("ValidateTLog"));

            if (validate)
            {
                try
                {
                    TranslateValidator = new SpencerGifts.TlogCommon.Validate();

                    //Before we can process the file we need to check to make sure its a valid tlog\
                    LogMessage(String.Format(ResourceHelper.Instance.GetString(ResFile, "ValidateFile"), file.Name));
                    //isvalid = TranslateValidator.isValidTLog(_SourceDocument, _SourceFile);
                    isvalid = TranslateValidator.isValidTLog(_SourceDocument, file.FullName);
                }
                catch (Exception ex)
                {
                    LogMessage("Validator Exception " + ex.Message + " " + ex.StackTrace);
                    //Defaulting to true since the validator blew up and we don't necessarly want to prevent tlogs from getting held up
                    isvalid = true;
                }
            }
            if (!isvalid)
            {
                string BadTlogLocation = PluginConfig.GetValue("BadTlogLocation");

                if (TranslateValidator != null)
                {
                    Console.WriteLine(TranslateValidator.ErrorMessage);
                    LogMessage(String.Format(ResourceHelper.Instance.GetString(ResFile, "InvalidFile"), file.Name));
                    LogMessage("\r\n------------------------------------------\r\n" + TranslateValidator.ErrorMessage + "------------------------------------------");
                    //Logging.LogMessage(String.Format(ResourceHelper.Instance.GetString(ResFile, "MovingBadTLog"), BadTlogLocation));
                }

                File.Move(_SourceFile, BadTlogLocation + "\\" + file.Name);
            }
            else
            {
                //We need to check the exclude file first before we translate.  If the store is in the exclude file and
                //has a type that specifies not to translate the file then move it to the appropriate non translating directory.
                if (!ExcludeHelper.ShouldTranslate(file.Name.Substring(4, 5)))
                {
                    MoveFile(file, ExcludeHelper.NonTranslateSavePath);
                    return;
                }

                LogMessage(String.Format(ResourceHelper.Instance.GetString(ResFile, "FileIsValid"), file.Name));
                LogMessage(String.Format(ResourceHelper.Instance.GetString(ResFile, "TranslatingFile"), file.Name));
                try
                {
                    StoreCountryCode = _SourceDocument.SelectSingleNode("//L10/@country").Value;
                    if (isConsignmentStore(file.Name))
                    {
                        countryConfig = new CountryConfig(PluginConfig.GetValue("ConsignmentCountryCode"));
                    }
                    else
                    {
                        countryConfig = new CountryConfig(StoreCountryCode);
                    }

                    base.Process();
                    //now we need to check the exclude file again to verify we can move the translated file to the backup location
                    if (ExcludeHelper.OkToBackup(file.Name.Substring(4, 5)))
                    {
                        BackupFile(file);
                    }
                    else
                    {
                        MoveFile(file, ExcludeHelper.NonTranslateSavePath);
                    }
                }
                catch (RuleConditionException ex)
                {
                    PropertyInfo[] info = ex.GetType().GetProperties();
                    LogException(info, ex);
                    throw ex;
                }
                catch (RuleActionException ex)
                {
                    PropertyInfo[] info = ex.GetType().GetProperties();
                    LogException(info, ex);
                    throw ex;
                }
                catch (RuleMappingException ex)
                {
                    PropertyInfo[] info = ex.GetType().GetProperties();
                    LogException(info, ex);
                    throw ex;
                }
                catch (Exception ex)
                {
                    LogMessage(String.Format(ResourceHelper.Instance.GetString(ResFile, "UnHandledException"), file.Name, ex.ToString()));
                    throw ex;
                }
                finally
                {
                    _SourceDocument   = null;
                    _SourceDocumentMS = null;
                }
            }
        }
Example #14
0
        protected override void Process()
        {
            LoadConsignmentStores();

            if (String.IsNullOrEmpty(RunTime))
            {
                RunTime = DateTime.Now.ToString("MMddhhmm");
            }

            //If a single file is already supplied we will only process that file instead
            //of looping through the source directory looking for files to Translate.
            if (!String.IsNullOrEmpty(_SourceFile))
            {
                if (!File.Exists(_SourceFile))
                {
                    return;
                }

                FileInfo file = new FileInfo(_SourceFile);
                try
                {
                    TranslateFile(file);
                }
                catch (Exception ex)
                {
                    LogException(ex.GetType().GetProperties(), ex);
                    throw ex;
                }

                LogMessage(String.Format(ResourceHelper.Instance.GetString(ResFile, "TranslateComplete"), file.Name, DateTime.Now.ToString("hh:mm:ss")));
                return;
            }

            FileInfo[] TlogFiles = GetFiles(base.SourceFileLocation);

            //If there are no files to translate quit.
            if (TlogFiles == null)
            {
                LogMessage(ResourceHelper.Instance.GetString(ResFile, "NoFiles"));
                LogMessage(String.Format(ResourceHelper.Instance.GetString(ResFile, "ValidPathCheck"), SourceFileLocation));
                TranslateComplete();
                System.Threading.Thread.Sleep(1000);
                return;
            }
            else if (TlogFiles.GetLength(0) == 0)
            {
                LogMessage(ResourceHelper.Instance.GetString(ResFile, "NoFiles"));
                TranslateComplete();
                System.Threading.Thread.Sleep(1000);
                return;
            }

            LogMessage(ResourceHelper.Instance.GetString(ResFile, "TranslateStarted"));

            try
            {
                //Initialize the threadpool for the worker items soon to be sent to it
                InitializeThreadPool();
            }
            catch (Exception ex)
            {
                LogMessage("Unable to initialize the thread pool.  Ending translate");
                LogException(ex.GetType().GetProperties(), ex);
                return;
            }

            //System.Threading.Tasks.TaskFactory factory = new System.Threading.Tasks.TaskFactory();

            foreach (FileInfo file in TlogFiles)
            {
                try
                {
                    Translate.TranslateItem item = new TLogTranslateItem();
                    item.SourceFile = file.FullName;
                    TranslateWorker.ExceptionLogHandler Logger = new TranslateWorker.ExceptionLogHandler(LogException);
                    TranslateWorker worker = new TranslateWorker(Logger);
                    worker.TransItem        = item;
                    worker.PluginConfigName = base.PluginConfig.PluginName;


                    //var task = factory.StartNew(() => item.ExecuteTranslate(base.PluginConfig.PluginName));

                    work.Add(worker);

                    //item.ExecuteTranslate(base.PluginConfig.PluginName);

                    //System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(item.ExecuteTranslate), base.PluginConfig.PluginName);
                    //return;
                    //TranslateFile(file);
                }
                catch (Exception ex)
                {
                    LogMessage(String.Format(ResourceHelper.Instance.GetString(ResFile, "UnHandledException"), file.Name, ex.Message + "\r\n" + ex.StackTrace));
                    if (!String.IsNullOrEmpty(PluginConfig.GetValue("FailedTranslatePath")))
                    {
                        if (Directory.Exists(PluginConfig.GetValue("FailedTranslatePath")))
                        {
                            LogMessage("Moving File to " + PluginConfig.GetValue("FailedTranslatePath"));
                            file.MoveTo(PluginConfig.GetValue("FailedTranslatePath") + "\\" + file.Name);
                        }
                        else
                        {
                            LogMessage("Unable to Move File.  Missing or Invalid configuration value: FailedTranslatePath");
                        }
                    }
                    _SourceDocument   = null;
                    _SourceDocumentMS = null;
                }
            }

            //int ProgramRunTime = 0;
            //while (!workcomplete)
            //{
            //  if (ProgramRunTime >= 600 && work.Count == 0)
            //  {
            //    //Used to prevent the program from infinite loop;
            //    LogMessage(ResourceHelper.Instance.GetString(ResFile, "AppTimeOut"));
            //    return;
            //  }
            //  #if (DEBUG)
            //    Console.WriteLine("*********Total Items In ThreadPool " + work.Count.ToString() + "*********");
            //  #endif
            //  System.Threading.Thread.Sleep(5000);
            //  ProgramRunTime++;
            //}

            //Keep the main thread waiting untill all items have been processed in the threadpool.  Once the threadpool is finished the application will exit.
            Thread.Sleep(Timeout.Infinite);
        }
Example #15
0
        protected override void AppendNode(XmlElement Parent, XmlNode NodeToAppend)
        {
            //All cases here are specific rules that need to be applied for the translate and could not be obtained in the translate rules.
            //If we have a header record append it to the output document
            if (NodeToAppend.Name == "H")
            {
                //keep track of the header that was found for later processing if a header is found without a line item.
                HeadItemFound = true;
                XmlNode OriginalDateNote = null;
                //We need to check the transaction date and time to make sure we do not have multiple transactions with the same time.
                //This is an auditworks rule
                //DateTime CurrentTransTime = Convert.ToDateTime(NodeToAppend.Attributes["Entry_date_time"].Value);
                //DateTime TempDate = new DateTime(PreviousHeaderTime.Year, PreviousHeaderTime.Month, PreviousHeaderTime.Day, PreviousHeaderTime.Hour, PreviousHeaderTime.Minute, 0);
                //if the current transaction time is the same as the previous transaction time we increment the time by 1 and store it until the time no longer matches
                //if (CurrentTransTime == TempDate)
                //{
                //  NodeToAppend.Attributes["Entry_date_time"].Value = PreviousHeaderTime.AddSeconds(1).ToString("MM/dd/yyyy HH:mm:ss");
                //  PreviousHeaderTime = PreviousHeaderTime.AddSeconds(1);
                //}
                //else
                //Time no longer matches so reset it to the current transaction time
                //  PreviousHeaderTime = CurrentTransTime;

                //Custom rule that determines when the date cutoff is.  If a transaction is found in the tlog with a date > than this (Currently 3AM)
                //the date will be moved back to the previous day.  This will only happen if it is turned on in the configuration.
                if (PluginConfig.GetValue("ReDate").ToLower() == "true")
                {
                    DateTime TranslateCutOffTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 3, 0, 0);
                    DateTime HeaderTransDate     = Convert.ToDateTime(NodeToAppend.Attributes["Entry_date_time"].Value);
                    if (HeaderTransDate >= TranslateCutOffTime)
                    {
                        NodeToAppend.Attributes["Entry_date_time"].Value = HeaderTransDate.AddDays(-1).ToString("MM/dd/yyyy") + " 23:59:59";
                        OriginalDateNote = DestinationDocumentTemplate.SelectSingleNode("//N");
                        OriginalDateNote.Attributes["Line_note_type"].Value = "57";
                        OriginalDateNote.Attributes["Line_Note"].Value      = HeaderTransDate.ToString("MM/dd/yyyy HH:mm:ss");
                    }
                }

                //LineNode will be null if we have a header with a line item
                if (LineNode != null)
                {
                    Parent.InnerXml = Parent.InnerXml + LineNode.OuterXml;
                    LineNode        = null;
                }

                Parent.AppendChild(NodeToAppend);

                if (OriginalDateNote != null)
                {
                    Parent.InnerXml = Parent.InnerXml + OriginalDateNote.OuterXml;
                }
            }
            //if we have a L record append it
            else if (NodeToAppend.Name == "L")
            {
                //keep track of line items found for later processing if necessary.
                LineFound = true;

                Parent.AppendChild(NodeToAppend);

                //now if we have any items waiting to be added we can add them now
                if (List.Count <= 0)
                {
                    return;
                }

                for (int i = 0; i < List.Count; i++)
                {
                    Parent.InnerXml = Parent.InnerXml + List[i].OuterXml;
                }

                List.Clear();
            }
            //A line item has already been found so keep adding
            else if (LineFound)
            {
                Parent.AppendChild(NodeToAppend);
            }
            //base.AppendNode(Parent, NodeToAppend);

            LastParentNodeAppendedTo = Parent;
        }