示例#1
0
        public static bool?OverwriteAnnotations(List <AnnotationDef> annotations)
        {
            List <string> annotationTitles = annotations.Select(annotation => annotation.GetKey()).ToList();

            string annotationMultiMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteAnnotations_Annotations_with_the_following_names_already_exist_, String.Empty,
                                                                  "{0}", String.Empty); // Not L10N

            string annotationSingleMessage =
                TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteAnnotations_An_annotation_with_the_following_name_already_exists_, String.Empty, "{0}", String.Empty); // Not L10N

            string annotationMessage = annotations.Count == 1 ? annotationSingleMessage : annotationMultiMessage;
            string question          = Resources.ConfigureToolsDlg_OverwriteAnnotations_Do_you_want_to_overwrite_or_keep_the_existing_annotations_;

            string messageFormat = TextUtil.LineSeparate(annotationMessage, question);

            DialogResult result = MultiButtonMsgDlg.Show(
                null,
                String.Format(messageFormat, TextUtil.LineSeparate(annotationTitles)),
                Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite,
                Resources.ConfigureToolsDlg_OverwriteAnnotations_Keep_Existing, true);

            switch (result)
            {
            case DialogResult.Cancel:
                return(null);

            case DialogResult.Yes:
                return(true);

            case DialogResult.No:
                return(false);
            }
            return(false);
        }
示例#2
0
        public void Cancel()
        {
            if (!Unsaved)
            {
                DialogResult = DialogResult.Cancel;
            }
            else
            {
                DialogResult result = MultiButtonMsgDlg.Show(
                    this,
                    Resources.ConfigureToolsDlg_Cancel_Do_you_wish_to_Save_changes_,
                    MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, true);
                switch (result)
                {
                case DialogResult.Yes:
                    if (SaveTools())
                    {
                        DialogResult = DialogResult.OK;
                    }
                    break;

                case DialogResult.No:
                    DialogResult = DialogResult.Cancel;
                    break;
                }
            }
        }
        /// <summary>
        /// Shows a dialog prompting user to decide whether to use embedded spectra when external spectra are preferred but cannot be found.
        /// Returns 'normal' if the user wants Embedded spectra, 'option1' to retry finding the external spectra, or to 'cancel' to abort the library build.
        /// </summary>
        public static UpdateProgressResponse ShowLibraryMissingExternalSpectraError(Control parentWindow, Exception errorException)
        {
            // E.g. could not find external raw data for MaxQuant msms.txt; ask user if they want to retry with "prefer embedded spectra" option
            if (!BiblioSpecLiteBuilder.IsLibraryMissingExternalSpectraError(errorException, out string spectrumFilename, out string resultsFilepath))
            {
                throw new InvalidOperationException(@"IsLibraryMissingExternalSpectraError returned false");
            }

            // TODO: parse supported file extensions from BiblioSpec or ProteoWizard
            var dialogResult = MultiButtonMsgDlg.Show(parentWindow,
                                                      string.Format(Resources.VendorIssueHelper_ShowLibraryMissingExternalSpectraError_Could_not_find_an_external_spectrum_file_matching__0__in_the_same_directory_as_the_MaxQuant_input_file__1__,
                                                                    spectrumFilename, resultsFilepath) +
                                                      string.Format(Resources.VendorIssueHelper_ShowLibraryMissingExternalSpectraError_ButtonDescriptionsSupportsExtensions__0__, BiblioSpecLiteBuilder.BiblioSpecSupportedFileExtensions),
                                                      Resources.BiblioSpecLiteBuilder_Embedded,
                                                      Resources.AlertDlg_GetDefaultButtonText__Retry, true);

            switch (dialogResult)
            {
            case DialogResult.Cancel: return(UpdateProgressResponse.cancel);

            case DialogResult.Yes: return(UpdateProgressResponse.normal);

            case DialogResult.No: return(UpdateProgressResponse.option1);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#4
0
        private void EnsureChorusAccount()
        {
            if (_chorusAccounts.Any())
            {
                return;
            }
            DialogResult buttonPress = MultiButtonMsgDlg.Show(
                this,
                TextUtil.LineSeparate(
                    Resources.OpenDataSourceDialog_EnsureChorusAccount_No_Chorus_acounts_have_been_specified,
                    Resources.OpenDataSourceDialog_EnsureChorusAccount_Press_Register_to_register_for_an_account_on_the_Chorus_Project,
                    Resources.OpenDataSourceDialog_EnsureChorusAccount_Press_Add_to_use_specify_an_existing_Chorus_account),
                Resources.OpenDataSourceDialog_EnsureChorusAccount_Register, Resources.OpenDataSourceDialog_EnsureChorusAccount_Add, true);

            if (buttonPress == DialogResult.Cancel)
            {
                return;
            }

            if (buttonPress == DialogResult.Yes)
            {
                // person intends to register
                WebHelpers.OpenLink(this, "https://chorusproject.org/pages/register.html"); // Not L10N
            }
            var newAccount = _chorusAccounts.NewItem(this, _chorusAccounts, null);

            if (null != newAccount)
            {
                _chorusAccounts.Add(newAccount);
            }
        }
示例#5
0
        public void OkDialog()
        {
            var chosenLists          = new HashSet <string>(_listsListBoxDriver.Chosen.Select(data => data.ListName));
            var removedListsWithData = DocumentContainer.Document.Settings.DataSettings.Lists
                                       .Where(list => !chosenLists.Contains(list.ListName) && list.RowCount > 0).ToArray();

            if (removedListsWithData.Any())
            {
                string message;
                if (removedListsWithData.Length == 1)
                {
                    var list = removedListsWithData[0];
                    message = string.Format(
                        Resources.DocumentSettingsDlg_OkDialog_The_list___0___has__1__items_in_it__If_you_remove_that_list_from_your_document__those_items_will_be_deleted__Are_you_sure_you_want_to_delete_those_items_from_that_list_,
                        list.ListName, list.RowCount);
                }
                else
                {
                    message = TextUtil.LineSeparate(new[]
                    {
                        Resources.DocumentSettingsDlg_OkDialog_The_following_lists_have_items_in_them_which_will_be_deleted_when_you_remove_the_lists_from_your_document_
                    }
                                                    .Concat(removedListsWithData.Select(list =>
                                                                                        string.Format(Resources.DocumentSettingsDlg_OkDialog_List___0___with__1__items, list.ListName, list.RowCount)))
                                                    .Concat(new[] { Resources.DocumentSettingsDlg_OkDialog_Are_you_sure_you_want_to_delete_those_items_from_those_lists_ }));
                }
                if (MultiButtonMsgDlg.Show(this, message, MultiButtonMsgDlg.BUTTON_OK) == DialogResult.Cancel)
                {
                    return;
                }
            }
            Settings.Default.ListDefList.Clear();
            Settings.Default.ListDefList.AddRange(_listsListBoxDriver.List.Select(list => list.DeleteAllRows()));
            DialogResult = DialogResult.OK;
        }
示例#6
0
        private bool SetCalibrationPeptides(ICollection <PeptideDocNode> exclude)
        {
            CheckDisposed();
            var document = Program.ActiveDocumentUI;

            if (!document.Settings.HasResults)
            {
                MessageDlg.Show(this, Resources.CalibrateIrtDlg_UseResults_The_document_must_contain_results_to_calibrate_a_standard);
                return(false);
            }

            var targetResolver = TargetResolver.MakeTargetResolver(document);

            _gridViewDriver.TargetResolver = targetResolver;

            var peptides = document.Molecules.Where(nodePep => nodePep.SchedulingTime.HasValue).ToArray();
            var count    = peptides.Length;

            if (exclude != null && exclude.Count > 0)
            {
                peptides = peptides.Where(nodePep => !exclude.Contains(nodePep)).ToArray();
                count    = peptides.Length;
                if (count < MIN_STANDARD_PEPTIDES)
                {
                    MessageDlg.Show(this,
                                    ModeUIAwareStringFormat(
                                        Resources.CalibrateIrtDlg_SetCalibrationPeptides_The_document_contains_results_for__0__peptide_s__not_in_this_standard__which_is_less_than_the_minimum_requirement_of__1__to_calibrate_a_standard_,
                                        count, MIN_STANDARD_PEPTIDES));
                    return(false);
                }
                else if (count < MIN_SUGGESTED_STANDARD_PEPTIDES)
                {
                    if (MultiButtonMsgDlg.Show(this,
                                               ModeUIAwareStringFormat(
                                                   Resources.CalibrateIrtDlg_SetCalibrationPeptides_The_document_only_contains_results_for__0__peptide_s__not_in_this_standard__It_is_recommended_to_use_at_least__1__peptides_to_calibrate_a_standard__Are_you_sure_you_wish_to_continue_,
                                                   count, MIN_SUGGESTED_STANDARD_PEPTIDES),
                                               MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false) != DialogResult.Yes)
                    {
                        return(false);
                    }
                }
            }
            if (count > 20)
            {
                using (var dlg = new AddIrtStandardsDlg(count, exclude != null && exclude.Count > 0))
                {
                    if (dlg.ShowDialog(this) != DialogResult.OK)
                    {
                        return(false);
                    }

                    count = dlg.StandardCount;
                }
            }

            _gridViewDriver.Recalculate(document, count, exclude);
            return(true);
        }
示例#7
0
        public void OkDialog()
        {
            var reader           = new StringReader(ProteinsText);
            var notFoundLines    = new List <string>();
            var acceptedProteins = new HashSet <string>();
            var setProteinNames  = GetProteinNames();

            string line;

            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }

                if (!setProteinNames.Contains(line))
                {
                    notFoundLines.Add(line);
                }
                else
                {
                    acceptedProteins.Add(line);
                }
            }

            if (acceptedProteins.Count == 0)
            {
                MessageDlg.Show(this, Resources.RefineListDlgProtein_OkDialog_None_of_the_specified_proteins_are_in_the_document_);
                return;
            }
            if (notFoundLines.Count > 0)
            {
                string message;
                if (notFoundLines.Count == 1)
                {
                    message = string.Format(Resources.RefineListDlgProtein_OkDialog_The_protein___0___is_not_in_the_document__Do_you_want_to_continue_, notFoundLines[0]);
                }
                else if (notFoundLines.Count < 15)
                {
                    message = TextUtil.LineSeparate(Resources.RefineListDlgProtein_OkDialog_The_following_proteins_are_not_in_the_document_, string.Empty,
                                                    TextUtil.LineSeparate(notFoundLines), string.Empty,
                                                    Resources.RefineListDlgProtein_OkDialog_Do_you_want_to_continue);
                }
                else
                {
                    message = string.Format(Resources.RefineListDlgProtein_OkDialog_Of_the_specified__0__proteins__1__are_not_in_the_document__Do_you_want_to_continue_,
                                            notFoundLines.Count + acceptedProteins.Count, notFoundLines.Count);
                }
                if (MultiButtonMsgDlg.Show(this, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
                {
                    return;
                }
            }
            AcceptedProteins = acceptedProteins;
            DialogResult     = DialogResult.OK;
        }
示例#8
0
 public void ResetAllSettings()
 {
     if (MultiButtonMsgDlg.Show(this,
                                string.Format(
                                    Resources
                                    .ToolOptionsUI_btnResetSettings_Click_Are_you_sure_you_want_to_clear_all_saved_settings__This_will_immediately_return__0__to_its_original_configuration_and_cannot_be_undone_,
                                    Program.Name), MultiButtonMsgDlg.BUTTON_OK) == DialogResult.OK)
     {
         Settings.Default.Reset();
     }
 }
示例#9
0
        public void RemovePeaks(SrmDocument.DOCUMENT_TYPE docType, BoundDataGridView dataGridView)
        {
            var parent        = FormUtil.FindTopLevelOwner(dataGridView);
            var selectedPeaks = GetSelectedPeaks(dataGridView).Distinct().ToArray();

            if (selectedPeaks.Length == 0)
            {
                MessageDlg.Show(parent, Resources.RemovePeaksAction_RemovePeaks_No_peaks_are_selected);
                return;
            }

            var    lookup  = selectedPeaks.ToLookup(tuple => tuple.Item1, tuple => tuple.Item2).ToArray();
            string message = GetConfirmRemoveMessage(docType, selectedPeaks.Length, lookup.Length);

            if (MultiButtonMsgDlg.Show(parent, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
            {
                return;
            }

            var skylineWindow = GetSkylineWindow(dataGridView);

            lock (skylineWindow.GetDocumentChangeLock())
            {
                skylineWindow.ModifyDocument(Resources.RemovePeaksAction_RemovePeaks_Remove_peaks,
                                             doc =>
                {
                    var longOperationRunner = new LongOperationRunner
                    {
                        ParentControl = parent,
                        JobTitle      = Resources.RemovePeaksAction_RemovePeaks_Removing_Peaks
                    };
                    SrmDocument resultDocument = doc;
                    doc = doc.BeginDeferSettingsChanges();
                    longOperationRunner.Run(broker =>
                    {
                        for (int iGroup = 0; iGroup < lookup.Length; iGroup++)
                        {
                            broker.ProgressValue = iGroup * 100 / lookup.Length;
                            if (broker.IsCanceled)
                            {
                                return;
                            }
                            doc = RemovePeaks(doc, lookup[iGroup]);
                        }

                        resultDocument = doc.EndDeferSettingsChanges(resultDocument, null);
                    });
                    return(resultDocument);
                },
                                             docPair => AuditLogEntry.CreateSingleMessageEntry(
                                                 new MessageInfo(MessageType.removed_peaks, docPair.NewDocumentType, selectedPeaks.Length, lookup.Length)));
            }
        }
示例#10
0
        protected void DeleteSkylineDocNodes(Control owner, ICollection <SkylineDocNode> docNodes)
        {
            if (docNodes.Count == 0)
            {
                return;
            }
            var confirmationMessages = docNodes.Select(node => node.GetDeleteConfirmation(docNodes.Count)).Distinct()
                                       .ToArray();
            string message = confirmationMessages.Length == 1
                ? confirmationMessages[0]
                : SkylineDocNode.GetGenericDeleteConfirmation(docNodes.Count);

            if (MultiButtonMsgDlg.Show(owner, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
            {
                return;
            }
            DeleteDocNodes(new HashSet <IdentityPath>(docNodes.Select(node => node.IdentityPath)));
        }
示例#11
0
        /// <summary>
        /// Returns true if the tools are saved
        /// </summary>
        private bool PromptForSave()
        {
            if (Unsaved)
            {
                DialogResult toSave = MultiButtonMsgDlg.Show(
                    this,
                    string.Format(Resources.ConfigureToolsDlg_AddFromFile_You_must_save_changes_before_installing_tools__Would_you_like_to_save_changes_),
                    MultiButtonMsgDlg.BUTTON_YES, Resources.ConfigureToolsDlg_AddFromFile_Cancel, false);
                switch (toSave)
                {
                case (DialogResult.Yes):
                    SaveTools();
                    return(true);

                case (DialogResult.No):
                    return(false);
                }
            }
            return(true);
        }
示例#12
0
        public static void DeleteSkylineDocNodes(SkylineWindow skylineWindow, BoundDataGridView dataGridView, IEnumerable <SkylineDocNode> docNodesToDelete)
        {
            var docNodes = (ICollection <SkylineDocNode>)DistinctNodes(docNodesToDelete).ToList();

            if (docNodes.Count == 0)
            {
                return;
            }

            var owner = FormUtil.FindTopLevelOwner(dataGridView);
            var confirmationMessages = docNodes.Select(node => node.GetDeleteConfirmation(docNodes.Count)).Distinct()
                                       .ToArray();
            string message = confirmationMessages.Length == 1
                ? confirmationMessages[0]
                : SkylineDocNode.GetGenericDeleteConfirmation(docNodes.Count);

            if (MultiButtonMsgDlg.Show(owner, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
            {
                return;
            }
            DeleteDocNodes(skylineWindow, new HashSet <IdentityPath>(docNodes.Select(node => node.IdentityPath)));
        }
示例#13
0
        public override void Delete()
        {
            var selectedItems = GetSelectedListItems(BoundDataGridView);

            if (selectedItems.Count == 0)
            {
                return;
            }
            string message = string.Format(Resources.ListViewContext_Delete_Are_you_sure_you_want_to_delete_the__0__selected_items_from_the_list___1___, selectedItems.Count, ListName);

            if (MultiButtonMsgDlg.Show(BoundDataGridView, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
            {
                return;
            }
            SkylineDataSchema.ModifyDocument(EditDescription.Message(ListRef.PROTOTYPE.ChangeName(ListName), string.Format(Resources.ListViewContext_Delete_Delete_from_list___0__, ListName)),
                                             doc =>
            {
                var listData = doc.Settings.DataSettings.FindList(ListName);
                listData     = listData.DeleteItems(selectedItems);
                return(doc.ChangeSettings(
                           doc.Settings.ChangeDataSettings(doc.Settings.DataSettings.ReplaceList(listData))));
            }, AuditLogEntry.SettingsLogFunction);
        }
示例#14
0
        public bool ValidateNewRow(RowItem rowItem, out bool cancelRowEdit)
        {
            cancelRowEdit = false;
            var listItem = rowItem.Value as ListItem;

            if (listItem == null)
            {
                return(true);
            }
            var values = ((ListItem.NewRecordData)listItem.GetRecord()).UncommittedValues;

            if (values.Count == 0)
            {
                return(true);
            }

            try
            {
                ListItemId listItemId;
                var        listData = SkylineDataSchema.Document.Settings.DataSettings.FindList(ListName);
                listData.AddRow(values, out listItemId);
                return(true);
            }
            catch (Exception exception)
            {
                if (MultiButtonMsgDlg.Show(BoundDataGridView,
                                           TextUtil.LineSeparate(Resources.ListViewContext_ValidateNewRow_The_new_row_could_not_be_added_because_of_the_following_error_,
                                                                 exception.Message, Resources.ListViewContext_ValidateNewRow_Press_OK_to_continue_editing_your_row__or_Cancel_to_throw_away_the_new_row_)

                                           , MultiButtonMsgDlg.BUTTON_OK) == DialogResult.Cancel)
                {
                    cancelRowEdit = true;
                }
                return(false);
            }
        }
示例#15
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            string name;

            if (!helper.ValidateNameTextBox(_editing ? (Control)textName : comboMod, out name))
            {
                return;
            }

            // Allow updating the original modification
            if (!_editing || !Equals(name, Modification.Name))
            {
                if (!ModNameAvailable(name))
                {
                    helper.ShowTextBoxError(_editing ? (Control)textName : comboMod,
                                            Resources.EditStaticModDlg_OkDialog_The_modification__0__already_exists, name);
                    return;
                }
            }

            string aas = comboAA.Text;

            if (string.IsNullOrEmpty(aas))
            {
                aas = null;
            }
            else
            {
                // Use the cleanest possible format.
                var sb = new StringBuilder();
                foreach (string aaPart in aas.Split(SEPARATOR_AA))
                {
                    string aa = aaPart.Trim();
                    if (aa.Length == 0)
                    {
                        continue;
                    }
                    if (sb.Length > 0)
                    {
                        sb.Append(", "); // Not L10N
                    }
                    sb.Append(aa);
                }
            }

            string      termString = comboTerm.SelectedItem.ToString();
            ModTerminus?term       = null;

            if (!string.IsNullOrEmpty(termString))
            {
                term = (ModTerminus)Enum.Parse(typeof(ModTerminus), termString);
            }

            if (cbVariableMod.Checked && aas == null && term == null)
            {
                MessageDlg.Show(this, Resources.EditStaticModDlg_OkDialog_Variable_modifications_must_specify_amino_acid_or_terminus);
                comboAA.Focus();
                return;
            }

            string     formula    = null;
            double?    monoMass   = null;
            double?    avgMass    = null;
            LabelAtoms labelAtoms = LabelAtoms.None;

            if (cbChemicalFormula.Checked)
            {
                formula = Formula;
            }
            else
            {
                labelAtoms = LabelAtoms;
            }

            // Get the losses to know whether any exist below
            IList <FragmentLoss> losses = null;

            if (listNeutralLosses.Items.Count > 0)
            {
                losses = Losses.ToArray();
            }

            if (!string.IsNullOrEmpty(formula))
            {
                try
                {
                    SequenceMassCalc.FormulaMass(BioMassCalc.MONOISOTOPIC, formula, SequenceMassCalc.MassPrecision);
                }
                catch (ArgumentException x)
                {
                    _formulaBox.ShowTextBoxErrorFormula(helper, x.Message);
                    return;
                }
            }
            else if (labelAtoms == LabelAtoms.None)
            {
                formula = null;

                // Allow formula and both masses to be empty, if losses are present
                if (NotZero(_formulaBox.MonoMass) || NotZero(_formulaBox.AverageMass) || losses == null)
                {
                    // TODO: Maximum and minimum masses should be formalized and applied everywhere
                    double mass;
                    if (!_formulaBox.ValidateMonoText(helper, -1500, 5000, out mass))
                    {
                        return;
                    }
                    monoMass = mass;
                    if (!_formulaBox.ValidateAverageText(helper, -1500, 5000, out mass))
                    {
                        return;
                    }
                    avgMass = mass;
                }
                // Loss-only modifications may not be variable
                else if (cbVariableMod.Checked)
                {
                    MessageDlg.Show(this, Resources.EditStaticModDlg_OkDialog_The_variable_checkbox_only_applies_to_precursor_modification_Product_ion_losses_are_inherently_variable);
                    cbVariableMod.Focus();
                    return;
                }
            }
            else if (aas == null && term.HasValue)
            {
                MessageDlg.Show(this, Resources.EditStaticModDlg_OkDialog_Labeled_atoms_on_terminal_modification_are_not_valid);
                return;
            }

            RelativeRT relativeRT = RelativeRT.Matching;

            if (comboRelativeRT.Visible && comboRelativeRT.SelectedItem != null)
            {
                relativeRT = RelativeRTExtension.GetEnum(comboRelativeRT.SelectedItem.ToString());
            }

            // Store state of the chemical formula checkbox for next use.
            if (cbChemicalFormula.Visible)
            {
                Settings.Default.ShowHeavyFormula = _formulaBox.FormulaVisible;
            }

            var newMod = new StaticMod(name,
                                       aas,
                                       term,
                                       cbVariableMod.Checked,
                                       formula,
                                       labelAtoms,
                                       relativeRT,
                                       monoMass,
                                       avgMass,
                                       losses);

            foreach (StaticMod mod in _existing)
            {
                if (newMod.Equivalent(mod) && !(_editing && mod.Equals(_originalModification)))
                {
                    if (DialogResult.OK == MultiButtonMsgDlg.Show(
                            this,
                            TextUtil.LineSeparate(Resources.EditStaticModDlg_OkDialog_There_is_an_existing_modification_with_the_same_settings,
                                                  string.Format("'{0}'.", mod.Name), // Not L10N
                                                  string.Empty,
                                                  Resources.EditStaticModDlg_OkDialog_Continue),
                            MultiButtonMsgDlg.BUTTON_OK))
                    {
                        Modification = newMod;
                        DialogResult = DialogResult.OK;
                    }
                    return;
                }
            }

            var uniMod = UniMod.GetModification(name, IsStructural);

            // If the modification name is not found in Unimod, check if there exists a modification in Unimod that matches
            // the dialog modification, and prompt the user to to use the Unimod modification instead.
            if (uniMod == null)
            {
                var matchingMod = UniMod.FindMatchingStaticMod(newMod, IsStructural);
                if (matchingMod != null &&
                    (ModNameAvailable(matchingMod.Name) ||
                     (_editing && Equals(matchingMod.Name, Modification.Name))))
                {
                    var result = MultiButtonMsgDlg.Show(
                        this,
                        TextUtil.LineSeparate(Resources.EditStaticModDlg_OkDialog_There_is_a_Unimod_modification_with_the_same_settings,
                                              string.Empty,
                                              string.Format(Resources.EditStaticModDlg_OkDialog_Click__Unimod__to_use_the_name___0___, matchingMod.Name),
                                              string.Format(Resources.EditStaticModDlg_OkDialog_Click__Custom__to_use_the_name___0___, name)),
                        Resources.EditStaticModDlg_OkDialog_Unimod,
                        Resources.EditStaticModDlg_OkDialog_Custom,
                        true);
                    if (result == DialogResult.Yes)
                    {
                        newMod = matchingMod.MatchVariableAndLossInclusion(newMod);   // Unimod
                    }
                    if (result == DialogResult.Cancel)
                    {
                        return;
                    }
                }
            }
            else
            {
                // If the dialog modification matches the modification of the same name in Unimod,
                // use the UnimodId.
                if (newMod.Equivalent(uniMod))
                {
                    newMod = uniMod.MatchVariableAndLossInclusion(newMod);
                }
                else
                {
                    // Finally, if the modification name is found in Unimod, but the modification in Unimod does not
                    // match the dialog modification, prompt the user to use the Unimod modification definition instead.
                    if (DialogResult.OK != MultiButtonMsgDlg.Show(
                            this,
                            TextUtil.LineSeparate(string.Format(Resources.EditStaticModDlg_OkDialog_This_modification_does_not_match_the_Unimod_specifications_for___0___, name),
                                                  string.Empty,
                                                  Resources.EditStaticModDlg_OkDialog_Use_non_standard_settings_for_this_name),
                            MultiButtonMsgDlg.BUTTON_OK))
                    {
                        return;
                    }
                }
            }

            _modification = newMod;

            DialogResult = DialogResult.OK;
        }
示例#16
0
        public void OkDialog()
        {
            IrtType irtType = GetIrtType();

            if (textCalculatorName.Text.Length == 0)
            {
                MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_Calculator_name_cannot_be_empty);
                return;
            }
            if (_existing.Select(spec => spec.Name).Contains(textCalculatorName.Text))
            {
                var replaceResult = MultiButtonMsgDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_A_calculator_with_that_name_already_exists___Do_you_want_to_replace_it_,
                                                           MultiButtonMsgDlg.BUTTON_YES,
                                                           MultiButtonMsgDlg.BUTTON_NO,
                                                           false);
                if (replaceResult == DialogResult.No)
                {
                    return;
                }
            }
            if (irtType == IrtType.existing)
            {
                try
                {
                    if (!File.Exists(textOpenDatabase.Text))
                    {
                        MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_contain_a_path_to_a_valid_file_);
                        textOpenDatabase.Focus();
                        return;
                    }
                    var db = IrtDb.GetIrtDb(textOpenDatabase.Text, null);
                    if (db == null)
                    {
                        throw new DatabaseOpeningException(string.Format(Resources.CreateIrtCalculatorDlg_OkDialog_Cannot_read_the_database_file__0_, textOpenDatabase.Text));
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(this, string.Format(Resources.CreateIrtCalculatorDlg_OkDialog_Failed_to_open_the_database_file___0_, x.Message), x);
                    return;
                }
            }
            else if (irtType == IrtType.separate_list)
            {
                if (textNewDatabase.Text.Length == 0)
                {
                    MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_not_be_empty_);
                    textNewDatabase.Focus();
                    return;
                }
                if (!CreateIrtDatabase(textNewDatabase.Text))
                {
                    return;
                }
            }
            else
            {
                if (textNewDatabaseProteins.Text.Length == 0)
                {
                    MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_not_be_empty_);
                    textNewDatabaseProteins.Focus();
                    return;
                }
                if (comboBoxProteins.SelectedIndex == -1)
                {
                    MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_Please_select_a_protein_containing_the_list_of_standard_peptides_for_the_iRT_calculator_);
                    comboBoxProteins.Focus();
                    return;
                }
                if (!CreateIrtDatabase(textNewDatabaseProteins.Text))
                {
                    return;
                }
            }
            // Make a version of the document with the new calculator in it
            var databaseFileName = irtType == IrtType.existing ? textOpenDatabase.Text :
                                   irtType == IrtType.separate_list ? textNewDatabase.Text :
                                   textNewDatabaseProteins.Text;
            var calculator = new RCalcIrt(textCalculatorName.Text, databaseFileName);
            // CONSIDER: Probably can't use just a static default like 10 below
            var retentionTimeRegression = new RetentionTimeRegression(calculator.Name, calculator, null, null, RetentionTimeRegression.DEFAULT_WINDOW, new List <MeasuredRetentionTime>());
            var docNew = Document.ChangeSettings(Document.Settings.ChangePeptidePrediction(prediction =>
                                                                                           prediction.ChangeRetentionTime(retentionTimeRegression)));

            // Import transition list of standards, if applicable
            if (irtType == IrtType.separate_list)
            {
                try
                {
                    if (!File.Exists(textImportText.Text))
                    {
                        MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_Transition_list_field_must_contain_a_path_to_a_valid_file_);
                        return;
                    }
                    IdentityPath selectPath;
                    List <MeasuredRetentionTime>     irtPeptides;
                    List <TransitionImportErrorInfo> errorList;
                    var inputs = new MassListInputs(textImportText.Text);
                    docNew = docNew.ImportMassList(inputs, null, out selectPath, out irtPeptides, out _librarySpectra, out errorList);
                    if (errorList.Any())
                    {
                        throw new InvalidDataException(errorList[0].ErrorMessage);
                    }
                    _dbIrtPeptides = irtPeptides.Select(rt => new DbIrtPeptide(rt.PeptideSequence, rt.RetentionTime, true, TimeSource.scan)).ToList();
                    IrtFile        = textImportText.Text;
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(this, string.Format(Resources.CreateIrtCalculatorDlg_OkDialog_Error_reading_iRT_standards_transition_list___0_, x.Message), x);
                    return;
                }
            }
            else if (irtType == IrtType.protein)
            {
                PeptideGroupDocNode selectedGroup = comboBoxProteins.SelectedItem as PeptideGroupDocNode;
// ReSharper disable PossibleNullReferenceException
                _irtPeptideSequences = new HashSet <Target>(selectedGroup.Peptides.Select(pep => pep.ModifiedTarget));
// ReSharper restore PossibleNullReferenceException
            }
            Document     = docNew;
            DialogResult = DialogResult.OK;
        }
示例#17
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            string name;

            if (!helper.ValidateNameTextBox(textName, out name))
            {
                return;
            }

            if (_existing.Contains(en => !ReferenceEquals(_isolationScheme, en) && Equals(name, en.Name)))
            {
                helper.ShowTextBoxError(textName,
                                        Resources.EditIsolationSchemeDlg_OkDialog_The_isolation_scheme_named__0__already_exists, name);
                return;
            }

            if (rbUseResultsData.Checked)
            {
                double?precursorFilter = null;
                bool   filterMargin    = Equals(comboIsolationWidth.SelectedItem, IsolationWidthType.RESULTS_WITH_MARGIN);
                if (!Equals(comboIsolationWidth.SelectedItem, IsolationWidthType.RESULTS))
                {
                    double minFilt = filterMargin ? 0 : TransitionFullScan.MIN_PRECURSOR_MULTI_FILTER;
                    double maxFilt = filterMargin
                        ? TransitionFullScan.MAX_PRECURSOR_MULTI_FILTER_MARGIN
                        : TransitionFullScan.MAX_PRECURSOR_MULTI_FILTER;
                    double precFilt;
                    if (!helper.ValidateDecimalTextBox(textPrecursorFilterMz,
                                                       minFilt, maxFilt, out precFilt))
                    {
                        return;
                    }
                    precursorFilter = precFilt;
                }
                try
                {
                    _isolationScheme = new IsolationScheme(name, SpecialHandling, precursorFilter, null, filterMargin);
                }
                catch (InvalidDataException exception)
                {
                    MessageDlg.ShowException(this, exception);
                    return;
                }
            }
            else
            {
                // Validate prespecified windows.
                List <IsolationWindow> windowList;
                if ((windowList = GetIsolationWindows()) == null)
                {
                    return;
                }


                // Must be at least one window.
                if (windowList.Count == 0)
                {
                    _gridViewDriver.SelectCell(COLUMN_START, 0);
                    MessageDlg.Show(this,
                                    Resources
                                    .EditIsolationSchemeDlg_OkDialog_Specify_Start_and_End_values_for_at_least_one_isolation_window);
                    gridIsolationWindows.Focus();
                    _gridViewDriver.EditCell();
                    return;
                }

                int?windowsPerScan = null;
                if (Equals(SpecialHandling, IsolationScheme.SpecialHandlingType.MULTIPLEXED))
                {
                    int x;
                    if (!helper.ValidateNumberTextBox(textWindowsPerScan,
                                                      IsolationScheme.MIN_MULTIPLEXED_ISOLATION_WINDOWS,
                                                      IsolationScheme.MAX_MULTIPLEXED_ISOLATION_WINDOWS,
                                                      out x))
                    {
                        return;
                    }
                    windowsPerScan = x;
                }
                // Check for overlap and gaps
                var          sortedWindowList = windowList.OrderBy(o => o.Start).ToList();
                bool         gapsOk           = false;
                bool         overlapsOk       = false;
                bool         overlap          = Overlap;
                int          increment        = overlap ? 2 : 1;
                int          subtraction      = overlap ? 3 : 1;
                const double tolerance        = 0.0001;
                for (int i = 0; i < sortedWindowList.Count - subtraction; i += increment)
                {
                    for (int j = 0; j < increment; j++)
                    {
                        IsolationWindow current = sortedWindowList.ElementAt(i + j);
                        IsolationWindow next    = sortedWindowList.ElementAt(i + j + increment);
                        if (!gapsOk && next.Start - current.End > tolerance)
                        {
                            if (MultiButtonMsgDlg.Show(this,
                                                       Resources
                                                       .EditIsolationSchemeDlg_OkDialog_There_are_gaps_in_a_single_cycle_of_your_extraction_windows__Do_you_want_to_continue_,
                                                       MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false) !=
                                DialogResult.Yes)
                            {
                                return;
                            }
                            gapsOk = true;
                        }
                        else if (!overlapsOk && current.End - next.Start > tolerance)
                        {
                            if (MultiButtonMsgDlg.Show(this,
                                                       Resources.EditIsolationSchemeDlgOkDialogThereAreOverlapsContinue,
                                                       MultiButtonMsgDlg.BUTTON_YES,
                                                       MultiButtonMsgDlg.BUTTON_NO, false) != DialogResult.Yes)
                            {
                                return;
                            }
                            overlapsOk = true;
                        }
                    }
                }
                try
                {
                    _isolationScheme = new IsolationScheme(name, windowList, SpecialHandling, windowsPerScan);
                }
                catch (InvalidDataException exception)
                {
                    MessageDlg.ShowException(this, exception);
                    return;
                }
            }

            DialogResult = DialogResult.OK;
        }
示例#18
0
        /// <summary>
        /// UI for warning about unrecognized peptides in imported file
        /// </summary>
        /// <param name="parent"></param>
        /// <returns></returns>
        public bool UnrecognizedPeptidesCancel(IWin32Window parent)
        {
            const int itemsToShow = 10;
            var       peptides    = UnrecognizedPeptides.ToList();

            if (peptides.Any())
            {
                var sb = new StringBuilder();
                sb.AppendLine(peptides.Count == 1
                    ? Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following_peptide_in_the_peak_boundaries_file_was_not_recognized_
                    : string.Format(Resources.SkylineWindow_ImportPeakBoundaries_The_following__0__peptides_in_the_peak_boundaries_file_were_not_recognized__,
                                    peptides.Count));
                sb.AppendLine();
                int peptidesToShow = Math.Min(peptides.Count, itemsToShow);
                for (int i = 0; i < peptidesToShow; ++i)
                {
                    sb.AppendLine(peptides[i]);
                }
                if (peptidesToShow < peptides.Count)
                {
                    sb.AppendLine("..."); // Not L10N
                }
                sb.AppendLine();
                sb.Append(peptides.Count == 1
                    ? Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ignoring_this_peptide_
                    : Resources.SkylineWindow_ImportPeakBoundaries_Continue_peak_boundary_import_ignoring_these_peptides_);
                var dlgPeptides = MultiButtonMsgDlg.Show(parent, sb.ToString(), MultiButtonMsgDlg.BUTTON_OK);
                if (dlgPeptides == DialogResult.Cancel)
                {
                    return(false);
                }
            }
            var files = UnrecognizedFiles.ToList();

            if (files.Any())
            {
                var sb = new StringBuilder();
                sb.AppendLine(files.Count == 1
                    ? Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following_file_name_in_the_peak_boundaries_file_was_not_recognized_
                    : string.Format(Resources.SkylineWindow_ImportPeakBoundaries_The_following__0__file_names_in_the_peak_boundaries_file_were_not_recognized_,
                                    files.Count));
                sb.AppendLine();
                int filesToShow = Math.Min(files.Count, itemsToShow);
                for (int i = 0; i < filesToShow; ++i)
                {
                    sb.AppendLine(files[i]);
                }
                if (filesToShow < files.Count)
                {
                    sb.AppendLine("..."); // Not L10N
                }
                sb.AppendLine();
                sb.Append(files.Count == 1
                    ? Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ignoring_this_file_
                    : Resources.SkylineWindow_ImportPeakBoundaries_Continue_peak_boundary_import_ignoring_these_files_);
                var dlgFiles = MultiButtonMsgDlg.Show(parent, sb.ToString(), MultiButtonMsgDlg.BUTTON_OK);
                if (dlgFiles == DialogResult.Cancel)
                {
                    return(false);
                }
            }
            var charges = UnrecognizedChargeStates.ToList();

            if (charges.Any())
            {
                var sb = new StringBuilder();
                sb.AppendLine(files.Count == 1
                              ? Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following_peptide__file__and_charge_state_combination_was_not_recognized_
                              : string.Format(Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following__0__peptide__file__and_charge_state_combinations_were_not_recognized_,
                                              charges.Count()));
                sb.AppendLine();
                int chargesToShow = Math.Min(charges.Count, itemsToShow);
                for (int i = 0; i < chargesToShow; ++i)
                {
                    sb.AppendLine(charges[i].PrintLine(' ')); // Not L10N
                }
                if (chargesToShow < charges.Count)
                {
                    sb.AppendLine("..."); // Not L10N
                }
                sb.AppendLine();
                sb.Append(files.Count == 1
                    ? Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ignoring_these_charge_states_
                    : Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ignoring_this_charge_state_);
                var dlgFiles = MultiButtonMsgDlg.Show(parent, sb.ToString(), MultiButtonMsgDlg.BUTTON_OK);
                if (dlgFiles == DialogResult.Cancel)
                {
                    return(false);
                }
            }
            return(true);
        }
        public override void Delete()
        {
            if (null == BoundDataGridView)
            {
                return;
            }
            var selectedRows = GetSelectedRows <FoldChangeBindingSource.FoldChangeRow>(BoundDataGridView);

            if (!selectedRows.Any())
            {
                MessageDlg.Show(BoundDataGridView, GroupComparisonStrings.GroupComparisonViewContext_Delete_No_rows_are_selected);
                return;
            }
            var docNodes = new Dictionary <IdentityPath, SkylineDocNode>();

            foreach (var row in selectedRows)
            {
                if (row.Peptide != null)
                {
                    docNodes[row.Peptide.IdentityPath] = row.Peptide;
                }
                else
                {
                    docNodes[row.Protein.IdentityPath] = row.Protein;
                }
            }
            string message;

            if (docNodes.Count == 1)
            {
                var peptide = docNodes.Values.First() as Peptide;
                if (null != peptide)
                {
                    message = string.Format(GroupComparisonStrings.GroupComparisonViewContext_Delete_Are_you_sure_you_want_to_delete_the_peptide__0_, peptide);
                }
                else
                {
                    var protein = docNodes.Values.First() as Protein;
                    message = string.Format(GroupComparisonStrings.GroupComparisonViewContext_Delete_Are_you_sure_you_want_to_delete_the_protein__0_, protein);
                }
            }
            else
            {
                if (docNodes.Values.First() is Peptide)
                {
                    message = string.Format(GroupComparisonStrings.GroupComparisonViewContext_Delete_Are_you_sure_you_want_to_delete_these__0__peptides, docNodes.Count);
                }
                else
                {
                    message = string.Format(GroupComparisonStrings.GroupComparisonViewContext_Delete_Are_you_sure_you_want_to_delete_these__0__proteins, docNodes.Count);
                }
            }
            if (MultiButtonMsgDlg.Show(BoundDataGridView, message, Resources.OK) != DialogResult.OK)
            {
                return;
            }
            var identityPathsToDelete = new HashSet <IdentityPath>(docNodes.Keys);
            var skylineWindow         = ((SkylineDataSchema)DataSchema).SkylineWindow;

            if (null != skylineWindow)
            {
                skylineWindow.ModifyDocument(GroupComparisonStrings.GroupComparisonViewContext_Delete_Delete_items, doc => DeleteProteins(doc, identityPathsToDelete));
            }
        }
示例#20
0
        private bool GetPackages()
        {
            ICollection <string> downloadablePackages = new Collection <string>();
            ICollection <string> localPackages        = new Collection <string>();

            AssignPackagesToInstall(ref downloadablePackages, ref localPackages);

            IEnumerable <string> packagePaths = null;

            try
            {
                // download packages
                using (var waitDlg = new LongWaitDlg {
                    ProgressValue = 0
                })
                {
                    waitDlg.PerformWork(this, 500, longWaitBroker => packagePaths = DownloadPackages(longWaitBroker, downloadablePackages));
                }

                // separate packages
                ICollection <string> exePaths    = new Collection <string>();
                ICollection <string> sourcePaths = new Collection <string>();
                foreach (var package in (packagePaths == null) ? localPackages : packagePaths.Concat(localPackages))
                {
                    if (package.EndsWith(@".exe"))
                    {
                        exePaths.Add(package);
                    }
                    else
                    {
                        sourcePaths.Add(package);
                    }
                }

                // first install executable packages, if any
                if (exePaths.Count != 0)
                {
                    using (var waitDlg = new LongWaitDlg(null, false)
                    {
                        Message = Resources.PythonInstaller_GetPackages_Installing_Packages
                    })
                    {
                        waitDlg.PerformWork(this, 500, () => InstallExecutablePackages(exePaths));
                    }
                }

                // then install source paths, if any
                if (sourcePaths.Count != 0)
                {
                    // try and find the path to the pip package manager .exe
                    string pipPath = PythonUtil.GetPipPath(_version);

                    // if it can't be found, install it
                    if (pipPath == null || TestingPip)
                    {
                        DialogResult result = MultiButtonMsgDlg.Show(
                            this,
                            Resources.PythonInstaller_InstallPackages_Skyline_uses_the_Python_tool_setuptools_and_the_Python_package_manager_Pip_to_install_packages_from_source__Click_install_to_begin_the_installation_process_,
                            Resources.PythonInstaller_InstallPackages_Install);
                        if (result == DialogResult.OK && GetPip())
                        {
                            pipPath = PythonUtil.GetPipPath(_version);
                            MessageDlg.Show(this, Resources.PythonInstaller_InstallPackages_Pip_installation_complete_);
                        }
                        else
                        {
                            MessageDlg.Show(this, Resources.PythonInstaller_InstallPackages_Python_package_installation_cannot_continue__Canceling_tool_installation_);
                            return(false);
                        }
                    }

                    using (var waitDlg = new LongWaitDlg(null, false)
                    {
                        Message = Resources.PythonInstaller_GetPackages_Installing_Packages
                    })
                    {
                        waitDlg.PerformWork(this, 500, () => InstallSourcePackages(sourcePaths, pipPath));
                    }
                }
                MessageDlg.Show(this, Resources.PythonInstaller_GetPackages_Package_installation_completed_);
                return(true);
            }
            catch (TargetInvocationException ex)
            {
                if (ex.InnerException is ToolExecutionException)
                {
                    MessageDlg.ShowException(this, ex);
                    return(false);
                }
                throw;
            }
        }
示例#21
0
        public void OkDialog()
        {
            var reader           = new StringReader(textPeptides.Text);
            var standardPeptides = new List <DbIrtPeptide>();
            var invalidLines     = new List <string>();

            string line;

            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                // Skip blank lines
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }
                DbIrtPeptide peptide = null;
                var          target  = TargetResolver.ResolveTarget(line);
                if (target == null || !_dictSequenceToPeptide.TryGetValue(target, out peptide))  // CONSIDER(bspratt) - small molecule equivalent?
                {
                    invalidLines.Add(line);
                }
                standardPeptides.Add(peptide);
            }

            if (invalidLines.Count > 0)
            {
                string message;
                if (invalidLines.Count == 1)
                {
                    message = ModeUIAwareStringFormat(Resources.ChangeIrtPeptidesDlg_OkDialog_The_sequence__0__is_not_currently_in_the_database,
                                                      invalidLines[0]);
                    MessageBox.Show(this, message, Program.Name);
                }
                else
                {
                    message = TextUtil.LineSeparate(GetModeUIHelper().Translate(Resources.ChangeIrtPeptidesDlg_OkDialog_The_following_sequences_are_not_currently_in_the_database),
                                                    string.Empty,
                                                    TextUtil.LineSeparate(invalidLines),
                                                    string.Empty,
                                                    GetModeUIHelper().Translate(Resources.ChangeIrtPeptidesDlg_OkDialog_Standard_peptides_must_exist_in_the_database));
                    MessageBox.Show(this, message, Program.Name);
                }
                return;
            }

            ReplacementProtein = null;
            var selected = (ComboBoxProtein)comboProteins.SelectedItem;

            if (selected.IsNotNull)
            {
                var removedPeptides = selected.RemovedPeptides(TargetResolver, textPeptides.Lines).ToArray();
                if (removedPeptides.Any())
                {
                    switch (MultiButtonMsgDlg.Show(this, TextUtil.LineSeparate(
                                                       Resources.ChangeIrtPeptidesDlg_OkDialog_The_following_peptides_were_removed_,
                                                       TextUtil.LineSeparate(removedPeptides.Select(nodePep => nodePep.ModifiedSequenceDisplay)),
                                                       Resources.ChangeIrtPeptidesDlg_OkDialog_Would_you_like_to_remove_them_from_the_document_),
                                                   MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, true))
                    {
                    case DialogResult.Yes:
                        ReplacementProtein = selected.RemovePeptides(TargetResolver, textPeptides.Lines);
                        break;

                    case DialogResult.No:
                        break;

                    case DialogResult.Cancel:
                        return;
                    }
                }
            }

            _standardPeptides = standardPeptides.ToArray();

            DialogResult = DialogResult.OK;
        }
示例#22
0
        public void UploadSharedZipFile(Control parent, Server server, string zipFilePath, string folderPath)
        {
            Uri result = null;

            if (server == null)
            {
                return;
            }
            try
            {
                var isCanceled = false;
                using (var waitDlg = new LongWaitDlg {
                    Text = Resources.PublishDocumentDlg_UploadSharedZipFile_Uploading_File
                })
                {
                    waitDlg.PerformWork(parent, 1000, longWaitBroker =>
                    {
                        result = SendZipFile(server, folderPath,
                                             zipFilePath, longWaitBroker);
                        if (longWaitBroker.IsCanceled)
                        {
                            isCanceled = true;
                        }
                    });
                }
                if (!isCanceled) // if user not canceled
                {
                    String message = Resources.WebPanoramaPublishClient_UploadSharedZipFile_Publish_succeeded__would_you_like_to_view_the_file_in_Panorama_;
                    if (MultiButtonMsgDlg.Show(parent, message, MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false)
                        == DialogResult.Yes)
                    {
                        Process.Start(result.ToString());
                    }
                }
            }
            catch (Exception x)
            {
                var panoramaEx = x.InnerException as PanoramaImportErrorException;
                if (panoramaEx != null)
                {
                    var message = Resources.WebPanoramaPublishClient_UploadSharedZipFile_An_error_occured_while_publishing_to_Panorama__would_you_like_to_go_to_Panorama_;
                    if (MultiButtonMsgDlg.Show(parent, message, MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false)
                        == DialogResult.Yes)
                    {
                        Process.Start(panoramaEx.JobUrl.ToString());
                    }
                }
                else
                {
                    MessageDlg.ShowException(parent, x);
                }
            }

            // Change PanoramaUrl setting to the successful url used
            var uriString = server.GetKey() + folderPath;

            uriString = Uri.EscapeUriString(uriString);
            var window = parent as SkylineWindow;

            if (window != null && Uri.IsWellFormedUriString(uriString, UriKind.Absolute)) // cant do Uri.isWellFormed because of port and ip
            {
                window.ChangeDocPanoramaUri(new Uri(uriString));
            }
        }
示例#23
0
        public bool SetCalibrationPeptides()
        {
            CheckDisposed();
            var document = Program.ActiveDocumentUI;

            if (!document.Settings.HasResults)
            {
                MessageDlg.Show(this, Resources.CalibrateIrtDlg_UseResults_The_document_must_contain_results_to_calibrate_a_standard);
                return(false);
            }
            var targetResolver = TargetResolver.MakeTargetResolver(document);

            _gridViewDriver.TargetResolver = targetResolver;

            var docTargets = document.Molecules.Where(nodePep => nodePep.SchedulingTime.HasValue).Select(nodePep => nodePep.ModifiedTarget).Distinct().ToArray();
            var count      = docTargets.Length;

            // If calibrating against another standard, exclude peptides in that standard
            var excludePeps = SelectedRegressionOption?.MatchedRegressionPeptides?.Select(match => match.Item2.ModifiedTarget).ToHashSet();
            var exclude     = excludePeps != null && excludePeps.Count > 0;

            if (exclude)
            {
                docTargets = docTargets.Where(target => !excludePeps.Contains(target)).ToArray();
                count      = docTargets.Length;
            }

            if (count < MIN_STANDARD_PEPTIDES)
            {
                MessageDlg.Show(this,
                                ModeUIAwareStringFormat(!exclude
                            ? Resources.CalibrateIrtDlg_UseResults_The_document_contains_results_for__0__peptides__which_is_less_than_the_minimum_requirement_of__1__to_calibrate_a_standard_
                            : Resources.CalibrateIrtDlg_SetCalibrationPeptides_The_document_contains_results_for__0__peptide_s__not_in_this_standard__which_is_less_than_the_minimum_requirement_of__1__to_calibrate_a_standard_,
                                                        count, MIN_STANDARD_PEPTIDES));
                return(false);
            }
            else if (count < MIN_SUGGESTED_STANDARD_PEPTIDES)
            {
                if (MultiButtonMsgDlg.Show(this,
                                           ModeUIAwareStringFormat(!exclude
                                ? Resources.CalibrateIrtDlg_UseResults_The_document_contains_results_for__0__peptides__but_using_fewer_than__1__standard_peptides_is_not_recommended__Are_you_sure_you_want_to_continue_
                                : Resources.CalibrateIrtDlg_UseResults_The_document_contains_results_for__0__peptides_not_in_this_standard__but_using_fewer_than__1__standard_peptides_is_not_recommended__Are_you_sure_you_want_to_continue_,
                                                                   count, MIN_SUGGESTED_STANDARD_PEPTIDES),
                                           MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false) != DialogResult.Yes)
                {
                    return(false);
                }
            }
            else if (count > 20)
            {
                using (var dlg = new AddIrtStandardsDlg(count, excludePeps != null && excludePeps.Count > 0))
                {
                    if (dlg.ShowDialog(this) != DialogResult.OK)
                    {
                        return(false);
                    }
                    count = dlg.StandardCount;
                }
            }

            _gridViewDriver.Recalculate(document, count, SelectedRegressionOption, excludePeps);
            return(true);
        }
示例#24
0
        public void OkDialog()
        {
            var reader           = new StringReader(PeptidesText);
            var invalidLines     = new List <string>();
            var notFoundLines    = new List <string>();
            var acceptedPeptides = new List <LibraryKey>();
            var peptideSequences = GetPeptideSequences();

            string line;

            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }
                int foundAt;
                var charge = Transition.GetChargeFromIndicator(line,
                                                               TransitionGroup.MIN_PRECURSOR_CHARGE, TransitionGroup.MAX_PRECURSOR_CHARGE, out foundAt);
                if (!charge.IsEmpty)
                {
                    line = line.Substring(0, foundAt);
                }
                Target target;
                try
                {
                    // CONSIDER(bspratt) small molecule equivalent?
                    if (!FastaSequence.IsExSequence(line))
                    {
                        invalidLines.Add(line);
                        continue;
                    }
                    line   = SequenceMassCalc.NormalizeModifiedSequence(line);
                    target = new Target(line);
                }
                catch (Exception)
                {
                    invalidLines.Add(line);
                    continue;
                }

                if (!peptideSequences.ContainsKey(target))
                {
                    notFoundLines.Add(line);
                }
                else
                {
                    acceptedPeptides.Add(new LibKey(target, charge).LibraryKey);
                }
            }

            if (invalidLines.Count > 0)
            {
                if (invalidLines.Count == 1)
                {
                    MessageDlg.Show(this, string.Format(Resources.RefineListDlg_OkDialog_The_sequence__0__is_not_a_valid_peptide, invalidLines[0]));
                }
                else
                {
                    MessageDlg.Show(this, TextUtil.LineSeparate(Resources.RefineListDlg_OkDialog_The_following_sequences_are_not_valid_peptides, string.Empty, TextUtil.LineSeparate(invalidLines)));
                }
                return;
            }
            if (acceptedPeptides.Count == 0)
            {
                MessageDlg.Show(this, Resources.RefineListDlg_OkDialog_None_of_the_specified_peptides_are_in_the_document);
                return;
            }
            if (notFoundLines.Count > 0)
            {
                string message;
                if (notFoundLines.Count == 1)
                {
                    message = string.Format(Resources.RefineListDlg_OkDialog_The_peptide__0__is_not_in_the_document_Do_you_want_to_continue, notFoundLines[0]);
                }
                else if (notFoundLines.Count < 15)
                {
                    message = TextUtil.LineSeparate(Resources.RefineListDlg_OkDialog_The_following_peptides_are_not_in_the_document, string.Empty,
                                                    TextUtil.LineSeparate(notFoundLines), string.Empty,
                                                    Resources.RefineListDlg_OkDialog_Do_you_want_to_continue);
                }
                else
                {
                    message = string.Format(Resources.RefineListDlg_OkDialog_Of_the_specified__0__peptides__1__are_not_in_the_document_Do_you_want_to_continue,
                                            notFoundLines.Count + acceptedPeptides.Count, notFoundLines.Count);
                }
                if (MultiButtonMsgDlg.Show(this, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
                {
                    return;
                }
            }

            AcceptedPeptides = acceptedPeptides.ToArray();
            DialogResult     = DialogResult.OK;
        }
示例#25
0
        public void UseResults()
        {
            if (!_document.Settings.HasResults)
            {
                MessageDlg.Show(this, Resources.CalibrateIrtDlg_UseResults_The_document_must_contain_results_to_calibrate_a_standard);
                return;
            }

            var count = _document.Molecules.Where(nodePep => nodePep.SchedulingTime.HasValue).Select(nodePep => nodePep.ModifiedTarget).Distinct().Count();

            if (count < CalibrateIrtDlg.MIN_STANDARD_PEPTIDES)
            {
                MessageDlg.Show(this,
                                string.Format(
                                    Resources.CalibrateIrtDlg_UseResults_The_document_contains_results_for__0__peptides__which_is_less_than_the_minimum_requirement_of__1__to_calibrate_a_standard_,
                                    count, CalibrateIrtDlg.MIN_STANDARD_PEPTIDES));
                return;
            }
            else if (count < CalibrateIrtDlg.MIN_SUGGESTED_STANDARD_PEPTIDES)
            {
                if (MultiButtonMsgDlg.Show(this,
                                           string.Format(
                                               Resources.CalibrateIrtDlg_UseResults_The_document_contains_results_for__0__peptides__but_using_fewer_than__1__standard_peptides_is_not_recommended__Are_you_sure_you_want_to_continue_,
                                               count, CalibrateIrtDlg.MIN_SUGGESTED_STANDARD_PEPTIDES),
                                           MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false) != DialogResult.Yes)
                {
                    return;
                }
            }
            else if (count > 20)
            {
                using (var dlg = new AddIrtStandardsDlg(count, false))
                {
                    if (dlg.ShowDialog(this) != DialogResult.OK)
                    {
                        return;
                    }
                    count = dlg.StandardCount;
                }
            }

            if (!_picker.HasScoredPeptides)
            {
                using (var longWaitDlg = new LongWaitDlg {
                    Text = Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Calculating_scores
                })
                {
                    longWaitDlg.PerformWork(this, 1000, pm => _picker.ScorePeptides(_document, pm));
                    if (longWaitDlg.IsCanceled)
                    {
                        return;
                    }
                }
            }

            var useCirt = false;

            if (_picker.TryGetCirtRegression(count, out _, out _))
            {
                switch (MultiButtonMsgDlg.Show(this, string.Format(
                                                   Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_This_document_contains__0__CiRT_peptides__Would_you_like_to_use__1__of_them_as_your_iRT_standards_,
                                                   _picker.CirtPeptideCount, count), MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, true))
                {
                case DialogResult.Yes:
                    useCirt = true;
                    break;

                case DialogResult.No:
                    break;

                case DialogResult.Cancel:
                    return;
                }
            }

            comboProteins.SelectedIndex = 0;
            PeptideLines = _picker.Pick(count, null, useCirt).Select(pep => pep.Target.ToString()).ToArray();
        }
示例#26
0
        public static bool?OverwriteOrInParallel(Control parent,
                                                 string toolCollectionName,
                                                 string toolCollectionVersion,
                                                 List <ReportOrViewSpec> reportList,
                                                 string foundVersion,
                                                 string newCollectionName)
        {
            string message;
            string buttonText;

            if (toolCollectionName != null)
            {
                RelativeVersion relativeVersion = DetermineRelativeVersion(toolCollectionVersion, foundVersion);
                string          toolMessage;
                switch (relativeVersion)
                {
                case RelativeVersion.upgrade:
                    toolMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_currently_installed_, String.Empty,
                                                        String.Format(Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_upgrade_to__0__or_install_in_parallel_, foundVersion));
                    buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Upgrade;
                    break;

                case RelativeVersion.olderversion:
                    toolMessage =
                        TextUtil.LineSeparate(
                            String.Format(Resources.ConfigureToolsDlg_OverwriteOrInParallel_This_is_an_older_installation_v_0__of_the_tool__1_, foundVersion, @"{0}"),
                            String.Empty,
                            String.Format(Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_with_the_older_version__0__or_install_in_parallel_,
                                          foundVersion));
                    buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite;
                    break;

                case RelativeVersion.reinstall:
                    toolMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_already_installed_,
                                                        String.Empty,
                                                        Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_reinstall_or_install_in_parallel_);
                    buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Reinstall;
                    break;

                default:
                    toolMessage =
                        TextUtil.LineSeparate(
                            Resources.ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_in_conflict_with_the_new_installation,
                            String.Empty,
                            Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_or_install_in_parallel_);
                    buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite;     // Or update?
                    break;
                }
                message = String.Format(toolMessage, toolCollectionName);
            }
            else //Warn about overwritng report.
            {
                List <string> reportTitles = reportList.Select(sp => sp.GetKey()).ToList();

                string reportMultiMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_This_installation_would_modify_the_following_reports, String.Empty,
                                                                  @"{0}", String.Empty);
                string reportSingleMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_This_installation_would_modify_the_report_titled__0_, String.Empty);

                string reportMessage = reportList.Count == 1 ? reportSingleMessage : reportMultiMessage;
                string question      = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_or_install_in_parallel_;
                buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite;
                string reportMessageFormat = TextUtil.LineSeparate(reportMessage, question);
                message = String.Format(reportMessageFormat, TextUtil.LineSeparate(reportTitles));
            }

            DialogResult result = MultiButtonMsgDlg.Show(
                parent, message, buttonText, Resources.ConfigureToolsDlg_OverwriteOrInParallel_In_Parallel, true);

            switch (result)
            {
            case DialogResult.Cancel:
                return(null);

            case DialogResult.Yes:
                return(true);

            case DialogResult.No:
                return(false);
            }
            return(false);
        }
示例#27
0
        public void OkDialog()
        {
            bool isModel = radioButtonModel.Checked;

            if (isModel)
            {
                var model = _driverPeakScoringModel.SelectedItem;
                if (model == null)
                {
                    MessageDlg.Show(this, Resources.PeakBoundaryCompareTest_DoTest_Must_select_a_model_for_comparison_);
                    return;
                }
                if (!model.IsTrained)
                {
                    MessageDlg.Show(this, Resources.AddPeakCompareDlg_OkDialog_Model_must_be_trained_before_it_can_be_used_for_peak_boundary_comparison_);
                    return;
                }
                BoundaryComparer = new ComparePeakBoundaries(model);
            }
            else
            {
                string displayName = textName.Text;
                if (displayName.Length == 0)
                {
                    MessageDlg.Show(this, Resources.AddPeakCompareDlg_OkDialog_Comparison_name_cannot_be_empty_);
                    return;
                }
                string filePath = textFilePath.Text;
                if (filePath.Length == 0)
                {
                    MessageDlg.Show(this, Resources.AddPeakCompareDlg_OkDialog_File_path_cannot_be_empty_);
                    return;
                }
                if (!File.Exists(filePath))
                {
                    MessageDlg.Show(this, Resources.AddPeakCompareDlg_OkDialog_File_path_field_must_contain_a_path_to_a_valid_file_);
                    return;
                }
                BoundaryComparer = new ComparePeakBoundaries(displayName, filePath);
            }
            var compNames = _existing.Select(comp => comp.Name);

            if (compNames.Contains(BoundaryComparer.Name) && (_current == null || _current.Name != BoundaryComparer.Name))
            {
                var message = isModel
                    ? Resources.AddPeakCompareDlg_OkDialog_The_selected_model_is_already_included_in_the_list_of_comparisons__Please_choose_another_model_
                    : Resources.AddPeakCompareDlg_OkDialog_There_is_already_an_imported_file_with_the_current_name___Please_choose_another_name;
                MessageDlg.Show(this, message);
                return;
            }
            using (var longWaitDlg = new LongWaitDlg
            {
                Text = isModel ? Resources.AddPeakCompareDlg_OkDialog_Comparing_Models : Resources.AddPeakCompareDlg_OkDialog_Comparing_Imported_Files
            })
            {
                try
                {
                    longWaitDlg.PerformWork(this, 1000, pm => BoundaryComparer.GenerateComparison(Document, pm));
                    if (BoundaryComparer.Matches.Count == 0)
                    {
                        throw new IOException(Resources.AddPeakCompareDlg_OkDialog_Document_has_no_eligible_chromatograms_for_analysis___Valid_chromatograms_must_not_be_decoys_or_iRT_standards_);
                    }
                    if (BoundaryComparer.Matches.All(match => match.IsMissingPickedPeak))
                    {
                        throw new IOException(Resources.AddPeakCompareDlg_OkDialog_The_selected_file_or_model_does_not_assign_peak_boundaries_to_any_chromatograms_in_the_document___Please_select_a_different_model_or_file_);
                    }
                    if (BoundaryComparer.HasNoQValues && BoundaryComparer.HasNoScores)
                    {
                        throw new IOException(Resources.AddPeakCompareDlg_OkDialog_The_current_file_or_model_has_no_q_values_or_scores_to_analyze___Either_q_values_or_scores_are_necessary_to_compare_peak_picking_tools_);
                    }
                    if (BoundaryComparer.CountMissing > 0)
                    {
                        var missingMessage = string.Format(Resources.AddPeakCompareDlg_OkDialog_The_imported_file_does_not_contain_any_peak_boundaries_for__0__transition_group___file_pairs___These_chromatograms_will_be_treated_as_if_no_boundary_was_selected_,
                                                           BoundaryComparer.CountMissing);
                        var dlgMissing = MultiButtonMsgDlg.Show(this, missingMessage, MultiButtonMsgDlg.BUTTON_OK);
                        if (dlgMissing == DialogResult.Cancel)
                        {
                            return;
                        }
                    }
                    // Show a warning message and give a chance to cancel, if there are unrecognized peptides
                    if (BoundaryComparer.Importer != null && !BoundaryComparer.Importer.UnrecognizedPeptidesCancel(this))
                    {
                        return;
                    }
                }
                catch (Exception x)
                {
                    string initMessage = isModel
                        ? Resources.AddPeakCompareDlg_OkDialog_Error_comparing_model_peak_boundaries___0_
                        : Resources.AddPeakCompareDlg_OkDialog_Error_applying_imported_peak_boundaries___0_;
                    MessageDlg.ShowWithException(this, string.Format(initMessage, x.Message), x);
                    return;
                }
            }
            DialogResult = DialogResult.OK;
        }
示例#28
0
            private List <MeasuredPeptide> PickPeptides(SrmDocument doc, int count, ICollection <Target> exclude, RegressionOption currentRegression, out RegressionOption cirt)
            {
                cirt = null;

                if (!_picker.HasScoredPeptides)
                {
                    using (var longWaitDlg = new LongWaitDlg {
                        Text = Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Calculating_scores
                    })
                    {
                        longWaitDlg.PerformWork(_parent, 1000, pm => _picker.ScorePeptides(doc, pm));
                        if (longWaitDlg.IsCanceled)
                        {
                            return(null);
                        }
                    }
                }

                RegressionLine cirtRegression    = null;
                var            useCirt           = false;
                var            cirtUsePredefined = false;

                if (_picker.TryGetCirtRegression(count, out var tryCirtRegression, out var matchedPeptides))
                {
                    var currentIsCirt = currentRegression != null && currentRegression.IsCirtDiscovered;
                    switch (MultiButtonMsgDlg.Show(_parent, string.Format(
                                                       Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_This_document_contains__0__CiRT_peptides__Would_you_like_to_use__1__of_them_as_your_iRT_standards_,
                                                       _picker.CirtPeptideCount, count), MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, true))
                    {
                    case DialogResult.Yes:
                        cirtRegression = tryCirtRegression;
                        useCirt        = true;
                        if (currentRegression?.RegressionLine == null || currentIsCirt)
                        {
                            switch (MultiButtonMsgDlg.Show(_parent,
                                                           Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Would_you_like_to_use_the_predefined_iRT_values_,
                                                           Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Predefined_values,
                                                           Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Calculate_from_regression,
                                                           true))
                            {
                            case DialogResult.Yes:
                                cirtUsePredefined = true;
                                break;

                            case DialogResult.No:
                                break;

                            case DialogResult.Cancel:
                                return(null);
                            }
                        }
                        break;

                    case DialogResult.No:
                        if (currentIsCirt)
                        {
                            cirtRegression = tryCirtRegression;
                        }
                        break;

                    case DialogResult.Cancel:
                        return(null);
                    }
                }

                var bestPeptides = _picker.Pick(count, exclude, useCirt);

                if (cirtRegression != null)
                {
                    var standardPeptides = bestPeptides.Select(pep => new StandardPeptide
                    {
                        Irt           = cirtUsePredefined ? _picker.CirtIrt(pep.Target).Value : double.NaN,
                        RetentionTime = pep.RetentionTime,
                        Target        = pep.Target
                    }).ToList();
                    cirt = new RegressionOption(Resources.CalibrationGridViewDriver_CiRT_option_name, cirtRegression,
                                                matchedPeptides.ToList(), standardPeptides, false, false);
                }
                return(bestPeptides);
            }
示例#29
0
        private void populateListViewFromDirectory(MsDataFileUri directory)
        {
            _abortPopulateList = false;
            listView.Cursor    = Cursors.Default;
            _waitingForData    = false;
            listView.Items.Clear();

            var listSourceInfo = new List <SourceInfo>();

            if (null == directory || directory is MsDataFilePath && string.IsNullOrEmpty(((MsDataFilePath)directory).FilePath))
            {
                foreach (DriveInfo driveInfo in DriveInfo.GetDrives())
                {
                    string     label      = string.Empty;
                    string     sublabel   = driveInfo.Name;
                    ImageIndex imageIndex = ImageIndex.Folder;
                    _driveReadiness[sublabel] = false;
                    try
                    {
                        switch (driveInfo.DriveType)
                        {
                        case DriveType.Fixed:
                            imageIndex = ImageIndex.LocalDrive;
                            label      = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Local_Drive;
                            if (driveInfo.VolumeLabel.Length > 0)
                            {
                                label = driveInfo.VolumeLabel;
                            }
                            break;

                        case DriveType.CDRom:
                            imageIndex = ImageIndex.OpticalDrive;
                            label      = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Optical_Drive;
                            if (driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0)
                            {
                                label = driveInfo.VolumeLabel;
                            }
                            break;

                        case DriveType.Removable:
                            imageIndex = ImageIndex.OpticalDrive;
                            label      = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Removable_Drive;
                            if (driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0)
                            {
                                label = driveInfo.VolumeLabel;
                            }
                            break;

                        case DriveType.Network:
                            label = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Network_Share;
                            break;
                        }
                        _driveReadiness[sublabel] = IsDriveReady(driveInfo);
                    }
                    catch (Exception)
                    {
                        label += string.Format(@" ({0})", Resources.OpenDataSourceDialog_populateListViewFromDirectory_access_failure);
                    }

                    string name = driveInfo.Name;
                    if (label != string.Empty)
                    {
                        name = string.Format(@"{0} ({1})", label, name);
                    }

                    listSourceInfo.Add(new SourceInfo(new MsDataFilePath(driveInfo.RootDirectory.FullName))
                    {
                        type         = DataSourceUtil.FOLDER_TYPE,
                        imageIndex   = imageIndex,
                        name         = name,
                        dateModified = GetDriveModifiedTime(driveInfo)
                    });
                }
            }
            else if (directory is RemoteUrl)
            {
                RemoteUrl remoteUrl = directory as RemoteUrl;
                if (string.IsNullOrEmpty(remoteUrl.ServerUrl))
                {
                    foreach (var remoteAccount in _remoteAccounts)
                    {
                        listSourceInfo.Add(new SourceInfo(remoteAccount.GetRootUrl())
                        {
                            name       = remoteAccount.GetKey(),
                            type       = DataSourceUtil.FOLDER_TYPE,
                            imageIndex = ImageIndex.MyNetworkPlaces,
                        });
                    }
                }
                else
                {
                    RemoteAccount remoteAccount = GetRemoteAccount(remoteUrl);
                    if (RemoteSession == null || !Equals(remoteAccount, RemoteSession.Account))
                    {
                        RemoteSession = RemoteSession.CreateSession(remoteAccount);
                    }
                    RemoteServerException exception;
                    bool isComplete = _remoteSession.AsyncFetchContents(remoteUrl, out exception);
                    foreach (var item in _remoteSession.ListContents(remoteUrl))
                    {
                        var imageIndex = DataSourceUtil.IsFolderType(item.Type)
                            ? ImageIndex.Folder
                            : ImageIndex.MassSpecFile;
                        listSourceInfo.Add(new SourceInfo(item.MsDataFileUri)
                        {
                            name         = item.Label,
                            type         = item.Type,
                            imageIndex   = imageIndex,
                            dateModified = item.LastModified,
                            size         = item.FileSize
                        });
                    }
                    if (null != exception)
                    {
                        if (MultiButtonMsgDlg.Show(this, exception.Message, Resources.OpenDataSourceDialog_populateListViewFromDirectory_Retry) != DialogResult.Cancel)
                        {
                            RemoteSession.RetryFetchContents(remoteUrl);
                            isComplete = false;
                        }
                    }
                    if (!isComplete)
                    {
                        listView.Cursor = Cursors.WaitCursor;
                        _waitingForData = true;
                    }
                }
            }
            else if (directory is MsDataFilePath)
            {
                MsDataFilePath msDataFilePath = (MsDataFilePath)directory;
                DirectoryInfo  dirInfo        = new DirectoryInfo(msDataFilePath.FilePath);

                try
                {
                    // subitems: Name, Type, Spectra, Size, Date Modified
                    var arraySubDirInfo = dirInfo.GetDirectories();
                    Array.Sort(arraySubDirInfo, (d1, d2) => string.Compare(d1.Name, d2.Name, StringComparison.CurrentCultureIgnoreCase));
                    var arrayFileInfo = dirInfo.GetFiles();
                    Array.Sort(arrayFileInfo, (f1, f2) => string.Compare(f1.Name, f2.Name, StringComparison.CurrentCultureIgnoreCase));

                    // Calculate information about the files, allowing the user to cancel
                    foreach (var info in arraySubDirInfo)
                    {
                        listSourceInfo.Add(getSourceInfo(info));
                        Application.DoEvents();
                        if (_abortPopulateList)
                        {
                            //MessageBox.Show( "abort" );
                            break;
                        }
                    }

                    if (!_abortPopulateList)
                    {
                        foreach (var info in arrayFileInfo)
                        {
                            listSourceInfo.Add(getSourceInfo(info));
                            Application.DoEvents();
                            if (_abortPopulateList)
                            {
                                //MessageBox.Show( "abort" );
                                break;
                            }
                        }
                    }
                }
                catch (Exception x)
                {
                    var message = TextUtil.LineSeparate(
                        Resources.OpenDataSourceDialog_populateListViewFromDirectory_An_error_occurred_attempting_to_retrieve_the_contents_of_this_directory,
                        x.Message);
                    // Might throw access violation.
                    MessageDlg.ShowWithException(this, message, x);
                    return;
                }
            }

            // Populate the list
            var items = new List <ListViewItem>();

            foreach (var sourceInfo in listSourceInfo)
            {
                if (sourceInfo != null &&
                    (sourceTypeComboBox.SelectedIndex == 0 ||
                     sourceTypeComboBox.SelectedItem.ToString() == sourceInfo.type ||
                     // Always show folders
                     sourceInfo.isFolder))
                {
                    ListViewItem item = new ListViewItem(sourceInfo.ToArray(), (int)sourceInfo.imageIndex)
                    {
                        Tag = sourceInfo,
                    };
                    item.SubItems[2].Tag = sourceInfo.size;
                    item.SubItems[3].Tag = sourceInfo.dateModified;

                    items.Add(item);
                }
            }
            listView.Items.AddRange(items.ToArray());
        }
示例#30
0
        private bool CheckPassToolInternal(int toolIndex)
        {
            ToolDescription tool;

            if (toolIndex < ToolList.Count && toolIndex >= 0)
            {
                tool = ToolList[toolIndex];
            }
            else
            {
                return(true);
            }
            if (tool.Title == string.Empty)
            {
                MessageDlg.Show(this, Resources.ConfigureToolsDlg_CheckPassTool_You_must_enter_a_valid_title_for_the_tool);
                textTitle.Focus();
                return(false);
            }
            //Ensure the tool Title is unique.
            if (!IsUniqueTitle(tool.Title))
            {
                MessageDlg.Show(this, Resources.ConfigureToolsDlg_CheckPassToolInternal_Tool_titles_must_be_unique__please_enter_a_unique_title_for_this_tool_);
                textTitle.Focus();
                return(false);
            }

            if (tool.Command == string.Empty)
            {
                MessageDlg.Show(this, string.Format(Resources.ConfigureToolsDlg_CheckPassTool_The_command_cannot_be_blank__please_enter_a_valid_command_for__0_, tool.Title));
                textCommand.Focus();
                return(false);
            }
            if (tool.IsWebPage)
            {
                try
                {
// ReSharper disable ObjectCreationAsStatement
                    new Uri(tool.Command);
// ReSharper restore ObjectCreationAsStatement
                }
                catch (Exception)
                {
                    MessageDlg.Show(this, Resources.ConfigureToolsDlg_CheckPassToolInternal_Please_specify_a_valid_URL_);
                    textCommand.Focus();
                    return(false);
                }

                return(true);
            }
            //If it is not a $(ProgramPath()) macro then do other checks.
            if (ToolMacros.GetProgramPathContainer(tool.Command) == null)
            {
                string supportedTypes = String.Join("; ", EXTENSIONS); // Not L10N
                supportedTypes = supportedTypes.Replace(".", "*.");    // Not L10N
                if (!CheckExtension(tool.Command))
                {
                    MessageDlg.Show(this, string.Format(TextUtil.LineSeparate(
                                                            Resources.ConfigureToolsDlg_CheckPassTool_The_command_for__0__must_be_of_a_supported_type,
                                                            Resources.ConfigureToolsDlg_CheckPassTool_Supported_Types___1_,
                                                            Resources.ConfigureToolsDlg_CheckPassTool_if_you_would_like_the_command_to_launch_a_link__make_sure_to_include_http____or_https___),
                                                        tool.Title, supportedTypes));
                    textCommand.Focus();
                    return(false);
                }
                string adjustedCommand = tool.Command;
                if (adjustedCommand.Contains(ToolMacros.TOOL_DIR))
                {
                    if (String.IsNullOrEmpty(tool.ToolDirPath))
                    {
                        MessageDlg.Show(this,
                                        Resources.ConfigureToolsDlg_CheckPassToolInternal__ToolDir__is_not_a_valid_macro_for_a_tool_that_was_not_installed_and_therefore_does_not_have_a_Tool_Directory_);
                        textCommand.Focus();
                        return(false);
                    }
                    else
                    {
                        adjustedCommand = adjustedCommand.Replace(ToolMacros.TOOL_DIR, tool.ToolDirPath);
                    }
                }
                if (!File.Exists(adjustedCommand))
                {
                    if (DialogResult.Yes == MultiButtonMsgDlg.Show(
                            this,
                            string.Format(TextUtil.LineSeparate(
                                              Resources.ConfigureToolsDlg_CheckPassTool__The_command_for__0__may_not_exist_in_that_location__Would_you_like_to_edit_it__,
                                              Resources.ConfigureToolsDlg_CheckPassTool__Note__if_you_would_like_the_command_to_launch_a_link__make_sure_to_include_http____or_https___),
                                          tool.Title),
                            MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false))
                    {
                        textCommand.Focus();
                        return(false);
                    }
                }
            }

            if (tool.Arguments.Contains(ToolMacros.INPUT_REPORT_TEMP_PATH) && string.IsNullOrEmpty(tool.ReportTitle))
            {
                MessageDlg.Show(this, TextUtil.LineSeparate(
                                    string.Format(Resources.ConfigureToolsDlg_CheckPassToolInternal_You_have_provided__0__as_an_argument_but_have_not_selected_a_report_, ToolMacros.INPUT_REPORT_TEMP_PATH),
                                    string.Format(Resources.ConfigureToolsDlg_CheckPassToolInternal_Please_select_a_report_or_remove__0__from_arguments_, ToolMacros.INPUT_REPORT_TEMP_PATH)));
                comboReport.Focus();
                return(false);
            }
            return(true);
        }