Exemplo n.º 1
0
        public override void PerformLongExport(Action<IProgressMonitor> performExport)
        {
            if (!ShowMessages)
            {
                performExport(new SilentProgressMonitor());
                return;
            }

            using (var longWait = new LongWaitDlg
                    {
                        Text = Resources.ExportDlgProperties_PerformLongExport_Exporting_Methods
                    })
            {
                try
                {
                    var status = longWait.PerformWork(_dialog, 800, performExport);
                    if (status.IsError)
                        MessageDlg.ShowException(_dialog, status.ErrorException);
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(_dialog, TextUtil.LineSeparate(Resources.ExportDlgProperties_PerformLongExport_An_error_occurred_attempting_to_export,
                                                                   x.Message), x);
                }
            }
        }
Exemplo n.º 2
0
        protected override void DoTest()
        {
            // Test non-cancellable dialog.
            using (var longWaitDlg = new LongWaitDlg(null, false))
            {
                longWaitDlg.PerformWork(Program.MainWindow, 20, () =>
                {
                    for (int i = 0; i < 100; i += 10)
                    {
                        Thread.Sleep(5);
                        longWaitDlg.ProgressValue = i;
                    }
                });
            }

            // Show cancellable dialog if we're running this Form from SkylineTester.
            if (Program.PauseForms != null && Program.PauseForms.Contains(typeof(LongWaitDlg).Name))
            {
                using (var longWaitDlg = new LongWaitDlg())
                {
                    longWaitDlg.PerformWork(Program.MainWindow, 0, () =>
                    {
                        WaitForOpenForm<LongWaitDlg>();
                        longWaitDlg.CancelButton.PerformClick();
                    });
                    Assert.IsTrue(longWaitDlg.IsCanceled);
                }
            }
        }
Exemplo n.º 3
0
        public void ImportFasta(TextReader reader, long lineCount, bool peptideList, string description)
        {
            SrmTreeNode nodePaste = SequenceTree.SelectedNode as SrmTreeNode;
            IdentityPath selectPath = null;
            var to = nodePaste != null ? nodePaste.Path : null;

            var docCurrent = DocumentUI;

            ModificationMatcher matcher = null;
            if(peptideList)
            {
                matcher = new ModificationMatcher();
                List<string> sequences = new List<string>();
                string line;
                var header = reader.ReadLine(); // Read past header
                while ((line = reader.ReadLine()) != null)
                {
                    string sequence = FastaSequence.NormalizeNTerminalMod(line.Trim());
                    sequences.Add(sequence);
                }
                try
                {
                    matcher.CreateMatches(docCurrent.Settings, sequences, Settings.Default.StaticModList, Settings.Default.HeavyModList);
                    var strNameMatches = matcher.FoundMatches;
                    if (!string.IsNullOrEmpty(strNameMatches))
                    {
                        var message = TextUtil.LineSeparate(Resources.SkylineWindow_ImportFasta_Would_you_like_to_use_the_Unimod_definitions_for_the_following_modifications,
                                                            string.Empty, strNameMatches);
                        if (DialogResult.Cancel == MultiButtonMsgDlg.Show(
                            this,
                            string.Format(message), Resources.SkylineWindow_ImportFasta_OK))
                        {
                            return;
                        }
                    }
                }
                catch(FormatException x)
                {
                    MessageDlg.ShowException(this, x);
                    return;
                }
                reader = new StringReader(TextUtil.LineSeparate(header, TextUtil.LineSeparate(sequences.ToArray())));
            }

            SrmDocument docNew = null;
            int emptyPeptideGroups = 0;
            using (var longWaitDlg = new LongWaitDlg(this) { Text = description })
            {
                IdentityPath nextAdded;
                longWaitDlg.PerformWork(this, 1000, longWaitBroker =>
                    docNew = docCurrent.ImportFasta(reader, longWaitBroker, lineCount, matcher, to, out selectPath, out nextAdded, out emptyPeptideGroups));

                if (docNew == null)
                    return;

                if (longWaitDlg.IsDocumentChanged(docCurrent))
                {
                    MessageDlg.Show(this, Resources.SkylineWindow_ImportFasta_Unexpected_document_change_during_operation);
                    return;
                }
            }

            // If importing the FASTA produced any childless proteins
            docNew = ImportFastaHelper.HandleEmptyPeptideGroups(this, emptyPeptideGroups, docNew);
            if (docNew == null || Equals(docCurrent, docNew))
                return;

            selectPath = null;
            var enumGroupsCurrent = docCurrent.MoleculeGroups.GetEnumerator();
            foreach (PeptideGroupDocNode nodePepGroup in docNew.MoleculeGroups)
            {
                if (enumGroupsCurrent.MoveNext() &&
                    !ReferenceEquals(nodePepGroup, enumGroupsCurrent.Current))
                {
                    selectPath = new IdentityPath(nodePepGroup.Id);
                    break;
                }
            }

            ModifyDocument(description, doc =>
            {
                if (!ReferenceEquals(doc, docCurrent))
                    throw new InvalidDataException(Resources.SkylineWindow_ImportFasta_Unexpected_document_change_during_operation);
                if (matcher != null)
                {
                    var pepModsNew = matcher.GetDocModifications(docNew);
                    docNew = docNew.ChangeSettings(docNew.Settings.ChangePeptideModifications(mods => pepModsNew));
                    docNew.Settings.UpdateDefaultModifications(false);
                }
                return docNew;
            });

            if (selectPath != null)
                SequenceTree.SelectedPath = selectPath;
        }
Exemplo n.º 4
0
        public void ApplyPeak(bool subsequent)
        {
            var nodePepTree = SequenceTree.GetNodeOfType<PeptideTreeNode>();
            var nodeTranGroupTree = SequenceTree.GetNodeOfType<TransitionGroupTreeNode>();
            var nodeTranGroup = nodeTranGroupTree != null ? nodeTranGroupTree.DocNode : null;

            using (var longWait = new LongWaitDlg(this) { Text = Resources.SkylineWindow_ApplyPeak_Applying_Peak })
            {
                SrmDocument doc = null;
                try
                {
                    var resultsIndex = SelectedResultsIndex;
                    var resultsFile = _listGraphChrom[resultsIndex].SelectedFileIndex;
                    longWait.PerformWork(this, 800, monitor => doc = PeakMatcher.ApplyPeak(Document, nodePepTree, nodeTranGroup, resultsIndex, resultsFile, subsequent, monitor));
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(this, TextUtil.LineSeparate(Resources.SkylineWindow_ApplyPeak_Failed_to_apply_peak_, x.Message), x);
                }

                if (!longWait.IsCanceled && doc != null && !ReferenceEquals(doc, Document))
                {
                    ModifyDocument(Resources.SkylineWindow_PickPeakInChromatograms_Apply_picked_peak, document => doc);
                }
            }
        }
Exemplo n.º 5
0
 private bool GetR()
 {
     try
     {
         using (var dlg = new LongWaitDlg {Message = Resources.RInstaller_InstallR_Downloading_R, ProgressValue = 0})
         {
             // Short wait, because this can't possible happen fast enough to avoid
             // showing progress, except in testing
             dlg.PerformWork(this, 50, DownloadR);
         }
         using (var dlg = new LongWaitDlg(null, false) {Message = Resources.RInstaller_GetR_Installing_R})
         {
             dlg.PerformWork(this, 50, InstallR);
         }
         MessageDlg.Show(this, Resources.RInstaller_GetR_R_installation_complete_);
     }
     catch (TargetInvocationException ex)
     {
         if (ex.InnerException.GetType() == typeof (ToolExecutionException))
         {
             MessageDlg.ShowException(this, ex);
             return false;
         }
         throw;
     }
     return true;
 }
Exemplo n.º 6
0
        public bool WriteChromatograms(string filePath)
        {
            var fileNames = (from object fileName in checkedListVars.CheckedItems select fileName.ToString()).ToList();

            using (var longWaitDlg = new LongWaitDlg
            {
                Text = Resources.ExportChromatogramDlg_OkDialog_Exporting_Chromatograms,
            })
            {
                try
                {
                    longWaitDlg.PerformWork(this, 1000,
                                            broker => WriteChromatograms(filePath,
                                                                         broker,
                                                                         fileNames,
                                                                         LocalizationHelper.CurrentCulture,
                                                                         _chromExtractors,
                                                                         _chromSources));
                    if (longWaitDlg.IsCanceled)
                        return false;
                }
                catch (Exception x)
                {
                    var message = TextUtil.LineSeparate(string.Format(Resources.ExportChromatogramDlg_OkDialog_Failed_attempting_to_save_chromatograms_to__0__, filePath),
                                                        x.Message);
                    MessageDlg.ShowWithException(this, message, x);
                }
            }
            return true;
        }
        private void RefreshStatus()
        {
            if (File.Exists(textPath.Text))
            {
                btnAddFastaFile.Enabled = true;
                ProteomeDb proteomeDb = null;
                try
                {
                    using (var longWaitDlg = new LongWaitDlg
                    {
                        Text = Resources.BuildBackgroundProteomeDlg_RefreshStatus_Loading_Proteome_File,
                        Message =
                            string.Format(
                                Resources.BuildBackgroundProteomeDlg_RefreshStatus_Loading_protein_information_from__0__,
                                textPath.Text)
                    })
                    {
                        longWaitDlg.PerformWork(this, 1000, () => proteomeDb = ProteomeDb.OpenProteomeDb(textPath.Text));
                    }
                    if (proteomeDb == null)
                        throw new Exception();

                    int proteinCount = proteomeDb.GetProteinCount();
                    var digestions = proteomeDb.ListDigestions();
                    tbxStatus.Text =
                        string.Format(
                            Resources.BuildBackgroundProteomeDlg_RefreshStatus_The_proteome_file_contains__0__proteins,
                            proteinCount);
                    if (proteinCount != 0 && digestions.Count > 0)
                    {
                        tbxStatus.Text = TextUtil.LineSeparate(tbxStatus.Text,
                            Resources.BuildBackgroundProteomeDlg_RefreshStatus_The_proteome_has_already_been_digested);
                    }
                }
                catch (Exception)
                {
                    tbxStatus.Text = Resources.BuildBackgroundProteomeDlg_OkDialog_The_proteome_file_is_not_valid;
                    btnAddFastaFile.Enabled = false;
                }
                finally
                {
                    if (null != proteomeDb)
                    {
                        proteomeDb.Dispose();
                    }
                }
            }
            else
            {
                btnAddFastaFile.Enabled = false;
                tbxStatus.Text = Resources.BuildBackgroundProteomeDlg_RefreshStatus_Click_the_Open_button_to_choose_an_existing_proteome_file_or_click_the_Create_button_to_create_a_new_proteome_file;
            }
        }
Exemplo n.º 8
0
        public bool UpdateResultsFiles(IEnumerable<string> dirPaths, bool overwrite)
        {
            using (var longWaitDlg = new LongWaitDlg
                {
                    Text = Resources.ImportResultsControl_FindResultsFiles_Searching_for_Results_Files
                })
            {
                try
                {
                    longWaitDlg.PerformWork(WizardForm, 1000, longWaitBroker =>
                        ImportPeptideSearch.UpdateSpectrumSourceFilesFromDirs(dirPaths, overwrite, longWaitBroker));
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(WizardForm, TextUtil.LineSeparate(
                        Resources.ImportResultsControl_FindResultsFiles_An_error_occurred_attempting_to_find_results_files_,
                        x.Message), x);
                }
            }

            UpdateResultsFilesUI();

            return !MissingResultsFiles.Any();
        }
Exemplo n.º 9
0
 public bool ShareDocument(string fileDest, bool completeSharing)
 {
     try
     {
         bool success = false;
         Helpers.TryTwice(() =>
         {
             using (var longWaitDlg = new LongWaitDlg { Text = Resources.SkylineWindow_ShareDocument_Compressing_Files, })
             {
                 var sharing = new SrmDocumentSharing(DocumentUI, DocumentFilePath, fileDest,  completeSharing);
                 longWaitDlg.PerformWork(this, 1000, sharing.Share);
                 success = !longWaitDlg.IsCanceled;
             }
         });
         return success;
     }
     catch (Exception x)
     {
         var message = TextUtil.LineSeparate(string.Format(Resources.SkylineWindow_ShareDocument_Failed_attempting_to_create_sharing_file__0__, fileDest),
                                             x.Message);
         MessageDlg.ShowWithException(this, message, x);
     }
     return false;
 }
Exemplo n.º 10
0
        public bool SaveDocument(String fileName, bool includingCacheFile = true)
        {
            if (string.IsNullOrEmpty(DocumentUI.Settings.DataSettings.DocumentGuid) ||
                !Equals(DocumentFilePath, fileName))
            {
                SrmDocument docOriginal;
                SrmDocument docNew;
                do
                {
                    docOriginal = Document;
                    docNew =
                        docOriginal.ChangeSettings(
                            docOriginal.Settings.ChangeDataSettings(
                                docOriginal.Settings.DataSettings.ChangeDocumentGuid()));
                } while (!SetDocument(docNew, docOriginal));
            }

            SrmDocument document = Document;

            try
            {
                using (var saver = new FileSaver(fileName))
                {
                    saver.CheckException();

                    using (var longWaitDlg = new LongWaitDlg(this)
                        {
                            Text = Resources.SkylineWindow_SaveDocument_Saving___,
                            Message = Path.GetFileName(fileName)
                        })
                    {
                        longWaitDlg.PerformWork(this, 800, progressMonitor =>
                        {
                            using (var writer = new XmlWriterWithProgress(saver.SafeName, fileName, Encoding.UTF8,
                                document.MoleculeTransitionCount, progressMonitor)
                            {
                                Formatting = Formatting.Indented
                            })
                            {
                                XmlSerializer ser = new XmlSerializer(typeof(SrmDocument));
                                ser.Serialize(writer, document);

                                writer.Flush();
                                writer.Close();

                                // If the user has chosen "Save As", and the document has a
                                // document specific spectral library, copy this library to
                                // the new name.
                                if (!Equals(DocumentFilePath, fileName))
                                    SaveDocumentLibraryAs(fileName);

                                saver.Commit();
                            }
                        });

                        // Sometimes this catches a cancellation that doesn't throw an OperationCanceledException.
                        if (longWaitDlg.IsCanceled)
                            return false;
                    }
                }
            }
            catch (OperationCanceledException)
            {
                return false;
            }
            catch (Exception ex)
            {
                var message = TextUtil.LineSeparate(string.Format(Resources.SkylineWindow_SaveDocument_Failed_writing_to__0__, fileName), ex.Message);
                MessageBox.Show(message);
                return false;
            }

            DocumentFilePath = fileName;
            _savedVersion = document.UserRevisionIndex;
            SetActiveFile(fileName);

            // Make sure settings lists contain correct values for this document.
            document.Settings.UpdateLists(DocumentFilePath);

            try
            {
                SaveLayout(fileName);

                // CONSIDER: Is this really optional?
                if (includingCacheFile)
                {
                    using (var longWaitDlg = new LongWaitDlg(this)
                    {
                        Text = Resources.SkylineWindow_SaveDocument_Optimizing_data_file___,
                        Message = Path.GetFileName(fileName)
                    })
                    {
                        longWaitDlg.PerformWork(this, 800, () =>
                            OptimizeCache(fileName, longWaitDlg));
                    }
                }
            }

            // We allow silent failures because it is OK for the cache to remain unoptimized
            // or the layout to not be saved.  These aren't critical as long as the document
            // was saved correctly.
            catch (UnauthorizedAccessException) {}
            catch (IOException) {}
            catch (OperationCanceledException) {}
            catch (TargetInvocationException) {}

            return true;
        }
Exemplo n.º 11
0
        public bool OpenSharedFile(string zipPath)
        {
            try
            {
                var sharing = new SrmDocumentSharing(zipPath);

                using (var longWaitDlg = new LongWaitDlg
                {
                    Text = Resources.SkylineWindow_OpenSharedFile_Extracting_Files,
                })
                {
                    longWaitDlg.PerformWork(this, 1000, sharing.Extract);
                    if (longWaitDlg.IsCanceled)
                        return false;
                }

                // Remember the directory containing the newly extracted file
                // as the active directory for the next open command.
                Settings.Default.ActiveDirectory = Path.GetDirectoryName(sharing.DocumentPath);

                return OpenFile(sharing.DocumentPath);
            }
            catch (ZipException zipException)
            {
                MessageDlg.ShowWithException(this, string.Format(Resources.SkylineWindow_OpenSharedFile_The_zip_file__0__cannot_be_read,
                                                    zipPath), zipException);
                return false;
            }
            catch (Exception e)
            {
                var message = TextUtil.LineSeparate(string.Format(
                        Resources.SkylineWindow_OpenSharedFile_Failure_extracting_Skyline_document_from_zip_file__0__,
                        zipPath), e.Message);
                MessageDlg.ShowWithException(this, message, e);
                return false;
            }
        }
Exemplo n.º 12
0
        public bool OpenFile(string path, FormEx parentWindow = null)
        {
            // Remove any extraneous temporary chromatogram spill files.
            var spillDirectory = Path.Combine(Path.GetDirectoryName(path) ?? "", "xic");    // Not L10N
            if (Directory.Exists(spillDirectory))
                DirectoryEx.SafeDelete(spillDirectory);

            Exception exception = null;
            SrmDocument document = null;

            try
            {
                using (var longWaitDlg = new LongWaitDlg(this)
                {
                    Text = Resources.SkylineWindow_OpenFile_Loading___,
                    Message = Path.GetFileName(path),
                    ProgressValue = 0
                })
                {
                    longWaitDlg.PerformWork(parentWindow ?? this, 500, progressMonitor =>
                    {
                        using (var reader = new StreamReaderWithProgress(path, progressMonitor))
                        {
                            XmlSerializer ser = new XmlSerializer(typeof (SrmDocument));
                            document = (SrmDocument) ser.Deserialize(reader);
                        }
                    });

                    if (longWaitDlg.IsCanceled)
                        document = null;
                }
            }
            catch (Exception x)
            {
                exception = x;
            }

            if (exception == null)
            {
                if (document == null)
                    return false;

                try
                {
                    document = ConnectDocument(parentWindow ?? this, document, path);
                    if (document == null || !CheckResults(document, path))
                        return false;

                    // Make sure settings lists contain correct values for
                    // this document.
                    document.Settings.UpdateLists(path);
                }
                catch (Exception x)
                {
                    exception = x;
                }
            }

            if (exception == null)
            {
                try
                {
                    using (new SequenceTreeForm.LockDoc(_sequenceTreeForm))
                    {
                        // Switch over to the opened document
                        SwitchDocument(document, path);
                    }
                    // Locking the sequenceTree can throw off the node count status
                    UpdateNodeCountStatus();
                }
                catch (Exception x)
                {
                    exception = x;
                }
            }

            if (exception != null)
            {
                new MessageBoxHelper(parentWindow ?? this).ShowXmlParsingError(
                    string.Format(Resources.SkylineWindow_OpenFile_Failure_opening__0__, path), path, exception);
                return false;
            }

            if (SequenceTree != null && SequenceTree.Nodes.Count > 0 && !SequenceTree.RestoredFromPersistentString)
                SequenceTree.SelectedNode = SequenceTree.Nodes[0];

            return true;
        }
Exemplo n.º 13
0
        public void ImportFiles(params string[] filePaths)
        {
            var resultsAction = MeasuredResults.MergeAction.remove;
            var mergePeptides = false;
            if (HasResults(filePaths))
            {
                using (var dlgResults = new ImportDocResultsDlg(!string.IsNullOrEmpty(DocumentFilePath)))
                {
                    if (dlgResults.ShowDialog(this) != DialogResult.OK)
                        return;
                    resultsAction = dlgResults.Action;
                    mergePeptides = dlgResults.IsMergePeptides;
                }
            }
            SrmTreeNode nodeSel = SequenceTree.SelectedNode as SrmTreeNode;
            IdentityPath selectPath = null;

            var docCurrent = DocumentUI;
            SrmDocument docNew = null;
            using (var longWaitDlg = new LongWaitDlg(this)
                {
                    Text = Resources.SkylineWindow_ImportFiles_Import_Skyline_document_data,
                })
            {
                longWaitDlg.PerformWork(this, 1000, longWaitBroker =>
                    docNew = ImportFiles(docCurrent,
                                         longWaitBroker,
                                         filePaths,
                                         resultsAction,
                                         mergePeptides,
                                         nodeSel != null ? nodeSel.Path : null,
                                         out selectPath));

                if (docNew == null || ReferenceEquals(docNew, docCurrent))
                    return;

                if (longWaitDlg.IsDocumentChanged(docCurrent))
                {
                    MessageDlg.Show(this, Resources.SkylineWindow_ImportFasta_Unexpected_document_change_during_operation);
                    return;
                }
            }

            ModifyDocument(Resources.SkylineWindow_ImportFiles_Import_Skyline_document_data, doc =>
            {
                docNew.ValidateResults();
                if (!ReferenceEquals(doc, docCurrent))
                    throw new InvalidDataException(Resources.SkylineWindow_ImportFasta_Unexpected_document_change_during_operation);
                return docNew;
            });

            if (selectPath != null)
                SequenceTree.SelectedPath = selectPath;
        }
Exemplo n.º 14
0
        private void ImportPeakBoundaries(string fileName, long lineCount, string description)
        {
            var docCurrent = DocumentUI;
            SrmDocument docNew = null;
            using (var longWaitDlg = new LongWaitDlg(this) { Text = description })
            {
                var peakBoundaryImporter = new PeakBoundaryImporter(docCurrent);
                longWaitDlg.PerformWork(this, 1000, longWaitBroker =>
                           docNew = peakBoundaryImporter.Import(fileName, longWaitBroker, lineCount));

                if (docNew == null)
                    return;
                if (!peakBoundaryImporter.UnrecognizedPeptidesCancel(this))
                    return;
                if (longWaitDlg.IsDocumentChanged(docCurrent))
                {
                    MessageDlg.Show(this, Resources.SkylineWindow_ImportPeakBoundaries_Unexpected_document_change_during_operation);
                    return;
                }
            }

            ModifyDocument(description, doc =>
            {
                if (!ReferenceEquals(doc, docCurrent))
                    throw new InvalidDataException(Resources.SkylineWindow_ImportPeakBoundaries_Unexpected_document_change_during_operation);
                return docNew;
            });
        }
Exemplo n.º 15
0
        private void ImportMassList(MassListInputs inputs, string description)
        {
            SrmTreeNode nodePaste = SequenceTree.SelectedNode as SrmTreeNode;
            IdentityPath insertPath = nodePaste != null ? nodePaste.Path : null;
            IdentityPath selectPath = null;
            List<MeasuredRetentionTime> irtPeptides = null;
            List<SpectrumMzInfo> librarySpectra = null;
            List<TransitionImportErrorInfo> errorList = null;
            List<PeptideGroupDocNode> peptideGroups = null;
            RetentionTimeRegression retentionTimeRegressionStore = null;
            var docCurrent = DocumentUI;
            SrmDocument docNew = null;
            var retentionTimeRegression = docCurrent.Settings.PeptideSettings.Prediction.RetentionTime;
            RCalcIrt calcIrt = retentionTimeRegression != null ? (retentionTimeRegression.Calculator as RCalcIrt) : null;
            using (var longWaitDlg = new LongWaitDlg(this) {Text = description})
            {
                longWaitDlg.PerformWork(this, 1000, longWaitBroker =>
                {
                    docNew = docCurrent.ImportMassList(inputs, longWaitBroker,
                        insertPath, out selectPath, out irtPeptides, out librarySpectra, out errorList, out peptideGroups);
                });
            }
            bool isDocumentSame = ReferenceEquals(docNew, docCurrent);
            // If nothing was imported (e.g. operation was canceled or zero error-free transitions) and also no errors, just return
            if (isDocumentSame && !errorList.Any())
                return;
            // Show the errors, giving the option to accept the transitions without errors,
            // if there are any
            if (errorList.Any())
            {
                using (var errorDlg = new ImportTransitionListErrorDlg(errorList, isDocumentSame))
                {
                    if (errorDlg.ShowDialog(this) == DialogResult.Cancel || isDocumentSame)
                    {
                        return;
                    }
                }
            }

            var dbIrtPeptides = irtPeptides.Select(rt => new DbIrtPeptide(rt.PeptideSequence, rt.RetentionTime, false, TimeSource.scan)).ToList();
            var dbIrtPeptidesFilter = ImportAssayLibraryHelper.GetUnscoredIrtPeptides(dbIrtPeptides, calcIrt);
            bool overwriteExisting = false;
            MassListInputs irtInputs = null;
            // If there are no iRT peptides or none with different values than the database, don't import any iRT's
            if (dbIrtPeptidesFilter.Any())
            {
                // Ask whether or not to include iRT peptides in the paste
                string useIrtMessage = calcIrt == null
                    ? Resources.SkylineWindow_ImportMassList_The_transition_list_appears_to_contain_iRT_values__but_the_document_does_not_have_an_iRT_calculator___Create_a_new_calculator_and_add_these_iRT_values_
                    : Resources.SkylineWindow_ImportMassList_The_transition_list_appears_to_contain_iRT_library_values___Add_these_iRT_values_to_the_iRT_calculator_;
                string yesButton = calcIrt == null
                    ? Resources.SkylineWindow_ImportMassList__Create___
                    : Resources.SkylineWindow_ImportMassList_Add;
                var useIrtResult = MultiButtonMsgDlg.Show(this, useIrtMessage,
                    yesButton, Resources.SkylineWindow_ImportMassList__Skip, true);
                if (useIrtResult == DialogResult.Cancel)
                {
                    return;
                }
                if (useIrtResult == DialogResult.Yes)
                {
                    if (calcIrt == null)
                    {
                        // If there is no iRT calculator, ask the user to create one
                        using (var dlg = new CreateIrtCalculatorDlg(docNew, DocumentFilePath, Settings.Default.RTScoreCalculatorList, peptideGroups))
                        {
                            if (dlg.ShowDialog(this) != DialogResult.OK)
                            {
                                return;
                            }

                            docNew = dlg.Document;
                            calcIrt = (RCalcIrt)docNew.Settings.PeptideSettings.Prediction.RetentionTime.Calculator;
                            dlg.UpdateLists(librarySpectra, dbIrtPeptidesFilter);
                            if (!string.IsNullOrEmpty(dlg.IrtFile))
                                irtInputs = new MassListInputs(dlg.IrtFile);
                        }
                    }
                    string dbPath = calcIrt.DatabasePath;
                    IrtDb db = File.Exists(dbPath) ? IrtDb.GetIrtDb(dbPath, null) : IrtDb.CreateIrtDb(dbPath);
                    var oldPeptides = db.GetPeptides().ToList();
                    IList<DbIrtPeptide.Conflict> conflicts;
                    dbIrtPeptidesFilter = DbIrtPeptide.MakeUnique(dbIrtPeptidesFilter);
                    DbIrtPeptide.FindNonConflicts(oldPeptides, dbIrtPeptidesFilter, null, out conflicts);
                    // Ask whether to keep or overwrite peptides that are present in the import and already in the database
                    if (conflicts.Any())
                    {
                        string messageOverwrite = string.Format(Resources.SkylineWindow_ImportMassList_The_iRT_calculator_already_contains__0__of_the_imported_peptides_,
                                                                conflicts.Count);
                        var overwriteResult = MultiButtonMsgDlg.Show(this,
                            TextUtil.LineSeparate(messageOverwrite, conflicts.Count == 1
                                ? Resources.SkylineWindow_ImportMassList_Keep_the_existing_iRT_value_or_overwrite_with_the_imported_value_
                                : Resources.SkylineWindow_ImportMassList_Keep_the_existing_iRT_values_or_overwrite_with_imported_values_),
                            Resources.SkylineWindow_ImportMassList__Keep, Resources.SkylineWindow_ImportMassList__Overwrite, true);
                        if (overwriteResult == DialogResult.Cancel)
                        {
                            return;
                        }
                        overwriteExisting = overwriteResult == DialogResult.No;
                    }
                    using (var longWaitDlg = new LongWaitDlg(this) { Text = Resources.SkylineWindow_ImportMassList_Adding_iRT_values_})
                    {
                        longWaitDlg.PerformWork(this, 100, progressMonitor =>
                            docNew = docNew.AddIrtPeptides(dbIrtPeptidesFilter, overwriteExisting, progressMonitor));
                    }
                    if (docNew == null)
                        return;
                    retentionTimeRegressionStore = docNew.Settings.PeptideSettings.Prediction.RetentionTime;
                }
            }
            BiblioSpecLiteSpec docLibrarySpec = null;
            BiblioSpecLiteLibrary docLibrary = null;
            int indexOldLibrary = -1;
            if (librarySpectra.Any())
            {
                string addLibraryMessage = Resources.SkylineWindow_ImportMassList_The_transition_list_appears_to_contain_spectral_library_intensities___Create_a_document_library_from_these_intensities_;
                var addLibraryResult = MultiButtonMsgDlg.Show(this, addLibraryMessage,
                    Resources.SkylineWindow_ImportMassList__Create___, Resources.SkylineWindow_ImportMassList__Skip,
                    true);
                if (addLibraryResult == DialogResult.Cancel)
                {
                    return;
                }
                if (addLibraryResult == DialogResult.Yes)
                {
                    // Can't name a library after the document if the document is unsaved
                    // In this case, prompt to save
                    if (DocumentFilePath == null)
                    {
                        string saveDocumentMessage = Resources.SkylineWindow_ImportMassList_You_must_save_the_Skyline_document_in_order_to_create_a_spectral_library_from_a_transition_list_;
                        var saveDocumentResult = MultiButtonMsgDlg.Show(this, saveDocumentMessage, MultiButtonMsgDlg.BUTTON_OK);
                        if (saveDocumentResult == DialogResult.Cancel)
                        {
                            return;
                        }
                        else if (!SaveDocumentAs())
                        {
                            return;
                        }
                    }

                    librarySpectra = SpectrumMzInfo.RemoveDuplicateSpectra(librarySpectra);

                    string documentLibrary = BiblioSpecLiteSpec.GetLibraryFileName(DocumentFilePath);
            // ReSharper disable once AssignNullToNotNullAttribute
                    string outputPath = Path.Combine(Path.GetDirectoryName(documentLibrary),
                                                     Path.GetFileNameWithoutExtension(documentLibrary) + BiblioSpecLiteSpec.ASSAY_NAME + BiblioSpecLiteSpec.EXT);
                    bool libraryExists = File.Exists(outputPath);
                    string name = Path.GetFileNameWithoutExtension(DocumentFilePath) + BiblioSpecLiteSpec.ASSAY_NAME;
                    indexOldLibrary = docNew.Settings.PeptideSettings.Libraries.LibrarySpecs.IndexOf(spec => spec != null && spec.FilePath == outputPath);
                    bool libraryLinkedToDoc = indexOldLibrary != -1;
                    if (libraryLinkedToDoc)
                    {
                        string oldName = docNew.Settings.PeptideSettings.Libraries.LibrarySpecs[indexOldLibrary].Name;
                        var libraryOld = docNew.Settings.PeptideSettings.Libraries.GetLibrary(oldName);
                        var additionalSpectra = SpectrumMzInfo.GetInfoFromLibrary(libraryOld);
                        additionalSpectra = SpectrumMzInfo.RemoveDuplicateSpectra(additionalSpectra);
                        librarySpectra = SpectrumMzInfo.MergeWithOverwrite(librarySpectra, additionalSpectra);
                        foreach (var stream in libraryOld.ReadStreams)
                            stream.CloseStream();
                    }
                    if (libraryExists && !libraryLinkedToDoc)
                    {
                        string replaceLibraryMessage = string.Format(Resources.SkylineWindow_ImportMassList_There_is_an_existing_library_with_the_same_name__0__as_the_document_library_to_be_created___Overwrite_this_library_or_skip_import_of_library_intensities_,
                                          name);
                        // If the document does not have an assay library linked to it, then ask if user wants to delete the one that we have found
                        var replaceLibraryResult = MultiButtonMsgDlg.Show(this, replaceLibraryMessage,
                            Resources.SkylineWindow_ImportMassList__Overwrite, Resources.SkylineWindow_ImportMassList__Skip, true);
                        if (replaceLibraryResult == DialogResult.Cancel)
                            return;
                        if (replaceLibraryResult == DialogResult.No)
                            librarySpectra.Clear();
                    }
                    if (librarySpectra.Any())
                    {
                        // Delete the existing library; either it's not tied to the document or we've already extracted the spectra
                        if (libraryExists)
                        {
                            FileEx.SafeDelete(outputPath);
                            FileEx.SafeDelete(Path.ChangeExtension(outputPath, BiblioSpecLiteSpec.EXT_REDUNDANT));
                        }
                        using (var blibDb = BlibDb.CreateBlibDb(outputPath))
                        {
                            docLibrarySpec = new BiblioSpecLiteSpec(name, outputPath);
                            using (var longWaitDlg = new LongWaitDlg(this) { Text = Resources.SkylineWindow_ImportMassList_Creating_Spectral_Library })
                            {
                                longWaitDlg.PerformWork(this, 1000, progressMonitor =>
                                {
                                    docLibrary = blibDb.CreateLibraryFromSpectra(docLibrarySpec, librarySpectra, name, progressMonitor);
                                    if (docLibrary == null)
                                        return;
                                    var newSettings = docNew.Settings.ChangePeptideLibraries(libs => libs.ChangeLibrary(docLibrary, docLibrarySpec, indexOldLibrary));
                                    var status = new ProgressStatus(Resources.SkylineWindow_ImportMassList_Finishing_up_import);
                                    progressMonitor.UpdateProgress(status);
                                    progressMonitor.UpdateProgress(status.ChangePercentComplete(100));
                                    docNew = docNew.ChangeSettings(newSettings);
                                });
                                if (docLibrary == null)
                                    return;
                            }
                        }
                    }
                }
            }

            ModifyDocument(description, doc =>
            {
                if (ReferenceEquals(doc, docCurrent))
                    return docNew;
                try
                {
                    // If the document was changed during the operation, try all the changes again
                    // using the information given by the user.
                    docCurrent = DocumentUI;
                    doc = doc.ImportMassList(inputs, insertPath, out selectPath);
                    if (irtInputs != null)
                    {
                        doc = doc.ImportMassList(irtInputs, null, out selectPath);
                    }
                    var newSettings = doc.Settings;
                    if (retentionTimeRegressionStore != null)
                    {
                        newSettings = newSettings.ChangePeptidePrediction(prediction =>
                            prediction.ChangeRetentionTime(retentionTimeRegressionStore));
                    }
                    if (docLibrarySpec != null)
                    {
                        newSettings = newSettings.ChangePeptideLibraries(libs =>
                            libs.ChangeLibrary(docLibrary, docLibrarySpec, indexOldLibrary));
                    }
                    if (!ReferenceEquals(doc.Settings, newSettings))
                        doc = doc.ChangeSettings(newSettings);
                }
                catch (Exception x)
                {
                    throw new InvalidDataException(string.Format(Resources.SkylineWindow_ImportMassList_Unexpected_document_change_during_operation___0_, x.Message, x));
                }
                return doc;
            });

            if (selectPath != null)
                SequenceTree.SelectedPath = selectPath;
            if (retentionTimeRegressionStore != null)
            {
                Settings.Default.RetentionTimeList.Add(retentionTimeRegressionStore);
                Settings.Default.RTScoreCalculatorList.Add(retentionTimeRegressionStore.Calculator);
            }
            if (docLibrarySpec != null)
            {
                Settings.Default.SpectralLibraryList.Insert(0, docLibrarySpec);
            }
        }
Exemplo n.º 16
0
        public static void Main(string[] args = null)
        {
            if (String.IsNullOrEmpty(Settings.Default.InstallationId)) // Each instance to have GUID
                Settings.Default.InstallationId = Guid.NewGuid().ToString();

            // don't allow 64-bit Skyline to run in a 32-bit process
            if (Install.Is64Bit && !Environment.Is64BitProcess)
            {
                string installUrl = Install.Url;
                string installLabel = (installUrl == string.Empty) ? string.Empty : string.Format(Resources.Program_Main_Install_32_bit__0__, Name);
                AlertLinkDlg.Show(null,
                    string.Format(Resources.Program_Main_You_are_attempting_to_run_a_64_bit_version_of__0__on_a_32_bit_OS_Please_install_the_32_bit_version, Name),
                    installLabel,
                    installUrl);
                return;
            }

            CommonFormEx.TestMode = FunctionalTest;
            CommonFormEx.Offscreen = SkylineOffscreen;
            CommonFormEx.ShowFormNames = FormEx.ShowFormNames = ShowFormNames;

            // For testing and debugging Skyline command-line interface
            if (args != null && args.Length > 0)
            {
                if (!CommandLineRunner.HasCommandPrefix(args[0]))
                {
                    var writer = new CommandStatusWriter(new DebugWriter());
                    if (args[0].Equals("--ui", StringComparison.InvariantCultureIgnoreCase)) // Not L10N
                    {
                        // ReSharper disable once ObjectCreationAsStatement
                        new CommandLineUI(args, writer);
                    }
                    else
                    {
                        CommandLineRunner.RunCommand(args, writer);
                    }
                }
                else
                {
                    // For testing SkylineRunner without installation
                    CommandLineRunner clr = new CommandLineRunner();
                    clr.Start(args[0]);
                }

                return;
            }
            // The way Skyline command-line interface is run for an installation
            else if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments != null &&
                AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData != null &&
                AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData.Length > 0 &&
                CommandLineRunner.HasCommandPrefix(AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0])) // Not L10N
            {
                CommandLineRunner clr = new CommandLineRunner();
                clr.Start(AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0]);

                // HACK: until the "invalid string binding" error is resolved, this will prevent an error dialog at exit
                Process.GetCurrentProcess().Kill();
                return;
            }

            try
            {
                Init();
                if (!string.IsNullOrEmpty(Settings.Default.DisplayLanguage))
                {
                    try
                    {
                        LocalizationHelper.CurrentUICulture =
                            CultureInfo.GetCultureInfo(Settings.Default.DisplayLanguage);
                    }
                    catch (CultureNotFoundException)
                    {
                    }
                }
                LocalizationHelper.InitThread(Thread.CurrentThread);

                // Make sure the user has agreed to the current license version
                // or one more recent.
                int licenseVersion = Settings.Default.LicenseVersionAccepted;
                if (licenseVersion < LICENSE_VERSION_CURRENT && !NoSaveSettings)
                {
                    // If the user has never used the application before, then
                    // they must have agreed to the current license agreement during
                    // installation.  Otherwise, make sure they agree to the new
                    // license agreement.
                    if (Install.Type == Install.InstallType.release &&
                            (licenseVersion != 0 || !Settings.Default.MainWindowSize.IsEmpty))
                    {
                        using (var dlg = new UpgradeDlg(licenseVersion))
                        {
                            if (dlg.ShowDialog() == DialogResult.Cancel)
                                return;
                        }
                    }

                    try
                    {
                        // Make sure the user never sees this again for this license version
                        Settings.Default.LicenseVersionAccepted = LICENSE_VERSION_CURRENT;
                        Settings.Default.Save();
                    }
            // ReSharper disable EmptyGeneralCatchClause
                    catch (Exception)
            // ReSharper restore EmptyGeneralCatchClause
                    {
                        // Just try to update the license version next time.
                    }
                }

                try
                {
                    // If this is a new installation copy over installed external tools from previous installation location.
                    var toolsDirectory = ToolDescriptionHelpers.GetToolsDirectory();
                    if (!Directory.Exists(toolsDirectory))
                    {
                        using (var longWaitDlg = new LongWaitDlg
                        {
                            Text = Name,
                            Message = Resources.Program_Main_Copying_external_tools_from_a_previous_installation,
                            ProgressValue = 0
                        })
                        {
                            longWaitDlg.PerformWork(null, 1000*3, broker => CopyOldTools(toolsDirectory, broker));
                        }
                    }
                }
                // ReSharper disable once EmptyGeneralCatchClause
                catch
                {

                }

                // Force live reports (though tests may reset this)
                //Settings.Default.EnableLiveReports = true;

                if (ReportShutdownDlg.HadUnexpectedShutdown())
                {
                    using (var reportShutdownDlg = new ReportShutdownDlg())
                    {
                        reportShutdownDlg.ShowDialog();
                    }
                }
                SystemEvents.DisplaySettingsChanged += SystemEventsOnDisplaySettingsChanged;
                // Careful, a throw out of the SkylineWindow constructor without this
                // catch causes Skyline just to appear to silently never start.  Makes for
                // some difficult debugging.
                try
                {
                    var activationArgs = AppDomain.CurrentDomain.SetupInformation.ActivationArguments;
                    if ((activationArgs != null &&
                        activationArgs.ActivationData != null &&
                        activationArgs.ActivationData.Length != 0) ||
                        !Settings.Default.ShowStartupForm)
                    {
                        MainWindow = new SkylineWindow(args);
                    }
                    else
                    {
                        StartWindow = new StartPage();
                        try
                        {
                            if (StartWindow.ShowDialog() != DialogResult.OK)
                            {
                                Application.Exit();
                                return;
                            }

                            MainWindow = StartWindow.MainWindow;
                        }
                        finally
                        {
                            StartWindow.Dispose();
                            StartWindow = null;
                        }
                    }
                }
                catch (Exception x)
                {
                    ReportExceptionUI(x, new StackTrace(1, true));
                }

                ConcurrencyVisualizer.StartEvents(MainWindow);

                // Position window offscreen for stress testing.
                if (SkylineOffscreen)
                    FormEx.SetOffscreen(MainWindow);

                ActionUtil.RunAsync(() =>
                {
                    try {
                        SendAnalyticsHit();
                    } catch (Exception ex) {
                        Trace.TraceWarning("Exception sending analytics hit {0}", ex);  // Not L10N
                    }
                });
                MainToolServiceName = Guid.NewGuid().ToString();
                Application.Run(MainWindow);
                StopToolService();
            }
            catch (Exception x)
            {
                // Send unhandled exceptions to the console.
                Console.WriteLine(x.Message);
                Console.Write(x.StackTrace);
            }

            MainWindow = null;
        }
Exemplo n.º 17
0
        /// <summary>
        /// Uses an <see cref="IToolStoreClient"/> to download (zip files) for each of the tools selected in the form's checklistbox.
        /// Returns a collection of tools to be updated. 
        /// </summary>
        private ICollection<ToolUpdateInfo> GetToolsToUpdate()
        {
            labelOperation.Text = Resources.ToolUpdatesDlg_GetTools_Downloading_Updates;
            var toolsToDownload = new Collection<ToolUpdateInfo>();
            var toolList = _tools.Keys.ToList();
            // get tools to update based on which ones are checked
            foreach (int index in checkedListBoxTools.CheckedIndices)
            {
                toolsToDownload.Add(toolList[index]);
            }

            ICollection<ToolUpdateInfo> successfulDownloads = null;
            ICollection<string> failedDownloads = null;

            using (var dlg = new LongWaitDlg {Message = Resources.ToolUpdatesDlg_GetToolsToUpdate_Downloading_Updates})
            {
                dlg.PerformWork(this, 1000,
                                longWaitBroker =>
                                DownloadTools(longWaitBroker, toolsToDownload, out successfulDownloads,
                                                out failedDownloads));
            }

            DisplayDownloadSummary(failedDownloads);
            return successfulDownloads;
        }
Exemplo n.º 18
0
        private void LaunchPeptideProteinsQuery()
        {
            HashSet<Protein> proteinSet = new HashSet<Protein>();
            using (var longWaitDlg = new LongWaitDlg
                {
                    Text = Resources.UniquePeptidesDlg_LaunchPeptideProteinsQuery_Querying_Background_Proteome_Database,
                    Message = Resources.UniquePeptidesDlg_LaunchPeptideProteinsQuery_Looking_for_proteins_with_matching_peptide_sequences
                })
            {
                try
                {
                    longWaitDlg.PerformWork(this, 1000, QueryPeptideProteins);
                }
                catch (Exception x)
                {
                    var message = TextUtil.LineSeparate(string.Format(Resources.UniquePeptidesDlg_LaunchPeptideProteinsQuery_Failed_querying_background_proteome__0__,
                                                BackgroundProteome.Name), x.Message);
                    MessageDlg.ShowWithException(this, message, x);
                }
            }
            if (_peptideProteins == null)
            {
                Close();
                return;
            }
            foreach (var proteins in _peptideProteins)
            {
                proteinSet.UnionWith(proteins);
            }
            List<Protein> proteinList = new List<Protein>();
            proteinList.AddRange(proteinSet);
            proteinList.Sort();
            foreach (var protein in proteinList)
            {
                ProteinColumn proteinColumn = new ProteinColumn(_proteinColumns.Count, protein);
                _proteinColumns.Add(proteinColumn);
                DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn
                {
                    Name = proteinColumn.Name,
                    HeaderText = ((protein.Gene != null) ? String.Format(Resources.UniquePeptidesDlg_LaunchPeptideProteinsQuery_, protein.Name, protein.Gene) : protein.Name), // Not L10N
                    ReadOnly = true,
                    ToolTipText = protein.ProteinMetadata.DisplayTextWithoutName(),
                    SortMode = DataGridViewColumnSortMode.Automatic,
                    Tag = proteinColumn,
                };
                dataGridView1.Columns.Add(column);
            }

            for (int i = 0; i < _peptideDocNodes.Count; i++)
            {
                var peptide = _peptideDocNodes[i];
                var proteins = _peptideProteins[i];
                var row = dataGridView1.Rows[dataGridView1.Rows.Add()];
                row.Tag = peptide;
                row.Cells[PeptideIncludedColumn.Name].Value = true;
                row.Cells[PeptideColumn.Name].Value = peptide.Peptide.Sequence;
                foreach (var proteinColumn in _proteinColumns)
                {
                    row.Cells[proteinColumn.Name].Value = proteins.Contains(proteinColumn.Protein);
                }
            }
            dataGridView1.EndEdit();
            if (dataGridView1.RowCount > 0)
            {
                // Select the first peptide to populate the other controls in the dialog.
                dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[1];
            }

            DrawCheckBoxOnPeptideIncludedColumnHeader();
        }
        public void AddFastaFile(string fastaFilePath)
        {
            String databasePath = textPath.Text;
            Settings.Default.FastaDirectory = Path.GetDirectoryName(fastaFilePath);
            using (var longWaitDlg = new LongWaitDlg { ProgressValue = 0 })
            {
                var progressMonitor = new ProgressMonitor(longWaitDlg);
                try
                {
                    longWaitDlg.PerformWork(this, 0, () =>
                    {
                        ProteomeDb proteomeDb = File.Exists(databasePath)
                            ? ProteomeDb.OpenProteomeDb(databasePath)
                            : ProteomeDb.CreateProteomeDb(databasePath);
                        using (proteomeDb)
                        {
                            using (var reader = File.OpenText(fastaFilePath))
                            {
                                proteomeDb.AddFastaFile(reader, progressMonitor.UpdateProgress);
                            }
                        }
                    });
                }
                catch (Exception x)
                {
                    var message = TextUtil.LineSeparate(string.Format(Resources.BuildBackgroundProteomeDlg_AddFastaFile_An_error_occurred_attempting_to_add_the_FASTA_file__0__,
                                                                      fastaFilePath), x.Message);
                    MessageDlg.ShowWithException(this, message, x);
                    return;
                }
            }

            string path = Path.GetFileName(fastaFilePath);
            if (path != null)
                listboxFasta.Items.Add(path);
            RefreshStatus();
        }
Exemplo n.º 20
0
        private MsDataFilePath[] GetWiffSubPaths(string filePath)
        {
            using (var longWaitDlg = new LongWaitDlg
                {
                    Text = Resources.ImportResultsDlg_GetWiffSubPaths_Sample_Names,
                    Message = string.Format(Resources.ImportResultsDlg_GetWiffSubPaths_Reading_sample_names_from__0__,
                                            Path.GetFileName(filePath))
                })
            {
                string[] dataIds = null;
                try
                {
                    longWaitDlg.PerformWork(this, 800, () => dataIds = MsDataFileImpl.ReadIds(filePath));
                }
                catch (Exception x)
                {
                    string message = TextUtil.LineSeparate(
                        string.Format(Resources.ImportResultsDlg_GetWiffSubPaths_An_error_occurred_attempting_to_read_sample_information_from_the_file__0__, filePath),
                        Resources.ImportResultsDlg_GetWiffSubPaths_The_file_may_be_corrupted_missing_or_the_correct_libraries_may_not_be_installed,
                        x.Message);
                    MessageDlg.ShowWithException(this, message, x);
                }

                return DataSourceUtil.GetWiffSubPaths(filePath, dataIds, ChooseSamples);
            }
        }
 public ProgressMonitor(LongWaitDlg longWaitDlg)
 {
     _longWaitDlg = longWaitDlg;
 }
        public bool BuildPeptideSearchLibrary(CancelEventArgs e)
        {
            // Nothing to build, if now search files were specified
            if (!SearchFilenames.Any())
            {
                var libraries = SkylineWindow.Document.Settings.PeptideSettings.Libraries;
                if (!libraries.HasLibraries)
                    return false;
                var libSpec = libraries.LibrarySpecs.FirstOrDefault(s => s.IsDocumentLibrary);
                return libSpec != null && LoadPeptideSearchLibrary(libSpec);
            }

            double cutOffScore;
            MessageBoxHelper helper = new MessageBoxHelper(WizardForm);
            if (!helper.ValidateDecimalTextBox(textCutoff, 0, 1.0, out cutOffScore))
            {
                e.Cancel = true;
                return false;
            }
            ImportPeptideSearch.CutoffScore = cutOffScore;

            BiblioSpecLiteBuilder builder;
            try
            {
                builder = ImportPeptideSearch.GetLibBuilder(SkylineWindow.Document, SkylineWindow.DocumentFilePath, cbIncludeAmbiguousMatches.Checked);
            }
            catch (FileEx.DeleteException de)
            {
                MessageDlg.ShowException(this, de);
                return false;
            }

            using (var longWaitDlg = new LongWaitDlg
                {
                    Text = Resources.BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Building_Peptide_Search_Library,
                    Message = Resources.BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Building_document_library_for_peptide_search_,
                })
            {
                // Disable the wizard, because the LongWaitDlg does not
                try
                {
                    ImportPeptideSearch.ClosePeptideSearchLibraryStreams(SkylineWindow.DocumentUI);
                    var status = longWaitDlg.PerformWork(WizardForm, 800,
                        monitor => LibraryManager.BuildLibraryBackground(SkylineWindow, builder, monitor, new LibraryManager.BuildState(null, null)));
                    if (status.IsError)
                    {
                        MessageDlg.ShowException(WizardForm, status.ErrorException);
                        return false;
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(WizardForm, TextUtil.LineSeparate(string.Format(Resources.BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Failed_to_build_the_library__0__,
                                                                                    Path.GetFileName(BiblioSpecLiteSpec.GetLibraryFileName(SkylineWindow.DocumentFilePath))), x.Message), x);
                    return false;
                }
            }

            var docLibSpec = builder.LibrarySpec.ChangeDocumentLibrary(true);
            Settings.Default.SpectralLibraryList.Insert(0, docLibSpec);

            // Go ahead and load the library - we'll need it for
            // the modifications and chromatograms page.
            if (!LoadPeptideSearchLibrary(docLibSpec))
                return false;

            var docNew = ImportPeptideSearch.AddDocumentSpectralLibrary(SkylineWindow.Document, docLibSpec);
            if (docNew == null)
                return false;

            SkylineWindow.ModifyDocument(Resources.BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Add_document_spectral_library, doc => docNew);

            if (!string.IsNullOrEmpty(builder.AmbiguousMatchesMessage))
            {
                MessageDlg.Show(WizardForm, builder.AmbiguousMatchesMessage);
            }
            return true;
        }
Exemplo n.º 23
0
 private bool GetPackages()
 {
     try
     {
         using (var dlg = new LongWaitDlg(null, false) {Message = Resources.RInstaller_GetPAckages_Installing_Packages})
         {
             dlg.PerformWork(this, 1000, InstallPackages);
         }
     }
     catch(TargetInvocationException ex)
     {
         //Win32Exception is thrown when the user does not ok Administrative Privileges
         if (ex.InnerException is ToolExecutionException || ex.InnerException is System.ComponentModel.Win32Exception)
         {
             MessageDlg.ShowException(this, ex);
             return false;
         }
         else
             throw;
     }
     return true;
 }
        private bool LoadPeptideSearchLibrary(LibrarySpec docLibSpec)
        {
            if (docLibSpec == null)
                return false;

            using (var longWait = new LongWaitDlg
            {
                Text = Resources.BuildPeptideSearchLibraryControl_LoadPeptideSearchLibrary_Loading_Library
            })
            {
                try
                {
                    var status = longWait.PerformWork(WizardForm, 800, monitor => ImportPeptideSearch.LoadPeptideSearchLibrary(LibraryManager, docLibSpec, monitor));
                    if (status.IsError)
                    {
                        MessageDlg.ShowException(WizardForm, status.ErrorException);
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(WizardForm,
                        TextUtil.LineSeparate(string.Format(Resources.BuildPeptideSearchLibraryControl_LoadPeptideSearchLibrary_An_error_occurred_attempting_to_import_the__0__library_,
                                                            docLibSpec.Name), x.Message), x);
                }
            }
            return ImportPeptideSearch.HasDocLib;
        }
Exemplo n.º 25
0
 public void DownloadSelectedTool()
 {
     try
     {
         string identifier = _tools[listBoxTools.SelectedIndex].Identifier;
         using (var dlg = new LongWaitDlg {ProgressValue = 0, Message = string.Format(Resources.ToolStoreDlg_DownloadSelectedTool_Downloading__0_, _tools[listBoxTools.SelectedIndex].Name)})
         {
             dlg.PerformWork(this, 500, progressMonitor => DownloadPath = _toolStoreClient.GetToolZipFile(progressMonitor, identifier, Path.GetTempPath()));
             if (!dlg.IsCanceled)
                 DialogResult = DialogResult.OK;
         }
     }
     catch (TargetInvocationException ex)
     {
         var exceptionType = ex.InnerException.GetType();
         if (exceptionType == typeof (ToolExecutionException) || exceptionType == typeof(WebException))
             MessageDlg.ShowException(this, ex);
         else
         {
             throw;
         }
     }
 }
Exemplo n.º 26
0
        public Database GetDatabase(Control owner)
        {
            if (_database == null)
            {
                var status = new ProgressStatus(Resources.ExportReportDlg_GetDatabase_Generating_Report_Data);
                using (var longWait = new LongWaitDlg
                    {
                        Text = status.Message,
                        Message = Resources.ExportReportDlg_GetDatabase_Analyzing_document
                    })
                {
                    longWait.PerformWork(owner, 1500, broker => EnsureDatabase(broker, 100, ref status));
                }
            }

            return _database;
        }
Exemplo n.º 27
0
        private bool ExportReport(string fileName, char separator)
        {
            try
            {
                using (var saver = new FileSaver(fileName))
                {
                    if (!saver.CanSave(this))
                        return false;

                    using (var writer = new StreamWriter(saver.SafeName))
                    {
                        Report report = GetReport();
                        bool success = false;

                        using (var longWait = new LongWaitDlg { Text = Resources.ExportReportDlg_ExportReport_Generating_Report })
                        {
                            longWait.PerformWork(this, 1500, broker =>
                            {
                                var status = new ProgressStatus(Resources.ExportReportDlg_GetDatabase_Analyzing_document);
                                broker.UpdateProgress(status);
                                Database database = EnsureDatabase(broker, 80, ref status);
                                if (broker.IsCanceled)
                                    return;
                                broker.UpdateProgress(status = status.ChangeMessage(Resources.ExportReportDlg_ExportReport_Building_report));
                                ResultSet resultSet = report.Execute(database);
                                if (broker.IsCanceled)
                                    return;
                                broker.UpdateProgress(status = status.ChangePercentComplete(95)
                                    .ChangeMessage(Resources.ExportReportDlg_ExportReport_Writing_report));

                                ResultSet.WriteReportHelper(resultSet, separator, writer, CultureInfo);

                                writer.Flush();
                                writer.Close();

                                if (broker.IsCanceled)
                                    return;
                                broker.UpdateProgress(status.Complete());

                                saver.Commit();
                                success = true;
                            });
                        }

                        return success;
                    }
                }
            }
            catch (Exception x)
            {
                MessageDlg.ShowWithException(this, string.Format(Resources.ExportReportDlg_ExportReport_Failed_exporting_to, fileName, GetExceptionDisplayMessage(x)), x);
                return false;
            }
        }
Exemplo n.º 28
0
        /* TODO bspratt drift time libs for small molecules

        [TestMethod]
        public void WatersImsMsePredictedDriftTimesChromatogramTestAsSmallMolecules()
        {
            WatersImsMseChromatogramTest(DriftFilterType.predictor, true);
        }

        [TestMethod]
        public void WatersImsMseLibraryDriftTimesChromatogramTestAsSmallMolecules()
        {
            WatersImsMseChromatogramTest(DriftFilterType.library, true);
        }

         */
        private void WatersImsMseChromatogramTest(DriftFilterType mode,
            RefinementSettings.ConvertToSmallMoleculesMode asSmallMolecules = RefinementSettings.ConvertToSmallMoleculesMode.none)
        {
            string subdir = (asSmallMolecules == RefinementSettings.ConvertToSmallMoleculesMode.none) ? null : asSmallMolecules.ToString();
            var testFilesDir = new TestFilesDir(TestContext, ZIP_FILE, subdir);
            TestSmallMolecules = false; // Don't need that extra magic node

            bool withDriftTimePredictor = (mode == DriftFilterType.predictor); // Load the doc that has a drift time predictor?
            bool withDriftTimeFilter = (mode != DriftFilterType.none); // Perform drift time filtering?  (either with predictor, or with bare times in blib file)
            string docPath;
            SrmDocument document = InitWatersImsMseDocument(testFilesDir, withDriftTimePredictor ? "single_with_driftinfo.sky" : "single_no_driftinfo.sky", asSmallMolecules, out docPath);
            AssertEx.IsDocumentState(document, (withDriftTimePredictor || (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.none)) ? 1 : 0, 1, 1, 1, 8); // Drift time lib load bumps the doc version
            var docContainer = new ResultsTestDocumentContainer(document, docPath);
            var doc = docContainer.Document;
            var docOriginal = doc;

            string testModeStr = withDriftTimePredictor ? "with drift time predictor" : "without drift time info";

            if (withDriftTimeFilter && !withDriftTimePredictor)
            {
                // Use the bare drift times in the spectral library
                var librarySpec = new BiblioSpecLiteSpec("drift test",
                                                    testFilesDir.GetTestPath("mse-mobility.filtered-scaled.blib"));
                doc = doc.ChangeSettings(
                    doc.Settings.ChangePeptideLibraries(lib => lib.ChangeLibrarySpecs(new[] { librarySpec })).
                    ChangePeptidePrediction(p => p.ChangeLibraryDriftTimesResolvingPower(100)).
                    ChangePeptidePrediction(p => p.ChangeUseLibraryDriftTimes(true))
                    );
                testModeStr = "with drift times from spectral library";
            }

            var listChromatograms = new List<ChromatogramSet>();
            // A small subset of the QC_HDMSE_02_UCA168_3495_082213 data set (RT 21.5-22.5) from Will Thompson
            const string path = @"waters-mobility.mz5";
            listChromatograms.Add(AssertResult.FindChromatogramSet(doc, new MsDataFilePath(path)) ??
                                    new ChromatogramSet(Path.GetFileName(path).Replace('.', '_'), new[] { path }));
            var docResults = doc.ChangeMeasuredResults(new MeasuredResults(listChromatograms));
            Assert.IsTrue(docContainer.SetDocument(docResults, docOriginal, true));
            docContainer.AssertComplete();
            document = docContainer.Document;

            float tolerance = (float)document.Settings.TransitionSettings.Instrument.MzMatchTolerance;
            double maxHeight = 0;
            var results = document.Settings.MeasuredResults;
            Assert.AreEqual(1, document.MoleculePrecursorPairs.Count());
            foreach (var pair in document.MoleculePrecursorPairs)
            {
                ChromatogramGroupInfo[] chromGroupInfo;
                Assert.IsTrue(results.TryLoadChromatogram(0, pair.NodePep, pair.NodeGroup,
                    tolerance, true, out chromGroupInfo));
                Assert.AreEqual(1, chromGroupInfo.Length, testModeStr);
                var chromGroup = chromGroupInfo[0];
                var expectedPeaks = ((asSmallMolecules == RefinementSettings.ConvertToSmallMoleculesMode.masses_only) ? 6 : 5);
                Assert.AreEqual(withDriftTimeFilter ? 3 : expectedPeaks, chromGroup.NumPeaks, testModeStr); // This will be higher if we don't filter on DT
                foreach (var tranInfo in chromGroup.TransitionPointSets)
                {
                    maxHeight = Math.Max(maxHeight, tranInfo.MaxIntensity);
                }
            }
            Assert.AreEqual(withDriftTimeFilter? 5226 : 20075 , maxHeight, 1, testModeStr);  // Without DT filtering, this will be much greater

            // now drill down for specific values
            int nPeptides = 0;
            foreach (var nodePep in document.Molecules.Where(nodePep => nodePep.Results[0] != null))
            {
                // expecting just one peptide result in this small data set
                if (nodePep.Results[0].Sum(chromInfo => chromInfo.PeakCountRatio > 0 ? 1 : 0) > 0)
                {
                    Assert.AreEqual(21.94865, (double)nodePep.GetMeasuredRetentionTime(0), .0001, testModeStr);
                    Assert.AreEqual(1.0, (double)nodePep.GetPeakCountRatio(0), 0.0001, testModeStr);
                    nPeptides++;
                }
            }
            Assert.AreEqual(1, nPeptides);

            if (withDriftTimePredictor || withDriftTimeFilter)
            {
                // Verify that the .imdb pr .blib file goes out in the share zipfile
                for (int complete = 0; complete <= 1; complete++)
                {
                    var sharePath = testFilesDir.GetTestPath(complete==1?"share_complete.zip":"share_minimized.zip");
                    var share = new SrmDocumentSharing(document, docPath, sharePath, complete==1);
                    using (var longWaitDlg = new LongWaitDlg
                    {
                        // ReSharper disable once LocalizableElement
                        Text = "unit test WatersImsTest -- sharing document",
                    })
                    {
                        longWaitDlg.PerformWork(null, 1000, share.Share);
                        Assert.IsFalse(longWaitDlg.IsCanceled);
                    }

                    var files = share.ListEntries().ToArray();
                    Assert.IsTrue(files.Contains(withDriftTimePredictor ? "scaled.imdb" : "mse-mobility.filtered-scaled.blib"));
                    // And round trip it to make sure we haven't left out any new features in minimized imdb or blib files
                    using (var longWaitDlg = new LongWaitDlg
                    {
                        // ReSharper disable once LocalizableElement
                        Text = "unit test WatersImsTest",
                    })
                    {
                        longWaitDlg.PerformWork(null, 1000, share.Extract);
                        Assert.IsFalse(longWaitDlg.IsCanceled);
                    }
                    using (TextReader reader = new StreamReader(share.DocumentPath))
                    {
                        XmlSerializer documentSerializer = new XmlSerializer(typeof(SrmDocument));
                        var document2 = (SrmDocument) documentSerializer.Deserialize(reader);
                        Assert.IsNotNull(document2);
                        var im = document.Settings.GetIonMobilities(new MsDataFilePath(path));
                        var pep = document2.Molecules.First();
                        foreach (TransitionGroupDocNode nodeGroup in pep.Children)
                        {
                            double windowDT;
                            var centerDriftTime = document.Settings.PeptideSettings.Prediction.GetDriftTime(
                                                       pep, nodeGroup, im, out windowDT);
                            Assert.AreEqual(3.86124, centerDriftTime.DriftTimeMsec(false) ?? 0, .0001, testModeStr);
                            Assert.AreEqual(0.077224865797235934, windowDT, .0001, testModeStr);
                        }
                    }
                }
            }

            // Release file handles
            docContainer.Release();
            testFilesDir.Dispose();
            string cachePath = ChromatogramCache.FinalPathForName(docPath, null);
            FileEx.SafeDelete(cachePath);
        }
Exemplo n.º 29
0
        public void OkDialog()
        {
            MessageBoxHelper helper = new MessageBoxHelper(this);
            string serverName;
            if (!helper.ValidateNameTextBox(textServerURL, out serverName))
                return;

            Uri uriServer = PanoramaUtil.ServerNameToUri(serverName);
            if (uriServer == null)
            {
                helper.ShowTextBoxError(textServerURL, Resources.EditServerDlg_OkDialog_The_text__0__is_not_a_valid_server_name_, serverName);
                return;
            }

            var panoramaClient = PanoramaClient ?? new WebPanoramaClient(uriServer);

            using (var waitDlg = new LongWaitDlg { Text = Resources.EditServerDlg_OkDialog_Verifying_server_information })
            {
                try
                {
                    waitDlg.PerformWork(this, 1000, () => PanoramaUtil.VerifyServerInformation( panoramaClient, Username, Password));
                }
                catch (Exception x)
                {
                    helper.ShowTextBoxError(textServerURL, x.Message);
                    return;
                }
            }

            Uri updatedUri = panoramaClient.ServerUri ?? uriServer;

            if (_existing.Contains(server => !ReferenceEquals(_server, server) && Equals(updatedUri, server.URI)))
            {
                helper.ShowTextBoxError(textServerURL, Resources.EditServerDlg_OkDialog_The_server__0__already_exists_, uriServer.Host);
                return;
            }

            _server = new Server(updatedUri, Username, Password);
            DialogResult = DialogResult.OK;
        }
Exemplo n.º 30
0
 public void AddDirectory(string dirPath)
 {
     using (var longWaitDlg = new LongWaitDlg
         {
             Text = Resources.BuildLibraryDlg_AddDirectory_Find_Input_Files,
         })
     {
         try
         {
             var inputFiles = new List<string>();
             longWaitDlg.PerformWork(this, 800, broker => FindInputFiles(dirPath, inputFiles, broker));
             AddInputFiles(inputFiles);
         }
         catch (Exception x)
         {
             var message = TextUtil.LineSeparate(string.Format(Resources.BuildLibraryDlg_AddDirectory_An_error_occurred_reading_files_in_the_directory__0__,
                                                               dirPath),
                                                 x.Message);
             MessageDlg.ShowWithException(this, message, x);
         }
     }
 }