コード例 #1
0
ファイル: DirectoryWatcher.cs プロジェクト: OSADP/archive
        private static void onEmailCreated(object source, FileSystemEventArgs e)
        {
            string msg = string.Format("File {0} | {1} | {2}",
                                       e.FullPath, e.ChangeType, e.Name);

            if (e.ChangeType == WatcherChangeTypes.Created)
            {
                Properties.attachmentPath = e.FullPath;
                VescoLog.LogEvent(msg);

                //smtpAttachGmail();
                String subject;
                String body;
                if (ass.isExecuted)
                {
                    subject = "Re-optimized plan";
                    body    = "Your re-optimized daily plan for today is attached. Please forward any questions/comments to Diane Newton (Leidos) at [email protected].";
                }
                else
                {
                    subject = "Initial optimization";
                    body    = "The optimized plan for your next business day is attached. Please forward any questions/comments to Diane Newton (Leidos) at [email protected].";
                }
                EmailHelper.sendGmail(subject, body, true);

                VescoLog.LogEvent("End of onEmailCreated");
            }
        }
コード例 #2
0
        static void Main(string[] args)
        {
            VescoLog   vl    = new VescoLog();
            Properties props = new Properties();

            VescoLog.LogEvent("Starting up Vesco Console at " + DateTime.Now);

            DirectoryWatcher watcher = new DirectoryWatcher();

            GmailChecker gmailChecker = new GmailChecker();

            gmailChecker.GetGmail(null, null);

            //Timer myTimer = new Timer();
            //myTimer.Elapsed += new ElapsedEventHandler(gmailChecker.GetGmail);
            //myTimer.Interval = Properties.emailCheckInterval * 60000;
            //myTimer.Start();

            //Timer t = new Timer();
            //t.Interval = 60000; //In milliseconds here
            //t.AutoReset = true; //Stops it from repeating
            //t.Elapsed += new ElapsedEventHandler(TimerElapsed);
            //t.Start();

            if (shouldWait)
            {
                Thread.Sleep(15 * 60000); //15 minutes
            }

//            Console.ReadLine();
        }
コード例 #3
0
        public void CheckForNewFriday(ImapClient _client)
        {
            // Get the Optimize
            IEnumerable <uint> optUid = _client.Search(
                SearchCondition.Subject(Properties.watchFriOptSubject)
                .And(SearchCondition.Unseen())
                );

            if (optUid.Count() != 0)
            {
                VescoLog.LogEvent("New Friday Email");

                // The email is here
                Program.shouldWait = true;
                MailMessage optMailMessage = _client.GetMessage(optUid.First());
                Attachment  optAttach      = optMailMessage.Attachments.First();
                SavePlan(optAttach, Properties.dropOptDir);

                Thread.Sleep(5000); //5 seconds
                VescoLog.LogEvent("Friday attachment placed in drop directory.");
            }
            else
            {
                VescoLog.LogEvent("No New Friday email");
            }
        }
コード例 #4
0
ファイル: DirectoryWatcher.cs プロジェクト: OSADP/archive
        //public static void smtpAttachGmail()
        //{
        //    var fromAddress = new MailAddress(Properties.fromEmail, Properties.fromName);
        //    string subject;
        //    string body;

        //    if (ass.isExecuted)
        //    {
        //        subject = "Re-optimized plan";
        //        body = "Your re-optimized daily plan for today is attached. Please forward any questions/comments to Diane Newton (Leidos) at [email protected].";
        //    }
        //    else
        //    {
        //        subject = "Initial optimization";
        //        body = "The optimized plan for your next business day is attached. Please forward any questions/comments to Diane Newton (Leidos) at [email protected].";
        //    }

        //    var smtp = new SmtpClient
        //    {
        //        Host = Properties.gmailHost,
        //        Port = Properties.gmailPort,
        //        EnableSsl = true,
        //        DeliveryMethod = SmtpDeliveryMethod.Network,
        //        UseDefaultCredentials = false,
        //        Credentials = new NetworkCredential(Properties.gmailUser, Properties.gmailPassword),
        //        Timeout = 20000
        //    };

        //    using (var message = new MailMessage()
        //    {
        //        Subject = subject,
        //        Body = body,
        //    })
        //    {
        //        // Go through distribution list
        //        String[] distList = Properties.distList.Split(',');
        //        foreach (string s in distList)
        //        {
        //            message.To.Add(s);
        //        }

        //        System.Threading.Thread.Sleep(10000);

        //        message.From = fromAddress;
        //        Attachment attachment = new Attachment(Properties.attachmentPath);
        //        message.Attachments.Add(attachment);

        //        try
        //        {
        //            smtp.Send(message);
        //            VescoLog.LogEvent("SMTP Through Attach Gmail Success");

        //        }
        //        catch (Exception ex)
        //        {
        //            Exception ex2 = ex;
        //            string errorMessage = string.Empty;
        //            while (ex2 != null)
        //            {
        //                errorMessage += ex2.ToString();
        //                ex2 = ex2.InnerException;
        //            }
        //            VescoLog.LogEvent("Dude, you're probably plugged in to the VPN!  Shut that shit down!");
        //            VescoLog.LogEvent(ex.StackTrace);
        //            VescoLog.LogEvent(errorMessage);
        //        }
        //    }
        //}

        private static void moveProcessedFile(string origFileName, string origFilePath)
        {
            // Moving the wrong file
            String processedName = origFileName.Insert(origFileName.IndexOf("."), DateTime.Now.ToString("-yyyyMMdd_HHmmssfff"));

            File.Copy(origFilePath, Properties.procDir + processedName); // Try to move
            File.Delete(origFilePath);
            VescoLog.LogEvent("Copied to " + Properties.procDir);        // Success
        }
コード例 #5
0
ファイル: EmailHelper.cs プロジェクト: OSADP/archive
        public static void sendGmail(String _subject, String _body, Boolean hasAttachment)
        {
            var fromAddress = new MailAddress(Properties.fromEmail, Properties.fromName);

            var smtp = new SmtpClient
            {
                Host                  = Properties.gmailHost,
                Port                  = Properties.gmailPort,
                EnableSsl             = true,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(Properties.gmailUser, Properties.gmailPassword),
                Timeout               = 20000
            };

            using (var message = new MailMessage()
            {
                Subject = _subject,
                Body = _body,
            })
            {
                // Go through distribution list
                String[] distList = Properties.distList.Split(',');
                foreach (string s in distList)
                {
                    message.To.Add(s);
                }

                System.Threading.Thread.Sleep(10000);

                message.From = fromAddress;
                if (hasAttachment)
                {
                    Attachment attachment = new Attachment(Properties.attachmentPath);
                    message.Attachments.Add(attachment);
                }

                try
                {
                    smtp.Send(message);
                    VescoLog.LogEvent("SMTP Through Attach Gmail Success");
                }
                catch (Exception ex)
                {
                    Exception ex2          = ex;
                    string    errorMessage = string.Empty;
                    while (ex2 != null)
                    {
                        errorMessage += ex2.ToString();
                        ex2           = ex2.InnerException;
                    }
                    VescoLog.LogEvent("Dude, you're probably plugged in to the VPN!  Shut that shit down!");
                    VescoLog.LogEvent(ex.StackTrace);
                    VescoLog.LogEvent(errorMessage);
                }
            }
        }
コード例 #6
0
ファイル: GmailWatcher.cs プロジェクト: OSADP/archive
        // this gets called sometimes because the executed and reopt emails
        // come in at the same time and the executed portion never gets called
        private void grabLatestExecuted(IdleMessageEventArgs e)
        {
            uint        u          = e.MessageUID - 1;
            MailMessage mm         = e.Client.GetMessage(u);
            Attachment  attachment = mm.Attachments.First();

            SavePlan(attachment, Properties.dropExDir);
            VescoLog.LogEvent(String.Format("Ex Attachment Name, {0}", attachment.Name));
            e.Client.AddMessageFlags(e.MessageUID, null, MessageFlag.Seen);
        }
コード例 #7
0
        public void CheckForNewReOptEmails(ImapClient _client)
        {
            // Get the ReOptimize first since it always comes in second
            IEnumerable <uint> reOptUid = _client.Search(
                SearchCondition.Subject(Properties.watchReOptSubject)
                .And(SearchCondition.Unseen())
                );

            if (reOptUid.Count() != 0)
            {
                VescoLog.LogEvent("ReOpt email is here.  Grab the ReOpt Email");

                Program.shouldWait = true;
                // Now grab the executed
                IEnumerable <uint> executedUid = _client.Search(
                    SearchCondition.Subject(Properties.watchExSubject)
                    .And(SearchCondition.Unseen())
                    );

                if (executedUid.Count() != 0)
                {
                    VescoLog.LogEvent("Executed email is here.  Grab the Executed Email");

                    // both emails are here, grab the attachments and
                    // drop them in the directory to be processed
                    MailMessage exMailMessage = _client.GetMessage(executedUid.First());
                    Attachment  exAttach      = exMailMessage.Attachments.First();
                    SavePlan(exAttach, Properties.dropExDir);

                    MailMessage reOptMailMessage = _client.GetMessage(reOptUid.First());
                    Attachment  reOptAttachment  = reOptMailMessage.Attachments.First();
                    SavePlan(reOptAttachment, Properties.dropReOptDir);

                    Thread.Sleep(5000); //5 seconds
                    VescoLog.LogEvent("Executed and ReOpt attachments placed in drop directory");
                }
                else
                {
                    // This should never ever happen, but if it does:
                    // revert the ReOpt to unseen, exit out, and try again in 10 minutes
                    VescoLog.LogEvent("ReOpt Found but no Executed.  What up with that?");
                    _client.RemoveMessageFlags(reOptUid.First(), null, MessageFlag.Seen);
                }
            }
            else
            {
                VescoLog.LogEvent("No New ReOpt emails");
            }
        }
コード例 #8
0
        public void GetGmail(object source, ElapsedEventArgs e)
        {
            VescoLog.LogEvent("Getting Gmail " + DateTime.Now);

            VescoLog.LogEvent("Creating Imap Client " + DateTime.Now);
            ImapClient client = new ImapClient(
                Properties.gmailImap, 993, Properties.gmailUser, Properties.gmailPassword, AuthMethod.Login, true);

            VescoLog.LogEvent("Finished Creating Imap Client " + DateTime.Now);

            CheckForNewDaily(client);
            CheckForNewFriday(client);
            CheckForNewReOptEmails(client);
            client.Dispose();

            VescoLog.LogEvent("Finished getting the Gmail " + DateTime.Now + Environment.NewLine);
        }
コード例 #9
0
ファイル: DirectoryWatcher.cs プロジェクト: OSADP/archive
        private static void CreateDropReOptWatcher()
        {
            FileSystemWatcher dropWatcher = new FileSystemWatcher(Properties.dropReOptDir);

            //Watch for changes in LastAccess and LastWrite times, and
            //the renaming of files or directories.
            dropWatcher.NotifyFilter = NotifyFilters.LastAccess
                                       | NotifyFilters.LastWrite
                                       | NotifyFilters.FileName
                                       | NotifyFilters.DirectoryName;

            // Add event handler.
            dropWatcher.Created += new FileSystemEventHandler(onDropReOptCreated);

            // Begin watching.
            dropWatcher.EnableRaisingEvents = true;
            VescoLog.LogEvent(String.Format("Drop ReOpt Dir Watcher created on {0}", Properties.dropReOptDir));
        }
コード例 #10
0
ファイル: DirectoryWatcher.cs プロジェクト: OSADP/archive
        private static void onDropReOptCreated(object source, FileSystemEventArgs e)
        {
            string msg = string.Format("{3}ReOptimization File {0} | {1} | {2}",
                                       e.FullPath, e.ChangeType, e.Name, Environment.NewLine);


            if (e.ChangeType == WatcherChangeTypes.Created)
            {
                VescoLog.LogEvent(msg);

                System.Threading.Thread.Sleep(5000);

                ass.processAssDrop(e.FullPath);

                moveProcessedFile(e.Name, e.FullPath);

                VescoLog.LogEvent("End of OnDropReOptCreated");
            }
        }
コード例 #11
0
ファイル: DirectoryWatcher.cs プロジェクト: OSADP/archive
        private static void CreateEmailWatcher()
        {
            FileSystemWatcher emailWatcher = new FileSystemWatcher(AppDomain.CurrentDomain.BaseDirectory + Properties.attachmentPath);

            //Watch for changes in LastAccess and LastWrite times, and
            //the renaming of files or directories.
            emailWatcher.NotifyFilter = NotifyFilters.LastAccess
                                        | NotifyFilters.LastWrite
                                        | NotifyFilters.FileName
                                        | NotifyFilters.DirectoryName;

            // Add event handlers
            emailWatcher.Created += new FileSystemEventHandler(onEmailCreated);

            // Begin watching.
            emailWatcher.EnableRaisingEvents = true;

            VescoLog.LogEvent(String.Format("Email Dir Watcher created on {0} {1}", emailWatcher.Path, Environment.NewLine));
        }
コード例 #12
0
ファイル: GmailWatcher.cs プロジェクト: OSADP/archive
        public void Watch()
        {
            VescoLog.LogEvent(String.Format("Creating Email Watch for {0}", Properties.gmailUser));
            client = new ImapClient(
                Properties.gmailImap, 993, Properties.gmailUser, Properties.gmailPassword, AuthMethod.Login, true);

            // Make sure IDLE is actually supported by the server.
            if (client.Supports("IDLE"))
            {
                VescoLog.LogEvent("Server supports IMAP IDLE");
            }
            else
            {
                VescoLog.LogEvent("Server does NOT support IMAP IDLE");
            }

            // We want to be informed when new messages arrive.
            client.IdleError  += client_IdleError;
            client.NewMessage += client_NewMessage;
        }
コード例 #13
0
ファイル: GmailWatcher.cs プロジェクト: OSADP/archive
        //private void client_IdleError(object sender, IdleErrorEventArgs e)
        //{
        //    VescoLog.LogEvent("An error occurred while idling: ");
        //    Exception idleException = e.Exception;
        //    string idleErrorMessage = string.Empty;
        //    while (idleException != null)
        //    {
        //        idleErrorMessage += idleException.ToString();
        //        idleException = idleException.InnerException;
        //    }
        //    VescoLog.LogEvent(idleErrorMessage);
        //    try
        //    {
        //        VescoLog.LogEvent("Trying to reset");
        //        reconnectEvent.Set();
        //        VescoLog.LogEvent("Reconnect successful");

        //        VescoLog.LogEvent("Trying to create events");
        //        e.Client.IdleError += client_IdleError;
        //        e.Client.NewMessage += client_NewMessage;
        //        VescoLog.LogEvent("Event creation successful");
        //    }
        //    catch (Exception ex)
        //    {
        //        Exception reconnectException = ex;
        //        string reconnectErrorMessage = string.Empty;
        //        while (reconnectException != null)
        //        {
        //            reconnectErrorMessage += reconnectException.ToString();
        //            reconnectException = reconnectException.InnerException;
        //        }
        //        VescoLog.LogEvent("An error occurred while resetting or creating events:");
        //        VescoLog.LogEvent(reconnectErrorMessage);
        //    }
        //}

        private void client_IdleError(object sender, IdleErrorEventArgs e)
        {
            VescoLog.LogEvent("An error occurred while idling at time: " + DateTime.Now);
            Exception idleException    = e.Exception;
            string    idleErrorMessage = string.Empty;

            while (idleException != null)
            {
                idleErrorMessage += idleException.ToString();
                idleException     = idleException.InnerException;
            }
            VescoLog.LogEvent(idleErrorMessage);

            try
            {
                VescoLog.LogEvent("Trying to dispose");
                client.Dispose();
                client = null;
                VescoLog.LogEvent("Dispose successful");

                VescoLog.LogEvent("Trying to call Watch()");
                Watch();
                VescoLog.LogEvent("Call to Watch() successful");
            }
            catch (Exception ex)
            {
                Exception reconnectException    = ex;
                string    reconnectErrorMessage = string.Empty;
                while (reconnectException != null)
                {
                    reconnectErrorMessage += reconnectException.ToString();
                    reconnectException     = reconnectException.InnerException;
                }
                VescoLog.LogEvent("An error occurred while disposing or watching:");
                VescoLog.LogEvent(reconnectErrorMessage);
            }
        }
コード例 #14
0
ファイル: Associated.cs プロジェクト: OSADP/archive
        private void generateVescoSpreadSheet(string _fullPath)
        {
            Excel.Application excelObj2           = new Excel.Application();
            Excel.Workbook    vescoExcelWorkbook  = null;
            Excel.Worksheet   vescoExcelWorksheet = null;

            Excel.Worksheet locationWorkSheet = null;
            Excel.Range     locationRange     = null;

            Excel.Worksheet driverExcelWorksheet = null;
            Excel.Range     driverRange          = null;
            ExecutedOrder   tempAssExOrder;

            try
            {
                vescoExcelWorkbook = excelObj2.Workbooks.Open(Properties.templateDir + "Associated Template.xlsx");

                if (assExOrders.Count > 0)
                {
                    driverExcelWorksheet = (Excel.Worksheet)vescoExcelWorkbook.Sheets.get_Item("Driver");
                    driverRange          = driverExcelWorksheet.UsedRange;
                    int      driverRowCount = driverRange.Rows.Count;
                    int      driverCount    = 0;
                    String   tempDriverId;
                    DateTime tempDateTime;
                    DateTime earliestStartTime;
                    DateTime dayEndsAt;
                    double   hoursElapsed;
                    double   newDrivingHours;
                    double   newDutyHours;

                    // loop through all the drivers
                    for (int i = 2; i <= driverRowCount; i++)  // Start at the second row and skip the header
                    {
                        tempDriverId = driverRange[i, 1].Value2.ToString();
                        // find if this driver has been added to the list
                        tempAssExOrder = assExOrders.Find(
                            delegate(ExecutedOrder aeo)
                        {
                            return(aeo.Driver == tempDriverId);
                        }
                            );
                        if (tempAssExOrder != null)
                        {
                            tempDateTime      = DateTime.FromOADate(driverRange[i, 4].Value2);
                            earliestStartTime = tempAssExOrder.dtDevliveryDateTime.Date.AddHours(tempDateTime.Hour);
                            dayEndsAt         = earliestStartTime.AddHours(driverRange[i, 3].Value2);
                            hoursElapsed      = tempAssExOrder.dtDevliveryDateTime.Subtract(earliestStartTime).TotalHours;
                            newDrivingHours   = Convert.ToDouble(driverRange[i, 2].Value2) - hoursElapsed;
                            newDrivingHours   = newDrivingHours > 0 ? newDrivingHours : 0.0;
                            newDutyHours      = Convert.ToDouble(driverRange[i, 3].Value2) - hoursElapsed;
                            newDutyHours      = newDutyHours > 0 ? newDutyHours : 0.0;

                            Console.WriteLine("Earliest Start Time -> " + earliestStartTime);
                            Console.WriteLine("Available Driving Hours -> " + driverRange[i, 2].Value2);
                            Console.WriteLine("Available Duty Hours -> " + driverRange[i, 3].Value2);
                            Console.WriteLine("Last Delivery Time -> " + tempAssExOrder.dtDevliveryDateTime);
                            Console.WriteLine("\tHours Elapsed -> " + hoursElapsed);
                            Console.WriteLine("\tNew Earliest Start Time -> " + tempAssExOrder.dtDevliveryDateTime);
                            Console.WriteLine("\tNew Driving Hours -> " + newDrivingHours);
                            Console.WriteLine("\tNew Duty Hours -> " + newDutyHours);
                            Console.WriteLine();

                            driverExcelWorksheet.Cells[i, 2] = newDrivingHours;
                            driverExcelWorksheet.Cells[i, 3] = newDutyHours;
                            driverExcelWorksheet.Cells[i, 4] = tempAssExOrder.dtDevliveryDateTime;
                            driverExcelWorksheet.Cells[i, 5] = tempAssExOrder.DeliverTo;
                            driverCount++;
                            assExOrders.Remove(tempAssExOrder);
                        }
                    }
                }

                VescoLog.LogEvent(vescoOrders.Count().ToString());
                List <String> badAssociatedOrders = AssociatedConverter.badOrders;
                foreach (String b in badAssociatedOrders)
                {
                    Console.Out.WriteLine("Bad Associated Order#," + b);
                }
                VescoLog.LogEvent(AppDomain.CurrentDomain.BaseDirectory);

                vescoExcelWorksheet = (Excel.Worksheet)vescoExcelWorkbook.Sheets.get_Item("RouteStop");

                //Location based stop delay
                locationWorkSheet = (Excel.Worksheet)vescoExcelWorkbook.Sheets.get_Item("Location");
                locationRange     = locationWorkSheet.UsedRange;
                int locationRowCount = locationRange.Rows.Count;
                List <SpecialLocation> specialLocations = new List <SpecialLocation>();
                SpecialLocation        specialLocation;

                for (int i = 2; i <= locationRowCount; i++)  // Start at the second row and skip the header
                {
                    if (locationRange[i, 6].Value2 != null)
                    {
                        specialLocation           = new SpecialLocation();
                        specialLocation.Name      = locationRange[i, 1].Value2.ToString();
                        specialLocation.Address   = locationRange[i, 2].Value2.ToString();
                        specialLocation.StopDelay = locationRange[i, 6].Value2.ToString();
                        specialLocations.Add(specialLocation);
                    }
                }

                specialLocation = new SpecialLocation();
                String stopActionCode;
                String windowStart = null;

                int row = 2;
                //Add the converted orders
                foreach (VescoOrder vo in vescoOrders)
                {
                    vescoExcelWorksheet.Cells[row, 1] = vo.Job;
                    vescoExcelWorksheet.Cells[row, 2] = vo.Sequence;
                    vescoExcelWorksheet.Cells[row, 3] = vo.StopAction;
                    vescoExcelWorksheet.Cells[row, 4] = vo.Location;
                    vescoExcelWorksheet.Cells[row, 5] = vo.Address;
                    specialLocation = specialLocations.Find(item => item.Name == vo.Location && item.Address == vo.Address);
                    stopActionCode  = vo.StopAction.Split('-')[0];

                    if ("11".Equals(stopActionCode) || "12".Equals(stopActionCode))
                    {
                        if (specialLocation != null)
                        {
                            vescoExcelWorksheet.Cells[row, 6] = specialLocation.StopDelay;
                        }
                        else
                        {
                            vescoExcelWorksheet.Cells[row, 6] = "60";
                        }
                    }
                    else
                    {
                        vescoExcelWorksheet.Cells[row, 6] = vo.StopDelay;
                    }

                    if (vo.WindowStart != null)
                    {
                        windowStart = (vo.WindowStart.Equals(vo.WindowEnd) ? null : vo.WindowStart);
                    }
                    else
                    {
                        windowStart = null;
                    }

                    vescoExcelWorksheet.Cells[row, 7]  = windowStart;
                    vescoExcelWorksheet.Cells[row, 8]  = vo.WindowEnd;
                    vescoExcelWorksheet.Cells[row, 9]  = vo.Hazardous;
                    vescoExcelWorksheet.Cells[row, 10] = vo.Overweight;
                    vescoExcelWorksheet.Cells[row, 11] = vo.OriginalLegNumber;
                    vescoExcelWorksheet.Cells[row, 12] = vo.ContainerNumber;
                    vescoExcelWorksheet.Cells[row, 13] = vo.SteamshipLine;
                    vescoExcelWorksheet.Cells[row, 14] = vo.LiveLoad;
                    vescoExcelWorksheet.Cells[row, 15] = vo.OriginalLegType;
                    vescoExcelWorksheet.Cells[row, 16] = vo.DispatcherSequence;
                    row++;
                }

                // Delete the Vesco file first since I can't figure out how to get rid of the confirmation dialog
                File.Delete(AppDomain.CurrentDomain.BaseDirectory + "\\Templates\\Vesco.xlsx");
                vescoExcelWorkbook.SaveAs(
                    AppDomain.CurrentDomain.BaseDirectory +
                    "Templates\\Vesco.xlsx",
                    Excel.XlFileFormat.xlWorkbookDefault, Type.Missing,
                    Type.Missing, false, false,
                    Excel.XlSaveAsAccessMode.xlNoChange,
                    Excel.XlSaveConflictResolution.xlLocalSessionChanges,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }
            catch (Exception ex)
            {
                VescoLog.LogEvent(ex.StackTrace);
            }
            finally
            {
                if (vescoExcelWorksheet != null)
                {
                    Marshal.ReleaseComObject(vescoExcelWorksheet);
                }
                if (vescoExcelWorkbook != null)
                {
                    Marshal.ReleaseComObject(vescoExcelWorkbook);
                }
                if (excelObj2 != null)
                {
                    excelObj2.Quit();
                    Marshal.ReleaseComObject(excelObj2);
                }
            }

            String path  = _fullPath + (isExecuted ? "," + executedFileName : "");
            Vesco  vesco = new Vesco(isExecuted, vescoOrders, badOrders, path, "Associated");

            vesco.performSteps();
        }
コード例 #15
0
ファイル: Associated.cs プロジェクト: OSADP/archive
        public void processAssDrop(string _fullPath)
        {
            VescoLog.LogEvent("processAssDrop, _fullPath=" + _fullPath);

            Boolean shouldContinue = false;

            Excel.Application excelObj  = new Excel.Application();
            Excel.Workbook    workbook  = null;
            Excel.Worksheet   worksheet = null;
            Excel.Range       assRange  = null;
            object            misValue  = System.Reflection.Missing.Value;

            System.Threading.Thread.Sleep(5000);

            try
            {
                workbook = excelObj.Workbooks.Open(_fullPath);

                int assOrdersCount = 0;

                worksheet   = (Excel.Worksheet)workbook.Sheets.Item[1];
                assRange    = worksheet.UsedRange;
                assRowCount = assRange.Rows.Count;
                assColCount = assRange.Columns.Count;

                if (assColCount != EXPECTED_ASS_COL_COUNT)
                {
                    String errMessage = _fullPath + " does not contain " + EXPECTED_ASS_COL_COUNT +
                                        " columns and can't be imported.  The most likely cause is an invlaid comma in the data.";
                    EmailHelper.sendGmail("Import Error", errMessage, false);
                    throw new Exception(errMessage);
                }

                runDate = getRunDate(_fullPath);

                // Sort based upon the order number and then the leg number
                assRange.Sort(assRange.Columns[1, Type.Missing],           // the first sort key - Order Number
                              Excel.XlSortOrder.xlAscending,
                              assRange.Columns[15, Type.Missing],          // second sort key - Leg Number
                              Type.Missing, Excel.XlSortOrder.xlAscending,
                              Type.Missing, Excel.XlSortOrder.xlAscending, // this would be the third key
                              Excel.XlYesNoGuess.xlYes,                    // ignore the header
                              Type.Missing,
                              Type.Missing,
                              Excel.XlSortOrientation.xlSortColumns,
                              Excel.XlSortMethod.xlPinYin,
                              Excel.XlSortDataOption.xlSortNormal,
                              Excel.XlSortDataOption.xlSortNormal,
                              Excel.XlSortDataOption.xlSortNormal);

                List <VescoOrder>   tempVescoOrders;
                List <TriniumOrder> assOrders = new List <TriniumOrder>();
                TriniumOrder        assOrd;

                Double   dblPickupDate;
                DateTime dtPickupDate;
                Double   dblDeliveryDate;
                DateTime dtDeliveryDate;

                for (int i = 2; i <= assRowCount; i++) // Start at the second row and skip the header
                {
                    assOrd                      = new TriniumOrder();
                    assOrd.OrderNumber          = assRange[i, 1].Value.ToString();
                    assOrd.DispatchCategoryCode = assRange[i, 2].Value.ToString();
                    assOrd.Sts                  = assRange[i, 3].Value.ToString();
                    assOrd.PickupName           = assRange[i, 4].Value.ToString();
                    assOrd.PickupAddress        = assRange[i, 5].Value.ToString();
                    assOrd.PickupCity           = assRange[i, 6].Value.ToString();
                    assOrd.PickupState          = assRange[i, 7].Value.ToString();
                    assOrd.PickupZip            = (assRange[i, 8].Value != null ? assRange[i, 8].Value.ToString() : "");
                    assOrd.DeliverName          = assRange[i, 9].Value.ToString();
                    assOrd.DeliverAddress       = assRange[i, 10].Value.ToString();
                    assOrd.DeliverCity          = assRange[i, 11].Value.ToString();
                    assOrd.DeliverState         = assRange[i, 12].Value.ToString();
                    assOrd.DeliverZip           = (assRange[i, 13].Value != null ? assRange[i, 13].Value.ToString() : "");
                    assOrd.LegType              = assRange[i, 14].Value.ToString();
                    assOrd.LegNumber            = assRange[i, 15].Value.ToString();

                    dblPickupDate = Convert.ToDouble(assRange[i, 16].Value2);
                    if (dblPickupDate != 0.0)
                    {
                        dtPickupDate = DateTime.FromOADate(dblPickupDate);
                        if (dtPickupDate.CompareTo(runDate) == 0 || dtPickupDate.CompareTo(runDate.AddDays(1)) == 0)
                        {
                            assOrd.ScheduledPickupDate     = dblPickupDate;
                            assOrd.ScheduledPickupTimeFrom = Convert.ToDouble(assRange[i, 17].Value2);
                            assOrd.ScheduledPickupTimeTo   = Convert.ToDouble(assRange[i, 18].Value2);
                        }
                    }

                    dblDeliveryDate = Convert.ToDouble(assRange[i, 19].Value2);
                    if (dblDeliveryDate != 0.0)
                    {
                        dtDeliveryDate = DateTime.FromOADate(dblDeliveryDate);
                        if (dtDeliveryDate.CompareTo(runDate) == 0 || dtDeliveryDate.CompareTo(runDate.AddDays(1)) == 0)
                        {
                            assOrd.ScheduledDeliverDate     = dblDeliveryDate;
                            assOrd.ScheduledDeliverTimeFrom = Convert.ToDouble(assRange[i, 20].Value2);
                            assOrd.ScheduledDeliverTimeTo   = Convert.ToDouble(assRange[i, 21].Value2);
                        }
                    }

                    assOrd.Ssl              = (assRange[i, 22].Value != null ? assRange[i, 22].Value.ToString() : "");
                    assOrd.Size             = assRange[i, 23].Value.ToString();
                    assOrd.Type             = assRange[i, 24].Value.ToString();
                    assOrd.Ll               = string.Equals(assRange[i, 25].Value, "yes", StringComparison.OrdinalIgnoreCase);
                    assOrd.Haz              = (assRange[i, 26].Value == "ü" || string.Equals(assRange[i, 26].Value, "yes", StringComparison.OrdinalIgnoreCase));
                    assOrd.SupplierCode     = assRange[i, 27].Value.ToString();
                    assOrd.DispatchSequence = assRange[i, 28].Value.ToString();
                    assOrd.Overweight       = string.Equals(assRange[i, 29].Value, "yes", StringComparison.OrdinalIgnoreCase);
                    assOrd.ContainerNumber  = (assRange[i, 30].Value != null ? assRange[i, 30].Value.ToString() : "");

                    assOrders.Add(assOrd);

                    // A new order number is coming up or this is the last record in the collection, add this job to the jobs list
                    if (i == assRowCount || assRange[i, 1].Value2.ToString() != assRange[i + 1, 1].Value2.ToString())
                    {
                        assOrdersCount++;

                        //Convert the Associated Order to a Vesco Order
                        tempVescoOrders = AssociatedConverter.Convert(assOrders);

                        if (tempVescoOrders.Count() == 0)
                        {
                            badOrders.Add(assOrd.OrderNumber);
                        }

                        //Add the converted orders
                        foreach (VescoOrder vo in tempVescoOrders)
                        {
                            vescoOrders.Add(vo);
                        }
                        triniumOrderCollection.Add(assOrders);
                        assOrders.Clear();
                    }
                }
                workbook.Close(false, misValue, misValue);
                shouldContinue = true;
            }
            catch (Exception ex)
            {
                VescoLog.LogEvent(ex.Message);
                VescoLog.LogEvent(ex.StackTrace);
            }
            finally
            {
                if (assRange != null)
                {
                    Marshal.ReleaseComObject(assRange);
                }
                if (worksheet != null)
                {
                    Marshal.ReleaseComObject(worksheet);
                }
                if (workbook != null)
                {
                    Marshal.ReleaseComObject(workbook);
                }
                if (excelObj != null)
                {
                    excelObj.Quit();
                    Marshal.ReleaseComObject(excelObj);
                }
            }

            if (shouldContinue)
            {
                generateVescoSpreadSheet(_fullPath);
            }
        }
コード例 #16
0
 static void TimerElapsed(object sender, ElapsedEventArgs e)
 {
     VescoLog.LogEvent("Wait just one minute");
 }
コード例 #17
0
ファイル: GmailWatcher.cs プロジェクト: OSADP/archive
        private void client_NewMessage(object sender, IdleMessageEventArgs e)
        {
            VescoLog.LogEvent(String.Format("Got a new message, uid = " + e.MessageUID));
            MailMessage mm = e.Client.GetMessage(e.MessageUID);

            VescoLog.LogEvent(String.Format("New email from <{0}>, subject <{1}>, attachments <{2}>",
                                            mm.From, mm.Subject, mm.Attachments.Count()));

            String[] distList = Properties.watchEmail.Split(',');

            //if (
            //        mm.From.Address.Equals(Properties.watchEmail, StringComparison.InvariantCultureIgnoreCase)  ||
            //        mm.From.Address.Equals("*****@*****.**", StringComparison.InvariantCultureIgnoreCase)
            //   )
            //{
            if (distList.Any(s => s.IndexOf(mm.From.Address, StringComparison.CurrentCultureIgnoreCase) > -1))
            {
                if (mm.Subject.Contains(Properties.watchOptSubject))
                {
                    if (mm.Attachments.Count() > 0)
                    {
                        Attachment attachment = mm.Attachments.First();
                        SavePlan(attachment, Properties.dropOptDir);
                        VescoLog.LogEvent(String.Format("Opt Attachment Name, {0}", attachment.Name));
                        e.Client.AddMessageFlags(e.MessageUID, null, MessageFlag.Seen);
                    }
                }
                else if (mm.Subject.Contains(Properties.watchExSubject) || mm.Subject.Contains(Properties.watchReOptSubject))
                {
                    e.Client.RemoveMessageFlags(e.MessageUID, null, MessageFlag.Seen);

                    // wait 5 seconds, sometimes the second message gets hung up.
                    //System.Threading.Thread.Sleep(5000);

                    // Get the Executed
                    IEnumerable <uint> executedUid = e.Client.Search(
                        SearchCondition.Subject(Properties.watchExSubject)
                        .And(SearchCondition.Unseen())
                        );

                    // this should never happen because the executed is always supposed to come first
                    // but if it does exit out and wait for the reOpt email to fire off the event
                    if (executedUid.Count() == 0)
                    {
                        VescoLog.LogEvent("ReOpt Email got delivered first.");
                        // reset the reOpt email message
                        e.Client.RemoveMessageFlags(e.MessageUID, null, MessageFlag.Seen);
                    }
                    else
                    {
                        // Get the ReOpt
                        IEnumerable <uint> reOptUid = e.Client.Search(
                            SearchCondition.Subject(Properties.watchReOptSubject)
                            .And(SearchCondition.Unseen())
                            );

                        // the reopt isn't there, yet so it will have
                        if (reOptUid.Count() == 0)
                        {
                            VescoLog.LogEvent("Executed email is there but the reOpt isn't.");
                            // reset the executed email message
                            e.Client.RemoveMessageFlags(executedUid.First(), null, MessageFlag.Seen);
                        }
                        // Get both attachments from the mail messages and drop them in the watched directories
                        else
                        {
                            MailMessage exMailMessage = e.Client.GetMessage(executedUid.First());
                            Attachment  exAttach      = exMailMessage.Attachments.First();
                            SavePlan(exAttach, Properties.dropExDir);
                            VescoLog.LogEvent(String.Format("Ex Attachment Name, {0}", exAttach.Name));

                            hasExecutedRun = true;

                            MailMessage reOptMailMessage = e.Client.GetMessage(reOptUid.First());
                            Attachment  reOptAttachment  = mm.Attachments.First();
                            SavePlan(reOptAttachment, Properties.dropReOptDir);
                            VescoLog.LogEvent(String.Format("ReOpt Attachment Name, {0}", reOptAttachment.Name));

                            VescoLog.LogEvent("Number of Emails -> " + (executedUid.Count() + reOptUid.Count()));
                        }
                    }
                }
                else
                {
                    VescoLog.LogEvent("Don't Process Message");
                    e.Client.RemoveMessageFlags(e.MessageUID, null, MessageFlag.Seen);
                }
            }
            else
            {
                VescoLog.LogEvent("Don't Process Message");
                e.Client.RemoveMessageFlags(e.MessageUID, null, MessageFlag.Seen);
            }
        }