/// <summary>
 /// Show a status message at the console and optionally include in the log file
 /// </summary>
 /// <param name="statusMessage">Status message</param>
 /// <param name="isError">True if this is an error</param>
 /// <param name="writeToLog">True to write to the log file; false to only display at console</param>
 public static void LogMessage(string statusMessage, bool isError = false, bool writeToLog = true)
 {
     if (writeToLog)
     {
         if (isError)
         {
             LogTools.LogError(statusMessage);
         }
         else
         {
             LogTools.LogMessage(statusMessage);
         }
     }
     else
     {
         if (isError)
         {
             ConsoleMsgUtils.ShowErrorCustom(statusMessage, false);
         }
         else
         {
             Console.WriteLine(statusMessage);
         }
     }
 }
Beispiel #2
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            // Start the main program running
            try
            {
                if (mMainProcess == null)
                {
                    mMainProcess = new MainProgram();
                    if (!mMainProcess.InitMgr())
                    {
                        PRISM.Logging.FileLogger.FlushPendingMessages();
                        return;
                    }
                    mMainProcess.DoDirectoryCreation();
                }
            }
            catch (Exception ex)
            {
                var errMsg = "Critical exception starting application: " + ex.Message;
                ConsoleMsgUtils.ShowWarning(errMsg + "; " + StackTraceFormatter.GetExceptionStackTrace(ex));
                ConsoleMsgUtils.ShowWarning("Exiting clsMainProcess.Main with error code = 1");
            }

            PRISM.Logging.FileLogger.FlushPendingMessages();
        }
Beispiel #3
0
        /// <summary>
        /// Show a status message at the console and optionally include in the log file
        /// </summary>
        /// <param name="statusMessage">Status message</param>
        /// <param name="isError">True if this is an error</param>
        /// <param name="writeToLog">True to write to the log file; false to only display at console</param>
        public static void LogMessage(string statusMessage, bool isError = false, bool writeToLog = true)
        {
            if (isError)
            {
                ConsoleMsgUtils.ShowErrorCustom(statusMessage, false);
            }
            else
            {
                Console.WriteLine(statusMessage);
            }

            if (!writeToLog)
            {
                return;
            }

            try
            {
                if (isError)
                {
                    WriteLog(LoggerTypes.LogFile, BaseLogger.LogLevels.ERROR, statusMessage);
                }
                else
                {
                    WriteLog(LoggerTypes.LogFile, BaseLogger.LogLevels.INFO, statusMessage);
                }
            }
            catch (Exception ex)
            {
                ErrorWritingToLog(statusMessage, ex);
            }
        }
        public MsScan(int scanNumber, XRawFileIO reader)
        {
            ScanNumber = scanNumber;

            if (!reader.GetScanInfo(scanNumber, out var scanInfo))
            {
                ConsoleMsgUtils.ShowWarning("Scan {0} not found in {1}", scanNumber, Path.GetFileName(reader.RawFilePath));
                return;
            }

            // Get centroided data
            var dataPointCount = GetScanData(reader, scanInfo, out var mzList, out var intensityList);

            MsLevel    = scanInfo.MSLevel;
            PeaksCount = dataPointCount;

            switch (scanInfo.IonMode)
            {
            case IonModeConstants.Positive:
                Polarity = "+";
                break;

            case IonModeConstants.Negative:
                Polarity = "-";
                break;

            case IonModeConstants.Unknown:
                Polarity = string.Empty;
                break;
            }

            FilterLine = scanInfo.FilterText;
            ScanType   = GetScanType();

            RetentionTime = "PT" + Math.Round(scanInfo.RetentionTime * 60, 8) + "S";
            TotIonCurrent = scanInfo.TotalIonCurrent;

            string encodedPeaks;

            if (PeaksCount == 0)
            {
                LowMz             = 0;
                HighMz            = 0;
                BasePeakMz        = 0;
                BasePeakIntensity = 0;

                encodedPeaks = Base64EncodeMsData(mzList, intensityList);
            }
            else
            {
                LowMz             = mzList.Min();
                HighMz            = mzList.Max();
                BasePeakMz        = scanInfo.BasePeakMZ;
                BasePeakIntensity = scanInfo.BasePeakIntensity;

                encodedPeaks = Base64EncodeMsData(mzList, intensityList);
            }

            PeakData = new Peaks(32, "network", "m/z-int", "none", 0, encodedPeaks);
        }
Beispiel #5
0
        private static void ShowGUI()
        {
            Application.EnableVisualStyles();
            Application.DoEvents();
            try
            {
                var handle = GetConsoleWindow();

                if (!mDebugMode)
                {
                    // Hide the console
                    ShowWindow(handle, SW_HIDE);
                }

                var objFormMain = new GUI()
                {
                    KeepDB = mKeepDB
                };

                objFormMain.ShowDialog();

                if (!mDebugMode)
                {
                    // Show the console
                    ShowWindow(handle, SW_SHOW);
                }
            }
            catch (Exception ex)
            {
                ConsoleMsgUtils.ShowWarning("Error in ShowGUI: " + ex.Message);
                ConsoleMsgUtils.ShowWarning(StackTraceFormatter.GetExceptionStackTraceMultiLine(ex));

                MessageBox.Show("Error in ShowGUI: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Beispiel #6
0
        private static void ProgressSubtaskChangedHandler()
        {
#if GUI
            if (mProgressForm != null)
            {
                mProgressForm.UpdateCurrentSubTask(mMASIC.SubtaskDescription);
                mProgressForm.UpdateSubtaskProgressBar(mMASIC.SubtaskProgressPercentComplete);
                if (mProgressForm.KeyPressAbortProcess)
                {
                    mMASIC.AbortProcessingNow();
                }

                Application.DoEvents();
                return;
            }
#endif

            if (DateTime.UtcNow.Subtract(mLastSubtaskProgressTime).TotalSeconds < 10)
            {
                return;
            }
            mLastSubtaskProgressTime = DateTime.UtcNow;

            ConsoleMsgUtils.ShowDebug("{0}: {1}%", mMASIC.SubtaskDescription, mMASIC.SubtaskProgressPercentComplete);
        }
        /// <summary>
        /// Find the best candidate folder with Python 3.x
        /// </summary>
        /// <returns>True if Python could be found, otherwise false</returns>
        protected static bool FindPython()
        {
            if (!string.IsNullOrWhiteSpace(PythonPath))
            {
                return(true);
            }

            if (SystemInfo.IsLinux)
            {
                PythonPath = "/usr/bin/python3";
                ConsoleMsgUtils.ShowDebug("Assuming Python 3 is at {0}", PythonPath);
                return(true);
            }

            foreach (var directoryPath in PythonPathsToCheck())
            {
                var exePath = FindPythonExe(directoryPath);
                if (string.IsNullOrWhiteSpace(exePath))
                {
                    continue;
                }

                PythonPath = exePath;
                break;
            }

            return(!string.IsNullOrWhiteSpace(PythonPath));
        }
        /// <summary>
        /// Lookup the base name and dataset ID for the given dataset name
        /// </summary>
        /// <param name="baseNameByDatasetName"></param>
        /// <param name="datasetIDs"></param>
        /// <param name="datasetName"></param>
        /// <param name="baseDatasetName">Output: base dataset name, or empty string if not found</param>
        /// <param name="datasetID">Output: dataset ID, or 0 if not found</param>
        protected void GetBaseNameAndDatasetID(
            Dictionary <string, string> baseNameByDatasetName,
            Dictionary <string, int> datasetIDs,
            string datasetName,
            out string baseDatasetName,
            out int datasetID)
        {
            if (string.IsNullOrWhiteSpace(datasetName))
            {
                baseDatasetName = string.Empty;
                datasetID       = 0;
                return;
            }

            if (!baseNameByDatasetName.TryGetValue(datasetName, out baseDatasetName))
            {
                ConsoleMsgUtils.ShowDebug(
                    "The baseNameByDatasetName dictionary does not contain key {0}; this is unexpected",
                    datasetName);
            }

            if (!datasetIDs.TryGetValue(datasetName, out datasetID))
            {
                datasetID = 0;
            }
        }
Beispiel #9
0
        private static int ProcessSQLiteDB(FileInfo fiSourceFile, string sourceTableName)
        {
            try
            {
                var runner = new Runner
                {
                    ShowProgressAtConsole = true
                };
                RegisterEvents(runner);

                var success = runner.ProcessSQLite(fiSourceFile.DirectoryName, fiSourceFile.Name, sourceTableName);

                if (success)
                {
                    Console.WriteLine();
                    Console.WriteLine("Processing complete");
                    ProgRunner.SleepMilliseconds(750);
                    return(0);
                }

                ConsoleMsgUtils.ShowWarning("Error computing protein parsimony: RunAlgorithm reports false");
                ProgRunner.SleepMilliseconds(1500);
                return(-3);
            }
            catch (Exception ex)
            {
                ConsoleMsgUtils.ShowError("Error computing protein parsimony", ex);
                ProgRunner.SleepMilliseconds(1500);
                return(-2);
            }
        }
Beispiel #10
0
        static int Main(string[] args)
        {
            var appName = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name;
            var exeName = Path.GetFileName(PRISM.FileProcessor.ProcessFilesOrDirectoriesBase.GetAppPath());

            var parser = new CommandLineParser <CommandLineOptions>(appName, PRISM.FileProcessor.ProcessFilesOrDirectoriesBase.GetAppVersion(PROGRAM_DATE))
            {
                ProgramInfo = ConsoleMsgUtils.WrapParagraph(
                    "This program contacts DMS to retrieve a list of Bionet computers (hosts). " +
                    "It pings each computer to see which respond, then optionally contacts DMS with the list of active hosts.") + Environment.NewLine + Environment.NewLine +
                              ConsoleMsgUtils.WrapParagraph(
                    "By default, it contacts DMS to retrieve the list of bionet hosts, then pings each one (appending suffix .bionet)." +
                    "Alternatively, use /Manual to define a list of hosts to contact (.bionet is not auto-appended). " +
                    "Or use /File to specify a text file listing one host per line (.bionet is not auto-appended)." +
                    "The /File switch is useful when used in conjunction with script Export_DNS_Entries.ps1, " +
                    "which can be run daily via a scheduled task to export all hosts and IP addresses " +
                    "tracked by the bionet DNS server (Gigasax).") + Environment.NewLine + Environment.NewLine +
                              ConsoleMsgUtils.WrapParagraph(
                    "When using /File, this program will still contact DMS to determine which hosts are inactive, " +
                    "and it will skip those hosts.  Use /HideInactive to not see the names of the skipped hosts"),
                ContactInfo = "Program written by Matthew Monroe for the Department of Energy (PNNL, Richland, WA)" + Environment.NewLine +
                              "E-mail: [email protected] or [email protected]" + Environment.NewLine +
                              "Website: https://github.com/PNNL-Comp-Mass-Spec/ or https://panomics.pnnl.gov/ or https://www.pnnl.gov/integrative-omics"
            };

            parser.UsageExamples.Add(
                "Program syntax:" + Environment.NewLine +
                exeName + Environment.NewLine +
                " [/Manual:Host1,Host2,Host3] [/File:HostListFile] [/HideInactive]" + Environment.NewLine +
                " [/Simulate] [/DB] [/DBAdd] [/NoDB]");

            var result = parser.ParseArgs(args);

            mOptions = result.ParsedResults;

            // Running with no command-line arguments specified is valid.
            if (args.Length > 0 && !result.Success)
            {
                if (parser.CreateParamFileProvided)
                {
                    return(0);
                }

                // Delay for 750 msec in case the user double clicked this file from within Windows Explorer (or started the program via a shortcut)
                System.Threading.Thread.Sleep(750);
                return(-1);
            }

            try
            {
                PingBionetComputers(mOptions.HostNameFile, mOptions.HostOverrideList);
                return(0);
            }
            catch (Exception ex)
            {
                ShowErrorMessage("Error occurred in Program->Main", ex);
                return(-1);
            }
        }
Beispiel #11
0
        private static void ShowWarning(string message)
        {
            Console.WriteLine();
            var msg = "Warning: " + message;

            ConsoleMsgUtils.ShowWarning(msg);
            mLogFile?.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\t" + msg);
        }
Beispiel #12
0
 private void WarnOnce(WriteWarnings code, string message)
 {
     if (warningTracker.Contains(code))
     {
         return;
     }
     warningTracker.Add(code);
     ConsoleMsgUtils.ShowWarning(string.Format("WARNING: {0}!", message));
 }
        /// <summary>
        /// Report an important error
        /// </summary>
        /// <param name="message"></param>
        private void OnCriticalErrorEvent(string message)
        {
            if (CriticalErrorEvent == null && WriteToConsoleIfNoListener)
            {
                ConsoleMsgUtils.ShowError(message, false, false, EmptyLinesBeforeErrorMessages);
            }

            CriticalErrorEvent?.Invoke(message, null);
        }
Beispiel #14
0
 /// <summary>
 /// Validate the options
 /// </summary>
 /// <returns>True if all options are valid</returns>
 /// <remarks>This method is called from Program.cs</remarks>
 // ReSharper disable once UnusedMember.Global
 public bool Validate()
 {
     if (string.IsNullOrWhiteSpace(InputFilePathSpec))
     {
         ConsoleMsgUtils.ShowWarning("Error: Input file spec must be provided and non-empty, for example *.tsv");
         return(false);
     }
     return(true);
 }
        public bool Validate()
        {
            if (string.IsNullOrWhiteSpace(InputDataFilePath))
            {
                ConsoleMsgUtils.ShowError($"ERROR: Input path must be provided and non-empty; \"{InputDataFilePath}\" was provided.");
                return(false);
            }

            return(true);
        }
Beispiel #16
0
        private static void ValidateLoaderByPath()
        {
            if (string.IsNullOrWhiteSpace(PwizPath))
            {
                var message = CannotFindExceptionMessage();

                ConsoleMsgUtils.ShowError(message);
                throw new TypeLoadException(message);
            }
        }
Beispiel #17
0
 private static void PeptideHitResultsProcRunner_WarningEvent(string message)
 {
     if (message.StartsWith("Warning", StringComparison.OrdinalIgnoreCase))
     {
         ConsoleMsgUtils.ShowWarning(message);
     }
     else
     {
         ConsoleMsgUtils.ShowWarning("Warning: " + message);
     }
 }
Beispiel #18
0
        private static void AssureDirectoryExists(DirectoryInfo directoryInfo)
        {
            if (directoryInfo == null || directoryInfo.Exists)
            {
                return;
            }

            ConsoleMsgUtils.ShowWarning("Creating missing directory: " + directoryInfo.FullName);
            directoryInfo.Create();
            Console.WriteLine();
        }
Beispiel #19
0
        private void PeptideToProteinMapper_ProgressUpdate(string progressMessage, float percentComplete)
        {
            if (DateTime.UtcNow.Subtract(mLastProgressTime).TotalSeconds < 1)
            {
                return;
            }

            mLastProgressTime = DateTime.UtcNow;

            ConsoleMsgUtils.ShowDebug("Peptide to protein mapper is {0:F1}% complete: {1}", percentComplete, progressMessage);
        }
Beispiel #20
0
        private void StoreKey(int linesRead, string sectionName, IDictionary <string, string> sectionInfo, string key, string value)
        {
            if (sectionInfo.ContainsKey(key))
            {
                ConsoleMsgUtils.ShowWarning(
                    "Line {0} has a duplicate key named {1} in section {2}; ignoring duplicate value {3}",
                    linesRead, key, sectionName, value);
            }

            sectionInfo.Add(key, value);
        }
Beispiel #21
0
        private void Parse()
        {
            _rows.Clear();
            _data.Clear();
            _header.Clear();

            var headerParsed = false;

            using (var reader = new StreamReader(new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        continue;
                    }

                    var token = line.Split(_delimeter);
                    if (!headerParsed)
                    {
                        for (var i = 0; i < token.Length; i++)
                        {
                            if (_data.ContainsKey(token[i]))
                            {
                                ConsoleMsgUtils.ShowWarning("Warning: header line has duplicate column names; ignoring duplicate " + token[i]);
                                continue;
                            }
                            _header.Add(i, token[i]);
                            _data[token[i]] = new List <string>();
                        }
                        headerParsed = true;
                        continue;
                    }

                    if (token.Length > _header.Count)
                    {
                        continue;
                    }

                    for (var i = 0; i < token.Length; i++)
                    {
                        if (!_header.ContainsKey(i))
                        {
                            continue;
                        }

                        _data[_header[i]].Add(token[i]);
                    }
                    _rows.Add(line);
                }
            }
        }
        private static void ShowProgramHelp()
        {
            try
            {
                Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
                                      "This program can be used to split apart a protein FASTA file into a number of sections. " +
                                      "Although the splitting is random, each section will have a nearly identical number of residues."));
                Console.WriteLine();
                Console.WriteLine("Program syntax:");
                Console.WriteLine(Path.GetFileName(ProcessFilesOrDirectoriesBase.GetAppPath()) +
                                  " /I:SourceFastaFile [/O:OutputDirectoryPath]");
                Console.WriteLine(" [/N:SplitCount] [/MB:TargetSizeMB] [/P:ParameterFilePath] ");
                Console.WriteLine(" [/S:[MaxLevel]] [/A:AlternateOutputDirectoryPath] [/R] [/L]");
                Console.WriteLine();
                Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
                                      "The input file path can contain the wildcard character * and should point to a FASTA file. " +
                                      "The output directory switch is optional. " +
                                      "If omitted, the output file will be created in the same directory as the input file."));
                Console.WriteLine();
                Console.WriteLine("Use /N to define the number of parts to split the input file into.");
                Console.WriteLine("For example, /N:10 will split the input FASTA file into 10 parts");
                Console.WriteLine();
                Console.WriteLine("Alternatively, use /MB to specify the size of the split FASTA files, in MB (minimum {0} MB)", SplitterOptions.MINIMUM_TARGET_FILE_SIZE_MB);
                Console.WriteLine("For example, /MB:100 will create separate FASTA files that are each ~100 MB in size");
                Console.WriteLine();
                Console.WriteLine("If both /N and /MB are specified, /N will be ignored");
                Console.WriteLine();
                Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
                                      "The parameter file path is optional. " +
                                      "If included, it should point to a valid XML parameter file."));
                Console.WriteLine();
                Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
                                      "Use /S to process all valid files in the input directory and subdirectories. " +
                                      "Include a number after /S (like /S:2) to limit the level of subdirectories to examine. " +
                                      "When using /S, you can redirect the output of the results using /A. " +
                                      "When using /S, you can use /R to re-create the input directory hierarchy in the alternate output directory (if defined)."));
                Console.WriteLine("Use /L to log messages to a file.");
                Console.WriteLine();
                Console.WriteLine("Program written by Matthew Monroe for the Department of Energy (PNNL, Richland, WA) in 2010");
                Console.WriteLine("Version: " + GetAppVersion());
                Console.WriteLine();
                Console.WriteLine("E-mail: [email protected] or [email protected]");
                Console.WriteLine("Website: https://omics.pnl.gov/ or https://panomics.pnnl.gov/");
                Console.WriteLine();

                // Delay for 750 msec in case the user double clicked this file from within Windows Explorer (or started the program via a shortcut)
                Thread.Sleep(750);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error displaying the program syntax: " + ex.Message);
            }
        }
Beispiel #23
0
        private bool ReadAnnoFile()
        {
            _offsetList   = new List <long>();
            _nameToLength = new Dictionary <string, int>();
            _names        = new Dictionary <long, string>();
            _descriptions = new Dictionary <long, string>();
            _nameToOffset = new Dictionary <string, long>();

            _duplicateNameCounts = new Dictionary <string, int>();

            using (var reader = new StreamReader(_annoFilePath))
            {
                string s;
                while ((s = reader.ReadLine()) != null)
                {
                    var token = s.Split(FastaDatabaseConstants.AnnotationDelimiter);
                    if (token.Length < 4)
                    {
                        break;
                    }
                    var offset = long.Parse(token[0]);
                    _offsetList.Add(offset);
                    var length = int.Parse(token[1]);
                    var name   = token[2];

                    if (_nameToLength.TryGetValue(name, out _))
                    {
                        ConsoleMsgUtils.ShowWarning(string.Format(
                                                        "Duplicate protein name, renaming {0} at offset {1} in {2} to avoid collisions",
                                                        name, offset, Path.GetFileName(_annoFilePath)));

                        if (_duplicateNameCounts.TryGetValue(name, out var duplicateSuffix))
                        {
                            duplicateSuffix++;
                            _duplicateNameCounts[name] = duplicateSuffix;
                        }
                        else
                        {
                            duplicateSuffix = 1;
                            _duplicateNameCounts.Add(name, duplicateSuffix);
                        }
                        name += "_Duplicate" + duplicateSuffix.ToString("00");
                    }

                    _nameToLength.Add(name, length);
                    _names.Add(offset, name);
                    _nameToOffset.Add(name, offset);
                    _descriptions.Add(offset, token[3]);
                }
            }

            return(true);
        }
Beispiel #24
0
        private static void ShowProgramHelp()
        {
            var exePath = PRISM.FileProcessor.ProcessFilesOrDirectoriesBase.GetAppPath();

            Console.WriteLine("Program syntax:" + Environment.NewLine + Path.GetFileName(exePath));
            Console.WriteLine("  InputFilePath.raw [/GetFilters] [/Centroid] [/Sum] [/Start:Scan] [/End:Scan]");
            Console.WriteLine("  [/ScanInfo:IntervalScans] [/NoScanData] [/NoScanEvents] [/NoCE]");
            Console.WriteLine("  [/NoMethods] [/MSLevelOnly] [/Trace]");

            Console.WriteLine();
            Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
                                  "Running this program without any parameters it will process file " + DEFAULT_FILE_PATH));
            Console.WriteLine();
            Console.WriteLine("The first parameter specifies the file to read");
            Console.WriteLine();
            Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
                                  "Use /GetFilters to compile and display a list of scan filters in any MASIC _ScanStatsEx.txt files in the working directory"));
            Console.WriteLine();
            Console.WriteLine("Without /GetFilters, data is read from the file, either from all scans, or a scan range");
            Console.WriteLine("Use /Start and /End to limit the scan range to process");
            Console.WriteLine("If /Start and /End are not provided, will read every 21 scans");
            Console.WriteLine();
            Console.WriteLine("Use /Centroid to centroid the data when reading");
            Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
                                  "Use /Sum to test summing the data across 15 scans " +
                                  "(each spectrum will be shown twice; once with summing and once without)"));
            Console.WriteLine();
            Console.WriteLine("While reading data, the scan number and elution time is displayed for each scan.");
            Console.WriteLine("To show this info every 5 scans, use /ScanInfo:5");
            Console.WriteLine();
            Console.WriteLine("Use /NoScanData to skip loading any scan data");
            Console.WriteLine("Use /NoScanEvents to skip loading any scan events");
            Console.WriteLine("Use /NoCE to skip trying to determine collision energies");
            Console.WriteLine("Use /NoMethods to skip loading instrument methods");
            Console.WriteLine();
            Console.WriteLine("Use /MSLevelOnly to only load MS levels using GetMSLevel");
            Console.WriteLine("Use /TestFilters to test the parsing of a set of standard scan filters");
            Console.WriteLine();
            Console.WriteLine("Use /Trace to display additional debug messages");
            Console.WriteLine();
            Console.WriteLine("Program written by Matthew Monroe for the Department of Energy (PNNL, Richland, WA) in 2012");
            Console.WriteLine("Version: " + GetAppVersion());
            Console.WriteLine();

            Console.WriteLine("E-mail: [email protected] or [email protected]");
            Console.WriteLine("Website: https://omics.pnl.gov or https://panomics.pnnl.gov/");
            Console.WriteLine();


            // Delay for 1.5 seconds in case the user double clicked this file from within Windows Explorer (or started the program via a shortcut)
            System.Threading.Thread.Sleep(1500);
        }
Beispiel #25
0
        private static void ShowError(string message, Exception ex = null)
        {
            Console.WriteLine();
            var msg = "Error: " + message;

            ConsoleMsgUtils.ShowError(msg, ex);
            mLogFile?.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\t" + msg);

            if (ex != null)
            {
                mLogFile?.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\t" + StackTraceFormatter.GetExceptionStackTrace(ex));
            }
        }
Beispiel #26
0
        /// <summary>
        /// Log a message to the local, generic log file
        /// </summary>
        /// <param name="logMessage"></param>
        /// <param name="localLogFilePath"></param>
        /// <remarks>Used to log errors and warnings when the standard log file (or database) cannot be written to</remarks>
        protected static void LogLocalMessage(LogMessage logMessage, string localLogFilePath = "FileLoggerErrors.txt")
        {
            switch (logMessage.LogLevel)
            {
            case LogLevels.DEBUG:
                ConsoleMsgUtils.ShowDebug(logMessage.Message);
                break;

            case LogLevels.WARN:
                ConsoleMsgUtils.ShowWarning(logMessage.Message);
                break;

            case LogLevels.ERROR:
            case LogLevels.FATAL:
                ConsoleMsgUtils.ShowError(logMessage.Message);
                break;

            default:
                Console.WriteLine(logMessage.Message);
                break;
            }

            if (string.IsNullOrWhiteSpace(localLogFilePath))
            {
                localLogFilePath = "FileLoggerErrors.txt";
            }

            try
            {
                var localLogFile = new FileInfo(localLogFilePath);
                localLogFilePath = localLogFile.FullName;

                using (var localLogWriter = new StreamWriter(new FileStream(localLogFile.FullName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
                {
                    localLogWriter.WriteLine(logMessage.GetFormattedMessage(TimestampFormat));
                }
            }
            catch (Exception ex)
            {
                if (!mLocalLogFileAccessError)
                {
                    mLocalLogFileAccessError = true;
                    ConsoleMsgUtils.ShowError("Error writing to the local log file: " + localLogFilePath);
                }

                ConsoleMsgUtils.ShowErrorCustom(
                    string.Format("Error writing '{0}' to the local log file: {1}", logMessage.GetFormattedMessage(TimestampFormat), ex),
                    false,
                    false);
            }
        }
Beispiel #27
0
        /// <summary>
        /// Look for the mzML CacheInfo file
        /// If it exists, determine the path of the .mzML.gz file that it points to and verify that the file exists
        /// </summary>
        /// <param name="baseOutputFilePath"></param>
        /// <param name="cachedMzMLFile"></param>
        /// <param name="cacheInfoFileName"></param>
        /// <returns>True if the CacheInfo file was found and the .mzML.gz file was successfully retrieved; otherwise false</returns>
        private bool ResolveCachedMzMLFile(string baseOutputFilePath, out FileInfo cachedMzMLFile, out string cacheInfoFileName)
        {
            cacheInfoFileName = baseOutputFilePath + ".mzML.gz_CacheInfo.txt";

            try
            {
                var cacheInfoFile = new FileInfo(cacheInfoFileName);
                if (!cacheInfoFile.Exists)
                {
                    cachedMzMLFile = null;
                    return(false);
                }

                string cachedMzMLFilePath;

                using (var reader = new StreamReader(new FileStream(cacheInfoFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
                {
                    if (reader.EndOfStream)
                    {
                        cachedMzMLFilePath = string.Empty;
                    }
                    else
                    {
                        cachedMzMLFilePath = reader.ReadLine();
                    }
                }

                if (string.IsNullOrWhiteSpace(cachedMzMLFilePath))
                {
                    cachedMzMLFile = null;
                    return(false);
                }

                cachedMzMLFile = new FileInfo(cachedMzMLFilePath);
                if (cachedMzMLFile.Exists)
                {
                    return(true);
                }

                ConsoleMsgUtils.ShowWarning("Cached .mzML.gz file specified by {0} not found;\n" +
                                            "Cannot use: {1}", cacheInfoFile.Name, cachedMzMLFilePath);
                cachedMzMLFile = null;
                return(false);
            }
            catch (Exception ex)
            {
                ConsoleMsgUtils.ShowError("Error looking for the fixed mzML file using the CacheInfo file", ex);
                cachedMzMLFile = null;
                return(false);
            }
        }
Beispiel #28
0
        /// <summary>
        /// Display a warning message at the console and write to the log file
        /// </summary>
        /// <param name="warningMessage">Warning message</param>
        /// <param name="logToDatabase">When true, log to the database (and to the file)</param>
        public static void LogWarning(string warningMessage, bool logToDatabase = false)
        {
            ConsoleMsgUtils.ShowWarning(warningMessage);

            try
            {
                var logType = logToDatabase ? LoggerTypes.LogDb : LoggerTypes.LogFile;
                WriteLog(logType, BaseLogger.LogLevels.WARN, warningMessage);
            }
            catch (Exception ex)
            {
                ErrorWritingToLog(warningMessage, ex);
            }
        }
Beispiel #29
0
        public void TestWrapParagraph(string textToWrap, int wrapWidth, int spaceIndentCount, int expectedLineCount, int expectedCharacterCount)
        {
            if (spaceIndentCount > 0)
            {
                // Indent all of the wrapped lines by the given amount
                textToWrap = new string(' ', spaceIndentCount) + textToWrap;
            }

            var wrappedText = ConsoleMsgUtils.WrapParagraph(textToWrap, wrapWidth);

            Console.WriteLine(wrappedText);

            var wrappedLines = wrappedText.Split('\n');

            var charCount = 0;
            var lineCount = 0;

            foreach (var textLine in wrappedLines)
            {
                charCount += textLine.Length;
                lineCount++;
            }

            Console.WriteLine();
            Console.WriteLine("Wrapping to {0} characters per line gives {1} lines of wrapped text and {2} total characters", wrapWidth, lineCount, charCount);
            if (spaceIndentCount > 0)
            {
                Console.WriteLine("Indented text by {0} characters", spaceIndentCount);
            }

            if (expectedLineCount > 0)
            {
                Assert.AreEqual(expectedLineCount, lineCount,
                                "Text wrapped to {0} lines instead of {1} lines", lineCount, expectedLineCount);
            }
            else
            {
                Console.WriteLine("Skipped line count validation");
            }

            if (expectedCharacterCount > 0)
            {
                Assert.AreEqual(expectedCharacterCount, charCount,
                                "Wrapped text has {0} characters instead of {1} characters", charCount, expectedCharacterCount);
            }
            else
            {
                Console.WriteLine("Skipped character count validation");
            }
        }
Beispiel #30
0
        public void TestSleep(int waitTimeSeconds)
        {
            var startTime = DateTime.UtcNow;

            Console.WriteLine("Sleeping for {0} seconds", waitTimeSeconds);

            ConsoleMsgUtils.SleepSeconds(waitTimeSeconds);

            var elapsedSeconds = DateTime.UtcNow.Subtract(startTime).TotalSeconds;

            Console.WriteLine("Done after {0:F3} seconds", elapsedSeconds);

            Assert.AreEqual(0, Math.Abs(elapsedSeconds - waitTimeSeconds), 0.1, "Did not sleep as long as expected");
        }