Esempio n. 1
0
        public bool SaveTools()
        {
            if (CheckPassTool(PreviouslySelectedIndex))
            {
                // Figure out which tools have been removed and if a directory in the tools folder can be removed.
                // Check if we can delete any toolDirs based on the tools on the remove list.
                if (Removelist.Count > 0)
                {
                    var referencedPaths = ToolList.Where(t => !string.IsNullOrEmpty(t.ToolDirPath))
                                          .Select(t => t.ToolDirPath).ToArray();
                    foreach (var removeTool in Removelist)
                    {
                        if (!string.IsNullOrEmpty(removeTool.ToolDirPath) &&
                            Directory.Exists(removeTool.ToolDirPath) &&
                            !referencedPaths.Contains(removeTool.ToolDirPath))
                        {
                            DirectoryEx.SafeDelete(removeTool.ToolDirPath);
                        }
                    }
                }

                Settings.Default.ToolList = Properties.ToolList.CopyTools(ToolList);
                Unsaved    = false;
                Removelist = new List <ToolDescription>();
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 2
0
        private void ClearAllTools()
        {
            Settings.Default.ToolList.Clear();
            string toolsDir = ToolDescriptionHelpers.GetToolsDirectory();

            DirectoryEx.SafeDelete(toolsDir);
        }
Esempio n. 3
0
        /// <summary>
        /// Generate the list of Existing Reports that would be modified and the list of new reports
        /// </summary>
        private static List <ReportOrViewSpec> FindReportConflicts(DirectoryInfo toolInfDir, string tempToolPath, out List <ReportOrViewSpec> newReports)
        {
            var existingReports = new List <ReportOrViewSpec>();

            newReports = new List <ReportOrViewSpec>();
            foreach (FileInfo file in toolInfDir.GetFiles(@"*" + ReportSpecList.EXT_REPORTS))
            {
                List <ReportOrViewSpec> loadedItems;
                try
                {
                    using (var stream = File.OpenRead(file.FullName))
                    {
                        loadedItems = ReportSharing.DeserializeReportList(stream);
                    }
                }
                catch (Exception exception)
                {
                    DirectoryEx.SafeDelete(tempToolPath);
                    throw new IOException(
                              string.Format(Resources.SerializableSettingsList_ImportFile_Failure_loading__0__,
                                            file.FullName), exception);
                }
                var externalToolReports =
                    Settings.Default.PersistedViews.GetViewSpecList(PersistedViews.ExternalToolsGroup.Id);
                Dictionary <string, ViewSpec> allExistingReports = new Dictionary <string, ViewSpec>();
                if (externalToolReports != null)
                {
                    foreach (var viewSpec in externalToolReports.ViewSpecs)
                    {
                        allExistingReports[viewSpec.Name] = viewSpec;
                    }
                }
                foreach (var reportOrViewSpec in loadedItems)
                {
                    ViewSpec existingView;
                    if (allExistingReports.TryGetValue(reportOrViewSpec.GetKey(), out existingView))
                    {
                        if (!ReportSharing.AreEquivalent(reportOrViewSpec, new ReportOrViewSpec(existingView)))
                        {
                            existingReports.Add(reportOrViewSpec);
                        }
                        else
                        {
                            newReports.Add(reportOrViewSpec);
                        }
                    }
                    else
                    {
                        newReports.Add(reportOrViewSpec);
                    }
                }
                // We now have the list of Reports that would have a naming conflict.
            }
            return(existingReports);
        }
Esempio n. 4
0
        private static List <ReportOrViewSpec> GetReportsFromFiles(DirectoryInfo toolInfDir, string tempToolPath)
        {
            var srmSerialzer = new XmlSerializer(typeof(SrmDocument));
            var loadedItems  = new List <ReportOrViewSpec>();
            var skyrFiles    = toolInfDir.GetFiles(@"*" + ReportSpecList.EXT_REPORTS);

            if (skyrFiles.Length > 0)
            {
                foreach (FileInfo file in skyrFiles)
                {
                    try
                    {
                        using (var stream = File.OpenRead(file.FullName))
                        {
                            loadedItems.AddRange(ReportSharing.DeserializeReportList(stream));
                        }
                    }
                    catch (Exception exception)
                    {
                        DirectoryEx.SafeDelete(tempToolPath);
                        throw new IOException(
                                  string.Format(Resources.SerializableSettingsList_ImportFile_Failure_loading__0__,
                                                file.FullName), exception);
                    }
                }
            }
            else
            {
                foreach (FileInfo file in toolInfDir.GetFiles().Where(file => file.Extension.Equals(SrmDocument.EXT)))
                {
                    SrmDocument document;
                    try
                    {
                        using (var stream = File.OpenRead(file.FullName))
                        {
                            document = (SrmDocument)srmSerialzer.Deserialize(stream);
                        }
                    }
                    catch (Exception exception)
                    {
                        throw new IOException(string.Format(
                                                  Resources.SerializableSettingsList_ImportFile_Failure_loading__0__,
                                                  file.FullName), exception);
                    }

                    var reports = document.Settings.DataSettings.ViewSpecList.ViewSpecLayouts;
                    foreach (ViewSpecLayout report in reports)
                    {
                        loadedItems.Add(new ReportOrViewSpec(report));
                    }
                }
            }

            return(loadedItems);
        }
Esempio n. 5
0
        private static void CopyOldTools(string outerToolsFolderPath, ILongWaitBroker broker)
        {
            //Copy tools to a different folder then Directory.Move if successful.
            string tempOuterToolsFolderPath = string.Concat(outerToolsFolderPath, @"_installing");

            if (Directory.Exists(tempOuterToolsFolderPath))
            {
                DirectoryEx.SafeDelete(tempOuterToolsFolderPath);
                // Not sure this is necessay, but just to be safe
                if (Directory.Exists(tempOuterToolsFolderPath))
                {
                    throw new Exception(Resources.Program_CopyOldTools_Error_copying_external_tools_from_previous_installation);
                }
            }

            // Must create the tools directory to avoid ending up here again next time
            Directory.CreateDirectory(tempOuterToolsFolderPath);

            ToolList  toolList      = Settings.Default.ToolList;
            int       numTools      = toolList.Count;
            const int endValue      = 100;
            int       progressValue = 0;
            // ReSharper disable once UselessBinaryOperation (in case we decide to start at progress>0 for display purposes)
            int increment = (endValue - progressValue) / (numTools + 1);

            foreach (var tool in toolList)
            {
                string toolDirPath = tool.ToolDirPath;
                if (!string.IsNullOrEmpty(toolDirPath) && Directory.Exists(toolDirPath))
                {
                    string foldername = Path.GetFileName(toolDirPath);
                    string newDir     = Path.Combine(outerToolsFolderPath, foldername);
                    string tempNewDir = Path.Combine(tempOuterToolsFolderPath, foldername);
                    if (!Directory.Exists(tempNewDir))
                    {
                        DirectoryEx.DirectoryCopy(toolDirPath, tempNewDir, true);
                    }
                    tool.ToolDirPath          = newDir; // Update the tool to point to its new directory.
                    tool.ArgsCollectorDllPath = tool.ArgsCollectorDllPath.Replace(toolDirPath, newDir);
                }
                if (broker.IsCanceled)
                {
                    // Don't leave around a corrupted directory
                    DirectoryEx.SafeDelete(tempOuterToolsFolderPath);
                    return;
                }

                progressValue       += increment;
                broker.ProgressValue = progressValue;
            }
            Directory.Move(tempOuterToolsFolderPath, outerToolsFolderPath);
            Settings.Default.ToolList = ToolList.CopyTools(toolList);
        }
Esempio n. 6
0
        public void Extract(IProgressMonitor progressMonitor)
        {
            ProgressMonitor = progressMonitor;
            ProgressMonitor.UpdateProgress(_progressStatus = new ProgressStatus(DefaultMessage));

            var extractDir = ExtractDir(SharedPath);

            using (ZipFile zip = ZipFile.Read(SharedPath))
            {
                CountEntries = zip.Entries.Count;
                ExpectedSize = zip.Entries.Select(entry => entry.UncompressedSize).Sum();

                zip.ExtractProgress += SrmDocumentSharing_ExtractProgress;

                string documentName = FindSharedSkylineFile(zip);

                string parentDir = Path.GetDirectoryName(SharedPath);
                if (!string.IsNullOrEmpty(parentDir))
                {
                    extractDir = Path.Combine(parentDir, extractDir);
                }
                extractDir   = GetNonExistentDir(extractDir);
                DocumentPath = Path.Combine(extractDir, documentName);

                foreach (var entry in zip.Entries)
                {
                    if (ProgressMonitor.IsCanceled)
                    {
                        break;
                    }

                    try
                    {
                        entry.Extract(extractDir);

                        ExtractedSize += entry.UncompressedSize;
                    }
                    catch (Exception)
                    {
                        if (!ProgressMonitor.IsCanceled)
                        {
                            throw;
                        }
                    }
                }
            }

            if (ProgressMonitor.IsCanceled)
            {
                DirectoryEx.SafeDelete(extractDir);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Removes any old folders in the ToolDir that dont have tools associated with them
        /// For the case where we have used a dll and couldn't delete it in some past instance of Skyline.
        /// </summary>
        public static void CheckToolDirConsistency()
        {
            var referencedPaths = Settings.Default.ToolList.Where(t => !string.IsNullOrEmpty(t.ToolDirPath))
                                  .Select(t => t.ToolDirPath).ToArray();
            string toolsDir = ToolDescriptionHelpers.GetToolsDirectory();

            if (string.IsNullOrEmpty(toolsDir) || !Directory.Exists(toolsDir))
            {
                return;
            }
            foreach (var folder in Directory.EnumerateDirectories(toolsDir))
            {
                if (!referencedPaths.Contains(folder))
                {
                    DirectoryEx.SafeDelete(folder);
                }
            }
        }
Esempio n. 8
0
        public void Dispose()
        {
            if (_spillFiles != null)
            {
                string cachePath = null;
                for (int i = 0; i < _spillFiles.Length; i++)
                {
                    if (_spillFiles[i].FileName != null)
                    {
                        cachePath = _spillFiles[i].FileName;
                    }
                    _spillFiles[i].CloseStream();
                }

                if (cachePath != null)
                {
                    DirectoryEx.SafeDelete(Path.GetDirectoryName(cachePath));
                }
            }
        }
Esempio n. 9
0
        public void Dispose()
        {
            if (_spillFiles != null)
            {
                string cachePath = null;
                for (int i = 0; i < _spillFiles.Length; i++)
                {
                    var stream = _spillFiles[i].Stream;
                    if (stream != null)
                    {
                        cachePath = stream.Name;
                        stream.Dispose();
                    }
                }

                if (cachePath != null)
                {
                    DirectoryEx.SafeDelete(Path.GetDirectoryName(cachePath));
                }
            }
        }
Esempio n. 10
0
        private void BrukerTOFMethodTest()
        {
            const string brukerOutputMethodFilename = "RetTimeMassListFile.Method";

            RunUI(() => SkylineWindow.OpenFile(TestFilesDir.GetTestPath("Bovine_std_curated_seq_small2-trigger.sky")));
            string brukerActualMeth   = TestFilesDir.GetTestPath("brukermethodexport.m");
            string brukerExpectedMeth = TestFilesDir.GetTestPath("BrukerExpected.Method");
            string brukerTemplateMeth = TestFilesDir.GetTestPath("Bruker Template Scheduled Precursor List.m");

            WaitForDocumentLoaded();

            // Export PRM method unscheduled
            RunDlg <ExportMethodDlg>(() => SkylineWindow.ShowExportMethodDialog(ExportFileType.Method),
                                     exportMethodDlg =>
            {
                exportMethodDlg.InstrumentType = ExportInstrumentType.BRUKER_TOF;
                exportMethodDlg.ExportStrategy = ExportStrategy.Single;
                exportMethodDlg.SetTemplateFile(brukerTemplateMeth);
                exportMethodDlg.MethodType = ExportMethodType.Standard;
                Assert.IsTrue(exportMethodDlg.IsRunLengthVisible);
                Assert.IsFalse(exportMethodDlg.IsOptimizeTypeEnabled);
                exportMethodDlg.RunLength = 20;
                exportMethodDlg.OkDialog(brukerActualMeth);
            });

            Assert.IsTrue(Directory.Exists(brukerActualMeth));
            AssertEx.NoDiff(File.ReadAllText(brukerExpectedMeth), File.ReadAllText(Path.Combine(brukerActualMeth, brukerOutputMethodFilename)));
            DirectoryEx.SafeDelete(brukerActualMeth);

            // Export PRM method scheduled
            RunDlg <ExportMethodDlg>(() => SkylineWindow.ShowExportMethodDialog(ExportFileType.Method),
                                     exportMethodDlg =>
            {
                exportMethodDlg.InstrumentType = ExportInstrumentType.BRUKER_TOF;
                exportMethodDlg.ExportStrategy = ExportStrategy.Single;
                exportMethodDlg.SetTemplateFile(brukerTemplateMeth);
                exportMethodDlg.MethodType = ExportMethodType.Scheduled;
                Assert.IsFalse(exportMethodDlg.IsRunLengthVisible);
                Assert.IsFalse(exportMethodDlg.IsOptimizeTypeEnabled);
                exportMethodDlg.OkDialog(brukerActualMeth);
            });

            Assert.IsTrue(Directory.Exists(brukerActualMeth));
            brukerExpectedMeth = TestFilesDir.GetTestPath("BrukerExpectedSched.Method");
            AssertEx.NoDiff(File.ReadAllText(brukerExpectedMeth), File.ReadAllText(Path.Combine(brukerActualMeth, brukerOutputMethodFilename)));
            DirectoryEx.SafeDelete(brukerActualMeth);

            // Export PRM method scheduled error
            {
                RunUI(() => SkylineWindow.ModifyDocument("Remove RT prediction",
                                                         doc => doc.ChangeSettings(doc.Settings.ChangePeptidePrediction(predict => predict.ChangeRetentionTime(null)))));
                var exportMethodDlgError = ShowDialog <ExportMethodDlg>(() => SkylineWindow.ShowExportMethodDialog(ExportFileType.Method));
                RunUI(() =>
                {
                    exportMethodDlgError.InstrumentType = ExportInstrumentType.BRUKER_TOF;
                    exportMethodDlgError.ExportStrategy = ExportStrategy.Single;
                    exportMethodDlgError.SetTemplateFile(brukerTemplateMeth);
                });
                RunDlg <MessageDlg>(() => exportMethodDlgError.MethodType = ExportMethodType.Scheduled,
                                    dlg => dlg.CancelDialog());
                OkDialog(exportMethodDlgError, exportMethodDlgError.CancelDialog);
            }

            // Export DIA Method
            {
                var isoWindows = new IsolationScheme("Prespecified", new[]
                {
                    new IsolationWindow(500, 521, null, 0.5, 0.5),
                    new IsolationWindow(520, 541, null, 0.5, 0.5),
                    new IsolationWindow(540, 561, null, 0.5, 0.5),
                });

                RunUI(() => SkylineWindow.ModifyDocument("Add isolation window list",
                                                         doc => doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(full => full.ChangeAcquisitionMethod(FullScanAcquisitionMethod.DIA, isoWindows)))));
                var exportMethodDlgDia = ShowDialog <ExportMethodDlg>(() => SkylineWindow.ShowExportMethodDialog(ExportFileType.Method));

                RunUI(() =>
                {
                    exportMethodDlgDia.InstrumentType = ExportInstrumentType.BRUKER_TOF;
                    exportMethodDlgDia.ExportStrategy = ExportStrategy.Single;
                    exportMethodDlgDia.SetTemplateFile(brukerTemplateMeth);
                });

                RunDlg <MessageDlg>(() => exportMethodDlgDia.MethodType = ExportMethodType.Scheduled, dlg =>
                {
                    Assert.AreEqual(Resources.ExportMethodDlg_comboTargetType_SelectedIndexChanged_Scheduled_methods_are_not_yet_supported_for_DIA_acquisition, dlg.Message);
                    dlg.CancelDialog();
                });

                RunUI(() =>
                {
                    Assert.IsTrue(exportMethodDlgDia.IsRunLengthVisible);
                    exportMethodDlgDia.RunLength = 20;
                });
                OkDialog(exportMethodDlgDia, () => exportMethodDlgDia.OkDialog(brukerActualMeth));

                Assert.IsTrue(Directory.Exists(brukerActualMeth));
                brukerExpectedMeth = TestFilesDir.GetTestPath("BrukerExpectedDIA.Method");
                AssertEx.NoDiff(File.ReadAllText(brukerExpectedMeth), File.ReadAllText(Path.Combine(brukerActualMeth, brukerOutputMethodFilename)));
            }

            // Export DIA method error not prespecified
            {
                var isoResults = new IsolationScheme("Results (20)", 20.0);
                RunUI(() => SkylineWindow.ModifyDocument("Add results isolation scheme",
                                                         doc => doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(full => full.ChangeAcquisitionMethod(FullScanAcquisitionMethod.DIA, isoResults)))));

                var exportMethodDlgDia = ShowDialog <ExportMethodDlg>(() => SkylineWindow.ShowExportMethodDialog(ExportFileType.Method));

                RunUI(() =>
                {
                    exportMethodDlgDia.InstrumentType = ExportInstrumentType.BRUKER_TOF;
                    exportMethodDlgDia.ExportStrategy = ExportStrategy.Single;
                    exportMethodDlgDia.SetTemplateFile(brukerTemplateMeth);
                });

                RunDlg <MessageDlg>(exportMethodDlgDia.OkDialog, dlg =>
                {
                    Assert.AreEqual(Resources.ExportMethodDlg_OkDialog_The_DIA_isolation_list_must_have_prespecified_windows_, dlg.Message);
                    dlg.CancelDialog();
                });

                OkDialog(exportMethodDlgDia, exportMethodDlgDia.CancelDialog);
            }
        }
Esempio n. 11
0
        private void InstallUpdates(ICollection <ToolUpdateInfo> tools)
        {
            if (tools != null && tools.Count != 0 && !TestingDownloadOnly)
            {
                var failedUpdates     = new Dictionary <string, string>();
                var successfulUpdates = new Collection <string>();

                int installCount = 0;
                foreach (var tool in tools)
                {
                    labelOperation.Text =
                        string.Format(Resources.ToolUpdatesDlg_InstallUpdates_Installing_updates_to__0_,
                                      tool._packageName);

                    var  toolList        = ToolList.CopyTools(Settings.Default.ToolList);
                    bool exceptionThrown = false;
                    ToolInstaller.UnzipToolReturnAccumulator result = null;
                    try
                    {
                        result = _updateHelper.UnpackZipTool(tool.FilePath, new ToolInstallUI.InstallZipToolHelper(_parent.InstallProgram));
                    }
                    catch (ToolExecutionException x)
                    {
                        failedUpdates.Add(tool._packageName, x.Message);
                        exceptionThrown = true;
                    }
                    catch (IOException x)
                    {
                        failedUpdates.Add(tool._packageName,
                                          TextUtil.LineSeparate(string.Format(Resources.ConfigureToolsDlg_UnpackZipTool_Failed_attempting_to_extract_the_tool_from__0_,
                                                                              Path.GetFileName(tool.FilePath)), x.Message));
                        exceptionThrown = true;
                    }

                    progressBar.Value = Convert.ToInt32((((((double)++installCount) / tools.Count) * 100) / 2) + 50);

                    if (result == null)
                    {
                        // user cancelled
                        if (!exceptionThrown)
                        {
                            failedUpdates.Add(tool._packageName, Resources.ToolUpdatesDlg_InstallUpdates_User_cancelled_installation);
                        }

                        // reset tool list
                        Settings.Default.ToolList = toolList;
                        continue;
                    }

                    // tool was successfully updated
                    result.MessagesThrown.ForEach(message => MessageDlg.Show(this, message));
                    successfulUpdates.Add(tool._packageName);
                }

                // clean-up
                DirectoryEx.SafeDelete(ToolDir.FullName);

                progressBar.Value = 100;
                DisplayInstallSummary(successfulUpdates, failedUpdates);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Function for unpacking zipped External tools.
        /// </summary>
        /// <param name="pathToZip">Path to the zipped file that contains the tool and all its assicaited files.</param>
        /// <param name="unpackSupport"> Interface that implements required functions that are dependent on context.</param>
        /// <returns></returns>
        public static UnzipToolReturnAccumulator UnpackZipTool(string pathToZip, IUnpackZipToolSupport unpackSupport)
        {
            if (!Directory.Exists(pathToZip) && !File.Exists(pathToZip))
            {
                throw new FileNotFoundException(pathToZip);
            }

            //Removes any old folders that dont have Tools associated with them
            CheckToolDirConsistency();

            var    retval = new UnzipToolReturnAccumulator();
            string name   = Path.GetFileNameWithoutExtension(pathToZip);

            if (name == null)
            {
                throw new ToolExecutionException(Resources.ConfigureToolsDlg_unpackZipTool_Invalid_file_selected__No_tools_added_);
            }
            // This helps with zipfiles that have spaces in the titles.
            // Consider: We may want to add quotes around usages of the $(ToolDir) macro incase the Tool directory has spaces in one of its directory names.
            name = name.Replace(' ', '_');

            string outerToolsFolderPath = ToolDescriptionHelpers.GetToolsDirectory();

            if (string.IsNullOrEmpty(outerToolsFolderPath))
            {
                throw new ToolExecutionException(Resources.ConfigureToolsDlg_unpackZipTool_Error_unpacking_zipped_tools);
            }
            string tempFolderPath = Path.Combine(outerToolsFolderPath, @"Temp");

            var toolDir = new DirectoryInfo(tempFolderPath);

            if (!toolDir.Exists)
            {
                toolDir.Create();
            }

            // This naming conflict shouldn't happen. The temp file should be empty.
            // Consider: Try to delete the existing directory in the temp directory.
            string tempToolPath = Path.Combine(tempFolderPath, name);

            if (Directory.Exists(tempToolPath))
            {
                tempToolPath = DirectoryEx.GetUniqueName(tempToolPath);
            }

            using (new TemporaryDirectory(tempToolPath))
            {
                if (Directory.Exists(pathToZip))
                {
                    DirectoryCopy(pathToZip, tempToolPath);
                }
                else
                {
                    using (var zipFile = new ZipFile(pathToZip))
                    {
                        try
                        {
                            zipFile.ExtractAll(tempToolPath, ExtractExistingFileAction.OverwriteSilently);
                        }
                        catch (Exception)
                        {
                            throw new ToolExecutionException(Resources.ConfigureToolsDlg_unpackZipTool_There_is_a_naming_conflict_in_unpacking_the_zip__Tool_importing_canceled_);
                        }
                    }
                }

                var dirInfo = new DirectoryInfo(tempToolPath);
                if (!dirInfo.Exists)
                {
                    // Case where they try to load tools from an empty zipfile then the folder is never created.
                    dirInfo.Create();
                }

                var toolInfDir = new DirectoryInfo(Path.Combine(tempToolPath, TOOL_INF));
                if (!toolInfDir.Exists)
                {
                    throw new ToolExecutionException(TextUtil.LineSeparate(
                                                         Resources.ToolInstaller_UnpackZipTool_The_selected_zip_file_is_not_an_installable_tool_,
                                                         string.Format(Resources.ToolInstaller_UnpackZipTool_Error__It_does_not_contain_the_required__0__directory_, TOOL_INF)));
                }

                // Handle info.properties
                var toolInfo = GetToolInfo(toolInfDir, retval);

                if (!HandleAnnotations(unpackSupport.ShouldOverwriteAnnotations, toolInfDir))
                {
                    return(null);
                }

                HandleLegacyQuaSAR(toolInfo);

                var toolsToBeOverwritten = GetToolsToBeOverwritten(toolInfo.PackageIdentifier);

                List <ReportOrViewSpec> newReports;
                var existingReports = FindReportConflicts(toolInfDir, tempToolPath, out newReports);

                bool?overwrite = IsOverwrite(unpackSupport.ShouldOverwrite, toolsToBeOverwritten, existingReports, toolInfo);
                if (!overwrite.HasValue)
                {
                    // User canceled installation.
                    return(null);
                }
                string DirectoryToRemove = null;
                if (overwrite.Value)
                {
                    // Delete the tools and their containing folder
                    if (toolsToBeOverwritten.Count > 0)
                    {
                        foreach (var tool in toolsToBeOverwritten)
                        {
                            Settings.Default.ToolList.Remove(tool);
                        }
                        // The tools are all guarenteed to be from the same directory by GetToolsToBeOverwritten
                        // and all toolDescriptions in a directory come from the same installation
                        DirectoryToRemove = toolsToBeOverwritten.First().ToolDirPath;
                    }

                    // Overwrite all existing reports.
                    foreach (ReportOrViewSpec item in existingReports)
                    {
                        ReportSharing.SaveReport(PersistedViews.ExternalToolsGroup, item);
                    }
                }

                // Add all new reports.
                foreach (ReportOrViewSpec item in newReports)
                {
                    ReportSharing.SaveReport(PersistedViews.ExternalToolsGroup, item);
                }
                var reportRenameMapping = new Dictionary <string, string>();
                if (overwrite == false) // Dont overwrite so rename reports.
                {
                    // Deal with renaming reports!
                    foreach (ReportOrViewSpec item in existingReports)
                    {
                        string oldname = item.GetKey();
                        string newname = GetUniqueReportName(oldname);
                        reportRenameMapping.Add(oldname, newname);
                        ReportSharing.SaveReportAs(PersistedViews.ExternalToolsGroup, item, newname);
                    }
                }

                foreach (FileInfo file in toolInfDir.GetFiles(@"*.properties"))
                {
                    // We will replace the tool Directory value (null below) later when we know the import is sucessful.
                    AddToolFromProperties(file, retval, toolInfo, null, tempToolPath, reportRenameMapping);
                }

                // Check if we need to install a program
                if (retval.Installations.Count > 0)
                {
                    foreach (var ppc in retval.Installations.Keys)
                    {
                        string pathToPackageInstallScript = null;
                        if (ppc.ProgramName.Equals(@"R") && retval.Installations[ppc].Count != 0)
                        {
                            pathToPackageInstallScript = Path.Combine(tempToolPath, TOOL_INF, INSTALL_R_PACKAGES);
                            if (!File.Exists(pathToPackageInstallScript))
                            {
                                throw new ToolExecutionException(TextUtil.LineSeparate(string.Format(Resources.ToolInstaller_UnpackZipTool_Error__There_is_a_file_missing_the__0__zip, name),
                                                                                       string.Empty,
                                                                                       string.Format(Resources.ToolInstaller_UnpackZipTool_Tool_Uses_R_and_specifies_Packages_without_an__0__file_in_the_tool_inf_directory_, INSTALL_R_PACKAGES)));
                            }
                        }

                        string path = unpackSupport.InstallProgram(ppc, retval.Installations[ppc], pathToPackageInstallScript);
                        if (path == null)
                        {
                            // Cancel installation
                            return(null);
                        }
                        else if (path != string.Empty)
                        {
                            if (Settings.Default.ToolFilePaths.ContainsKey(ppc))
                            {
                                Settings.Default.ToolFilePaths.Remove(ppc);
                            }
                            Settings.Default.ToolFilePaths.Add(ppc, path);
                        }
                    }
                }
                // We don't decide the final toolDirPath until we make it to here.
                // This will require some fixing of the tooldir and path to dll in each of the tools in retval.validtoolsfound
                // It also enables us to not delete the tools from the tool list unless we have a sucessful installation.

                // Decide the permToolPath.
                if (DirectoryToRemove != null)
                {
                    DirectoryEx.SafeDelete(DirectoryToRemove);
                }

                // Final Directory Location.
                string permToolPath = DirectoryEx.GetUniqueName(Path.Combine(outerToolsFolderPath, name));

                foreach (var tool in retval.ValidToolsFound)
                {
                    tool.ToolDirPath = permToolPath;
                    if (!string.IsNullOrEmpty(tool.ArgsCollectorDllPath))
                    {
                        tool.ArgsCollectorDllPath = Path.Combine(permToolPath, tool.ArgsCollectorDllPath);
                    }
                    Settings.Default.ToolList.Add(tool);
                }

                if (retval.ValidToolsFound.Count != 0)
                {
                    Helpers.TryTwice(() => Directory.Move(tempToolPath, permToolPath));
                }
            }
            return(retval);
        }
Esempio n. 13
0
        public void WatersMultiReplicateTest()
        {
            var testFilesDir = new TestFilesDir(TestContext, ZIP_FILE);

            string      docPath;
            SrmDocument docOriginal    = InitWatersDocument(testFilesDir, out docPath);
            SrmDocument doc            = docOriginal;
            var         listCachePaths = new List <string>();

            using (var docContainer = new ResultsTestDocumentContainer(doc, docPath))
            {
                string extRaw = ExtensionTestContext.ExtWatersRaw;

                string[] replicatePaths =
                {
                    testFilesDir.GetTestPath("160109_Mix1_calcurve_070.mzML"),
                    testFilesDir.GetTestPath("160109_Mix1_calcurve_073.mzML"),
                    testFilesDir.GetTestPath("160109_Mix1_calcurve_075" + extRaw),
                    testFilesDir.GetTestPath("160109_Mix1_calcurve_078.mzML")
                };
                // Count peaks where higher concentration replicates show less area
                int outOfOrder = 0;
                foreach (string path in replicatePaths)
                {
                    var listChromatograms = new List <ChromatogramSet>();
                    if (doc.Settings.HasResults)
                    {
                        listChromatograms.AddRange(doc.Settings.MeasuredResults.Chromatograms);
                    }

                    string name = Path.GetFileNameWithoutExtension(path);
                    if (name != null)
                    {
                        name = name.Substring(name.Length - 12);
                    }
                    listChromatograms.Add(new ChromatogramSet(name, new[] { MsDataFileUri.Parse(path) }));
                    int len = listChromatograms.Count;

                    var docResults = doc.ChangeMeasuredResults(doc.Settings.MeasuredResults != null
                        ? doc.Settings.MeasuredResults.ChangeChromatograms(listChromatograms)
                        : new MeasuredResults(listChromatograms));
                    // Adding unloaded results should add a new null result.
                    foreach (var nodeTran in docResults.PeptideTransitions)
                    {
                        Assert.IsTrue(nodeTran.HasResults);
                        Assert.AreEqual(listChromatograms.Count, nodeTran.Results.Count);
                        Assert.IsTrue(nodeTran.Results[len - 1].IsEmpty);
                    }

                    Assert.IsTrue(docContainer.SetDocument(docResults, doc, true),
                                  string.Format("Failed adding results for {0}.", path));
                    docContainer.AssertComplete();
                    docResults = docContainer.Document;

                    Assert.IsTrue(docResults.Settings.MeasuredResults.IsLoaded);

                    var transOld = doc.PeptideTransitions.ToArray();
                    var transNew = docResults.PeptideTransitions.ToArray();
                    Assert.AreEqual(transOld.Length, transNew.Length);
                    int countPeaks = 0;
                    for (int i = 0; i < transNew.Length; i++)
                    {
                        // Make sure new peak was added to each transition
                        var nodeTranNew = transNew[i];
                        Assert.IsTrue(nodeTranNew.HasResults);
                        Assert.AreEqual(len, nodeTranNew.Results.Count);
                        var chromInfo = nodeTranNew.Results[len - 1][0];
                        Assert.IsNotNull(chromInfo);

                        if (!chromInfo.IsEmpty)
                        {
                            countPeaks++;
                        }

                        // Make sure previously loaded peaks did not change
                        for (int j = 0; j < len - 1; j++)
                        {
                            var chromInfoPrevious = transOld[i].Results[j][0];
                            Assert.AreSame(chromInfoPrevious, nodeTranNew.Results[j][0]);
                            if ((chromInfo.IsEmpty && !chromInfoPrevious.IsEmpty) ||
                                (!chromInfo.IsEmpty && chromInfoPrevious.Area >= chromInfo.Area))
                            {
                                outOfOrder++;
                            }
                        }
                    }
                    // Allow 2 missed peaks
                    Assert.IsTrue(countPeaks >= transNew.Length - (TestSmallMolecules ? 1 : 0) - 2);

                    // Check results calculations for peptides and groups
                    foreach (var nodePep in docResults.Peptides)
                    {
                        Assert.AreEqual(len, nodePep.Results.Count);
                        Assert.IsTrue(nodePep.HasResults);
                        var chromInfo = nodePep.Results[len - 1][0];
                        Assert.AreEqual(1, nodePep.Children.Count);
                        var nodeGroup = (TransitionGroupDocNode)nodePep.Children[0];
                        Assert.IsTrue(nodeGroup.HasResults);
                        Assert.AreEqual(len, nodeGroup.Results.Count);
                        var chromInfoGroup = nodeGroup.Results[len - 1][0];
                        Assert.IsTrue(chromInfoGroup.PeakCountRatio >= 0.5);
                        Assert.IsTrue(chromInfoGroup.RetentionTime.HasValue);
                        Assert.IsTrue(chromInfoGroup.Area.HasValue && chromInfoGroup.Area > 290);

                        Assert.AreEqual(chromInfo.RetentionTime, chromInfoGroup.RetentionTime);
                        Assert.AreEqual(chromInfo.PeakCountRatio, chromInfoGroup.PeakCountRatio);
                    }

                    doc = docResults;
                }

                Assert.AreEqual(13, outOfOrder, 1);

                // Remove the original data
                foreach (string path in replicatePaths)
                {
                    if (File.Exists(path))
                    {
                        FileEx.SafeDelete(path);
                    }
                    else
                    {
                        DirectoryEx.SafeDelete(path);
                    }
                }
                FileEx.SafeDelete(docPath);

                // Save the document
                string xmlSaved     = null;
                var    docPersisted = AssertEx.RoundTrip(doc, ref xmlSaved);
                Assert.IsTrue(!docPersisted.Settings.MeasuredResults.IsLoaded);
                // Make sure the persisted document round-trips.
                // The orginal doesn't because of changing precision in the results info.
                AssertEx.Serializable(docPersisted, AssertEx.DocumentCloned);

                // Make sure the loaded document has reasonable results info
                // before the cache files are loaded
                for (int i = 0; i < doc.Children.Count; i++)
                {
                    PeptideGroupDocNode nodePepGroup1 = (PeptideGroupDocNode)doc.Children[i];
                    if (TestSmallMolecules && nodePepGroup1.Name.Equals(SrmDocument.TestingNonProteomicMoleculeGroupName))
                    {
                        continue;
                    }
                    PeptideGroupDocNode nodePepGroup2 = (PeptideGroupDocNode)docPersisted.Children[i];
                    Assert.AreNotSame(nodePepGroup1, nodePepGroup2);
                    for (int j = 0; j < nodePepGroup1.Children.Count; j++)
                    {
                        PeptideDocNode nodePep1 = (PeptideDocNode)nodePepGroup1.Children[j];
                        PeptideDocNode nodePep2 = (PeptideDocNode)nodePepGroup2.Children[j];
                        Assert.AreNotSame(nodePep1, nodePep2);
                        Assert.AreEqual(nodePep1.Results.Count, nodePep2.Results.Count);
                        for (int k = 0; k < nodePep1.Results.Count; k++)
                        {
                            Assert.AreEqual(nodePep1.Results[k][0].PeakCountRatio, nodePep2.Results[k][0].PeakCountRatio);
                        }
                        for (int k = 0; k < nodePep1.Children.Count; k++)
                        {
                            TransitionGroupDocNode nodeGroup1 = (TransitionGroupDocNode)nodePep1.Children[k];
                            TransitionGroupDocNode nodeGroup2 = (TransitionGroupDocNode)nodePep2.Children[k];
                            Assert.AreNotSame(nodeGroup1, nodeGroup2);
                            Assert.AreEqual(nodeGroup1.Results.Count, nodeGroup2.Results.Count);
                            for (int l = 0; l < nodeGroup1.Results.Count; l++)
                            {
                                Assert.AreEqual(nodeGroup1.Results[l][0].PeakCountRatio,
                                                nodeGroup2.Results[l][0].PeakCountRatio);
                            }
                            for (int l = 0; l < nodeGroup1.Children.Count; l++)
                            {
                                TransitionDocNode nodeTran1 = (TransitionDocNode)nodeGroup1.Children[l];
                                TransitionDocNode nodeTran2 = (TransitionDocNode)nodeGroup2.Children[l];
                                Assert.AreNotSame(nodeTran1, nodeTran2);
                                Assert.AreEqual(nodeTran1.Results.Count, nodeTran2.Results.Count);
                                for (int m = 0; m < nodeTran1.Results.Count; m++)
                                {
                                    if (!nodeTran1.Results[m].IsEmpty && !nodeTran2.Results[m].IsEmpty)
                                    {
                                        Assert.AreEqual(nodeTran1.Results[m][0].IsEmpty, nodeTran2.Results[m][0].IsEmpty);
                                    }
                                    else
                                    {
                                        Assert.AreEqual(nodeTran1.Results[m], nodeTran2.Results[m]); // both null
                                    }
                                }
                            }
                        }
                    }
                }

                // Reload data from .skyd files
                Assert.IsTrue(docContainer.SetDocument(docPersisted, doc, true));
                docContainer.AssertComplete();
                doc = docContainer.Document;

                var         results   = doc.Settings.MeasuredResults;
                const float tolerance = (float)TransitionInstrument.DEFAULT_MZ_MATCH_TOLERANCE;
                foreach (var pair in doc.PeptidePrecursorPairs)
                {
                    foreach (var chromSet in results.Chromatograms)
                    {
                        ChromatogramGroupInfo[] chromGroupInfo;
                        Assert.IsTrue(results.TryLoadChromatogram(chromSet, pair.NodePep, pair.NodeGroup,
                                                                  tolerance, true, out chromGroupInfo));
                    }
                }

                // The single final cache path should be open now
                listCachePaths.AddRange(doc.Settings.MeasuredResults.CachePaths);
                // Should only have one cache file at this point
                Assert.AreEqual(1, listCachePaths.Count);
                foreach (var cachePath in listCachePaths)
                {
                    // Attempting to delete should throw
                    string path = cachePath;
                    AssertEx.ThrowsException <IOException>(() => FileEx.SafeDelete(path));
                }
            }

            foreach (var cachePath in listCachePaths)
            {
                // Cache files should be closed now, and delete successfully.
                FileEx.SafeDelete(cachePath);
            }
            testFilesDir.Dispose();
        }