public static bool DeleteFolder(LoggingLog logFile, DirectoryInfo folderDirectoryInfo, bool updateConsole)
        {
            bool hadDeletingIssues = false;

            if (!Directory.Exists(folderDirectoryInfo.FullName))
            {
                return false;
            }

            if (updateConsole)
                Console.Write("**");

            foreach (FileInfo fileInfo in folderDirectoryInfo.GetFiles())
            {
                try
                {
                    RemoveAttribute(fileInfo.FullName, fileInfo.Attributes, FileAttributes.ReadOnly);
                    fileInfo.Delete();
                }
                catch (Exception ex)
                {
                    logFile.LogAndPrintScreenMessage(String.Format("Could not delete file '{0}' because of {1}", fileInfo.FullName, ex.Message), true);
                    hadDeletingIssues = true;
                }
            }

            foreach (DirectoryInfo directoryInfo in folderDirectoryInfo.GetDirectories())
            {
                try
                {
                    DeleteFolder(logFile, directoryInfo, updateConsole);
                }
                catch (Exception ex)
                {
                    logFile.LogAndPrintScreenMessage(String.Format("Could not delete directory '{0}' because of {1}", directoryInfo.FullName, ex.Message), true);
                    hadDeletingIssues = true;
                }
            }

            //This deletes the folder after all its contents empty
            folderDirectoryInfo.Delete();

            if (updateConsole)
            {
                if (Console.CursorLeft > 1)
                    Console.CursorLeft = Console.CursorLeft - 2;
                Console.Write("  ");
                if (Console.CursorLeft > 1)
                    Console.CursorLeft = Console.CursorLeft - 2;
            }

            return hadDeletingIssues;
        }
示例#2
0
 public void IntializeWorkItem(
     UpdateOrdersAndInventoryConfigSection updateOrdersAndInventoryConfigSection,
     AccountSettingsConfigSection accountSettingsConfigSection,
     LoggingLog processingLog,
     WorkItemEnum workItemEnum, 
     string fileCommonName, 
     string logPath, 
     string pathForDataOutputWithYearMonth,
     DateTime startRange, 
     DateTime endRange)
 {
     UpdateOrdersAndInventoryConfigSection = updateOrdersAndInventoryConfigSection;
     AccountSettingsConfigSection = accountSettingsConfigSection;
     ProcessingLog = processingLog;
     WorkItemEnum = workItemEnum;
     FileCommonName = fileCommonName;
     LogPath = logPath;
     PathForDataOutputWithYearMonth = pathForDataOutputWithYearMonth;
     StartRange = startRange;
     EndRange = endRange;
 }
        private void SetupAppLogAndFiles()
        {
            _processingStartTime = DateTime.Now;
            _fileCommonName = string.Format("{0}_{1}_To_{2}{3}{4}",
                WorkType,
                StartRange.ToString("yyyy MM dd"),
                EndRange.ToString("yyyy MM dd"),
                ManifestCommonName,
                _processingStartTime.ToString("yyyy MM dd T HH mm ss")
                );

            _pathForDataOutputWithYearMonth = Path.Combine(_updateOrdersAndInventoryConfigSection.OutputFolder.Value, string.Format("Y{0:yyyy}M{1:MM}", StartRange, StartRange), AdditionalPathForWorkType, AdditionalSubDayPathForWorkType);
            ProgressDocumentFilePath = Path.Combine(_pathForDataOutputWithYearMonth, string.Format("ProgressDownload_{0}_Y{1:yyyy}M{2:MM}{3}.xml", WorkType, StartRange, StartRange, AdditionalDayForWorkType));
            _completedAllFileName = Path.Combine(_pathForDataOutputWithYearMonth, string.Format("DownloadComplete_{0}_Y{1:yyyy}M{2:MM}{3}.txt", WorkType, StartRange, StartRange, AdditionalDayForWorkType));

            if (!Directory.Exists(_pathForDataOutputWithYearMonth))
                Directory.CreateDirectory(_pathForDataOutputWithYearMonth);

            _logPath = Path.Combine(_pathForDataOutputWithYearMonth, "Logs");

            if (!Directory.Exists(_logPath))
                Directory.CreateDirectory(_logPath);

            _processingLog = new LoggingLog(Path.Combine(_logPath, string.Format("Log_For_{0}.log", _fileCommonName)));
            _processingLog.LogAndPrintScreenMessage(string.Format("At [{0}] starting to get {1} for [{2}]", _processingStartTime.ToString("g"),WorkType, _fileCommonName), true);

            _emailSmptSendingEngine = new EmailSmptSendingEngine(
                _updateOrdersAndInventoryConfigSection.SendEmail.Value,
                "smtp.gmail.com",
                587,
                _updateOrdersAndInventoryConfigSection.EncryptedPassage.Value,
                _updateOrdersAndInventoryConfigSection.EncryptedDirection.Value,
                _updateOrdersAndInventoryConfigSection.EmailUserFromAddress.Value,
                _updateOrdersAndInventoryConfigSection.EncryptedEmailPassword.Value
                ) { DefaultToAddress = _updateOrdersAndInventoryConfigSection.EmailUserToAddress.Value };
        }
        public void ExecuteWorkItems()
        {
            bool hadException = false;
            try
            {
                ExtractConfigurationFiles();
                SetupAppLogAndFiles();
                PopulateWorkItemsList();

                SendEmailWithCatch("Starting Download", string.Format("Starting download for {0}", WorkType), null, null);

                _previousExecutionState = MiscNativeMethods.SetThreadExecutionState(MiscNativeMethods.ES_CONTINUOUS | MiscNativeMethods.ES_SYSTEM_REQUIRED);
                if (_previousExecutionState == 0)
                {
                    _processingLog.LogAndPrintScreenMessage("Could not prevent sleeping make sure computer stays awake during the download!", true);
                }

                if (File.Exists(_completedAllFileName))
                {
                    _processingLog.LogAndPrintScreenMessage(string.Format("Processing for {0} had already been completed.", _completedAllFileName), true);
                }
                else
                {
                    //Exceptions for each work item are caught and logged
                    ExecuteWorkItemInList();
                }
            }
            catch (Exception exception)
            {
                hadException = true;
                if (_processingLog != null)
                {
                    _processingLog.LogAndPrintScreenMessage(string.Format("Get {0} had exception during Setup and Download:\n {1}:\n{2}", WorkType, exception.Message, exception.StackTrace), true);
                }
            }
            finally
            {
                _processingEndTime = DateTime.Now;
                TimeSpan duration = _processingEndTime - _processingStartTime;
                try
                {
                    string downloadProgressContents = string.Empty;
                    if (DownloadProgress !=null)
                    {
                        DownloadProgress.SaveFile(ProgressDocumentFilePath);
                        downloadProgressContents = DownloadProgress.GetXmlAsString();
                    }

                    bool allWorkDoneOkay = _allWorkItemsInListCompleted && !hadException;
                    if (allWorkDoneOkay)
                    {
                        File.Create(_completedAllFileName);
                        WriteManifestFile();
                    }

                    string emailContents = string.Format("Finished download for {0}.\r\n" +
                                      "All work done okay?: {1}.\r\n" +
                                      "Progress Status Document:\r\n" +
                                      "{2}",
                                      WorkType,
                                      allWorkDoneOkay,
                                      downloadProgressContents);

                    if (_processingLog != null)
                    {
                        _processingLog.LogAndPrintScreenMessage(string.Format("Download progress contents at finish:\r\n{0}", downloadProgressContents), true);
                        _processingLog.LogAndPrintScreenMessage(string.Format("Email message contents at finish:\r\n{0}", emailContents), true);
                        _processingLog.LogAndPrintScreenMessage(string.Format("At [{0}] finished getting {1} for [{2}]. It took {3:hh\\:mm\\:ss} to complete the download.",
                            _processingEndTime.ToString("g"), WorkType, _fileCommonName, duration), true);
                        _processingLog.Dispose();
                        _processingLog = null;
                    }

                    SendEmailWithCatch(string.Format("Finished {0} download. All items in work list completed: {1}. Had issue in execution: {2}.", WorkType, _allWorkItemsInListCompleted, hadException),
                        emailContents,
                        null,
                        Path.Combine(_logPath, string.Format("Log_For_{0}.log", _fileCommonName)));
                }
                catch (Exception exception)
                {
                    //TODO: look into creating Error log folder for this type of errors
                    string overallIssue = string.Format("Overall issue in close out work items hadException [{0}] with exception:\n {1}:\n{2}", hadException, exception.Message, exception.StackTrace);
                    throw;
                }
                finally
                {
                    MiscNativeMethods.SetThreadExecutionState(_previousExecutionState);
                    Console.WriteLine();
                    Console.WriteLine("Finished doing download");

                    if (_autoCloseOverride.HasValue)
                    {
                        if (!_autoCloseOverride.Value)
                        {
                            Console.WriteLine("Press Enter To Exit");
                            Console.ReadLine();
                        }
                    }
                    else
                    {
                        if (!_updateOrdersAndInventoryConfigSection.AutoClose.Value)
                        {
                            Console.WriteLine("Press Enter To Exit");
                            Console.ReadLine();
                        }
                    }
                }
            }
        }
 protected override void ProcessPrintConfigItem(LoggingLog log, bool toScreen, PropertyInfo prop)
 {
     //use this if create custom configuration type
 }
        public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, string tooLongFolder, LoggingLog backupLog,
            bool showErrorsOnScreen, BackupSizeAndProgress backupSizeAndProgress)
        {
            DirectoryInfo sourceDir;
            DirectoryInfo[] sourceDirArray;
            try
            {
                sourceDir = new DirectoryInfo(sourceDirName);
                sourceDirArray = sourceDir.GetDirectories();
            }
            catch (UnauthorizedAccessException)
            {
                //this is for hidden system files
                return;
            }
            catch (Exception ex)
            {
                backupLog.LogAndPrintScreenMessage(String.Format("Could not copy source directory: {0}. Because: {1}", sourceDirName, ex), showErrorsOnScreen);
                backupSizeAndProgress.HadIssues = true;
                return;
            }

            // If the source directory does not exist
            if (!sourceDir.Exists)
            {
                backupLog.LogAndPrintScreenMessage(String.Format("Could not copy source directory: {0}. Source directory does not exist or could not be found.", sourceDirName), showErrorsOnScreen);
                backupSizeAndProgress.HadIssues = true;
                return;
            }

            // If the destination directory does not exist, create it.
            try
            {
                if (!Directory.Exists(destDirName))
                {
                    Directory.CreateDirectory(destDirName);
                }
            }
            catch (PathTooLongException)
            {
                DirectoryInfo dirInfo = sourceDir;
                string dirName = dirInfo.Name;
                string newDestName = String.Format("{0}_TooLong_{1}", dirName, DateTime.Now.ToString("hhmmssffff"));
                string newDestPath = Path.Combine(tooLongFolder, newDestName);

                DirectoryCopy(sourceDirName, newDestPath, copySubDirs, tooLongFolder, backupLog, showErrorsOnScreen, backupSizeAndProgress);
                return;
            }
            catch (Exception ex)
            {
                //TODO: figure out what exception still caught
                backupLog.LogAndPrintScreenMessage(String.Format("Could not create destination directory: {0}. Because: {1}", destDirName, ex), showErrorsOnScreen);
                backupSizeAndProgress.HadIssues = true;
                return;
            }

            // Get the file contents of the directory to copy.
            FileInfo[] files = sourceDir.GetFiles();

            foreach (FileInfo file in files)
            {
                // Create the path to the new copy of the file.
                string temppath = Path.Combine(destDirName, file.Name);

                // Copy the file.
                try
                {
                    if (backupSizeAndProgress.ExcludedExtensions.Contains(file.Extension))
                    {
                        backupSizeAndProgress.TotalFilesExcluded++;
                        continue;
                    }
                    file.CopyTo(temppath, true);
                    backupSizeAndProgress.TotalSizeBackedup += file.Length;
                    backupSizeAndProgress.TotalFileBackedup++;
                }
                catch (PathTooLongException)
                {
                    string parentDirName;
                    try
                    {
                        DirectoryInfo dirInfo = file.Directory;
                        parentDirName = dirInfo.Name;
                    }
                    catch (PathTooLongException)
                    {
                        parentDirName = "NoDirectory";
                    }

                    string fullDestPath = "Not Assigned";
                    try
                    {
                        string newDestName = String.Format("{0}_TooLong_{1}", parentDirName, DateTime.Now.ToString("hhmmssffff"));
                        string newDestPath = Path.Combine(tooLongFolder, newDestName);
                        Directory.CreateDirectory(newDestPath);
                        fullDestPath = Path.Combine(newDestPath, file.Name);
                        file.CopyTo(fullDestPath, true);

                        backupSizeAndProgress.TotalSizeBackedup += file.Length;
                        backupSizeAndProgress.TotalFileBackedup++;
                    }
                    catch (Exception ex)
                    {
                        backupLog.LogAndPrintScreenMessage(String.Format("Failed to copy Too Long file twice: {0} to Destination: {1}, Because: {2}", file.Name, fullDestPath, ex.Message), showErrorsOnScreen);
                    }
                }
                catch (Exception ex)
                {
                    backupLog.LogAndPrintScreenMessage(String.Format("Could not copy: {0}. Because: {1}", file.FullName, ex), showErrorsOnScreen);
                    backupSizeAndProgress.HadIssues = true;
                }
            }

            // If copySubDirs is true, copy the subdirectories.
            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in sourceDirArray)
                {
                    // Create the subdirectory.
                    string temppath = Path.Combine(destDirName, subdir.Name);

                    // Copy the subdirectories.
                    backupSizeAndProgress.TotalDirectoryBackedup++;
                    DirectoryCopy(subdir.FullName, temppath, true, tooLongFolder, backupLog, showErrorsOnScreen, backupSizeAndProgress);
                }
            }
        }