public void MinimizeToFile(string targetFile, CacheFormat cacheFormat) { var targetSkydFile = ChromatogramCache.FinalPathForName(targetFile, null); using (var skydSaver = new FileSaver(targetSkydFile, true)) using (var scansSaver = new FileSaver(targetSkydFile + ChromatogramCache.SCANS_EXT, true)) using (var peaksSaver = new FileSaver(targetSkydFile + ChromatogramCache.PEAKS_EXT, true)) using (var scoreSaver = new FileSaver(targetSkydFile + ChromatogramCache.SCORES_EXT, true)) { var minimizer = Document.Settings.MeasuredResults.GetChromCacheMinimizer(Document); var settings = new ChromCacheMinimizer.Settings().ChangeCacheFormat(cacheFormat); var lockObject = new object(); ProgressMonitor.UpdateProgress(_progressStatus = _progressStatus.ChangeMessage(Resources.SrmDocumentSharing_MinimizeToFile_Writing_chromatograms)); minimizer.Minimize(settings, stats => { if (ProgressMonitor.IsCanceled) { throw new OperationCanceledException(); } lock (lockObject) { ProgressMonitor.UpdateProgress(_progressStatus = _progressStatus.ChangePercentComplete(stats.PercentComplete)); } }, skydSaver.FileStream, scansSaver.FileStream, peaksSaver.FileStream, scoreSaver.FileStream); skydSaver.Commit(); } }
public IrtDb AddPeptides(IProgressMonitor monitor, IList <DbIrtPeptide> newPeptides, ref IProgressStatus status) { var total = newPeptides.Count; var i = 0; using (var session = OpenWriteSession()) using (var transaction = session.BeginTransaction()) { foreach (var peptideNewDisconnected in newPeptides.Select(peptideNew => new DbIrtPeptide(peptideNew) { Id = null })) { session.SaveOrUpdate(peptideNewDisconnected); if (monitor != null) { if (monitor.IsCanceled) { return(null); } monitor.UpdateProgress(status = status.ChangePercentComplete(++i * 100 / total)); } } transaction.Commit(); } if (monitor != null) { monitor.UpdateProgress(status.Complete()); } return(ChangeProp(ImClone(this), im => im.LoadPeptides(newPeptides))); }
private static bool UpdatePrecentComplete(IProgressMonitor progressMonitor, int percentComplete, ref IProgressStatus progressStatus) { if (progressMonitor.IsCanceled) { progressMonitor.UpdateProgress(progressStatus.Cancel()); return(false); } if (progressStatus.PercentComplete != percentComplete) { progressMonitor.UpdateProgress(progressStatus = progressStatus.ChangePercentComplete(percentComplete)); } return(true); }
private bool UpdateProgress(int totalPeptideCount, int doneCount) { if (ProgressMonitor != null) { if (ProgressMonitor.IsCanceled) { return(false); } int progressValue = (doneCount) * 100 / totalPeptideCount; ProgressMonitor.UpdateProgress(_progressStatus = _progressStatus.ChangePercentComplete(progressValue)); } return(true); }
public void Run(ProcessStartInfo psi, string stdin, IProgressMonitor progress, ref IProgressStatus status, TextWriter writer) { if (shouldCancel) { status.Cancel(); progress.UpdateProgress(status = status.Cancel()); return; } if (!string.IsNullOrEmpty(stringToWriteToWriter)) { writer.WriteLine(stringToWriteToWriter); } status.ChangePercentComplete(100); progress.UpdateProgress(status); }
public bool Export(CancellationToken cancellationToken, IProgressMonitor progressMonitor, ref IProgressStatus status, ViewInfo viewInfo, TextWriter writer, DsvWriter dsvWriter) { progressMonitor = progressMonitor ?? new SilentProgressMonitor(); using (var bindingListSource = new BindingListSource(cancellationToken)) { bindingListSource.SetViewContext(this, viewInfo); progressMonitor.UpdateProgress(status = status.ChangePercentComplete(5) .ChangeMessage(Resources.ExportReportDlg_ExportReport_Writing_report)); WriteDataWithStatus(progressMonitor, ref status, writer, bindingListSource, dsvWriter); if (progressMonitor.IsCanceled) { return(false); } writer.Flush(); progressMonitor.UpdateProgress(status = status.Complete()); } return(true); }
private void SrmDocumentSharing_SaveProgress(object sender, SaveProgressEventArgs e) { if (ProgressMonitor != null) { if (ProgressMonitor.IsCanceled) { e.Cancel = true; return; } // TODO: More accurate total byte progress double percentCompressed = (e.TotalBytesToTransfer > 0 ? 1.0 * e.BytesTransferred / e.TotalBytesToTransfer : 0); int progressValue = (int)Math.Round((EntriesSaved + percentCompressed) * 100 / CountEntries); if (progressValue != _progressStatus.PercentComplete) { _progressStatus = _progressStatus.ChangePercentComplete(progressValue); if (e.CurrentEntry == null) { ProgressMonitor.UpdateProgress(_progressStatus = _progressStatus.ChangeMessage(DefaultMessage)); } else { if (!Equals(CurrentEntry, e.CurrentEntry.FileName)) { if (CurrentEntry != null) { EntriesSaved++; } CurrentEntry = e.CurrentEntry.FileName; } var message = string.Format(Resources.SrmDocumentSharing_SrmDocumentSharing_SaveProgress_Compressing__0__, e.CurrentEntry.FileName); ProgressMonitor.UpdateProgress(_progressStatus = _progressStatus.ChangeMessage(message)); } } } }
private bool Load(ILoadMonitor loader, IProgressStatus status, bool cached) { try { int loadPercent = 100; if (!cached) { // Building the cache will take 95% of the load time. loadPercent = 5; status = status.ChangeMessage(string.Format(Resources.XHunterLibrary_Load_Building_binary_cache_for__0__library, Path.GetFileName(FilePath))); status = status.ChangePercentComplete(0); loader.UpdateProgress(status); if (!CreateCache(loader, status, 100 - loadPercent)) { return(false); } } status = status.ChangeMessage(string.Format(Resources.XHunterLibrary_Load_Loading__0__library, Path.GetFileName(FilePath))); loader.UpdateProgress(status); var valueCache = new ValueCache(); var sm = loader.StreamManager; using (Stream stream = sm.CreateStream(CachePath, FileMode.Open, true)) { // Read library header from the end of the cache int countHeader = (int)LibHeaders.count * sizeof(int); stream.Seek(-countHeader, SeekOrigin.End); byte[] libHeader = new byte[countHeader]; ReadComplete(stream, libHeader, countHeader); int version = GetInt32(libHeader, (int)LibHeaders.format_version); if (version != FORMAT_VERSION_CACHE) { return(false); } int countRevisionBytes = GetInt32(libHeader, (int)LibHeaders.revision_byte_count); int countIdBytes = GetInt32(libHeader, (int)LibHeaders.id_byte_count); stream.Seek(-countHeader - countRevisionBytes - countIdBytes, SeekOrigin.End); Revision = ReadString(stream, countRevisionBytes); Id = ReadString(stream, countIdBytes); int numSpectra = GetInt32(libHeader, (int)LibHeaders.num_spectra); var libraryEntries = new XHunterSpectrumInfo[numSpectra]; // Seek to beginning of spectrum headers long locationHeaders = BitConverter.ToInt64(libHeader, ((int)LibHeaders.location_headers_lo) * sizeof(int)); stream.Seek(locationHeaders, SeekOrigin.Begin); for (int i = 0; i < numSpectra; i++) { int percent = (100 - loadPercent) + (i * loadPercent / numSpectra); if (status.PercentComplete != percent) { // Check for cancellation after each integer change in percent loaded. if (loader.IsCanceled) { loader.UpdateProgress(status.Cancel()); return(false); } // If not cancelled, update progress. loader.UpdateProgress(status = status.ChangePercentComplete(percent)); } // Read spectrum header LibKey key = LibKey.Read(valueCache, stream); long location = PrimitiveArrays.ReadOneValue <long>(stream); float processedIntensity = PrimitiveArrays.ReadOneValue <float>(stream); int numPeaks = PrimitiveArrays.ReadOneValue <int>(stream); float expect = PrimitiveArrays.ReadOneValue <float>(stream); libraryEntries[i] = new XHunterSpectrumInfo(key, processedIntensity, expect, (short)numPeaks, location); } // Checksum = checksum.ChecksumValue; SetLibraryEntries(libraryEntries); loader.UpdateProgress(status.Complete()); // Create the stream from which the spectra will be read CreateStream(loader); } return(true); } catch (InvalidDataException x) { if (!cached) { loader.UpdateProgress(status.ChangeErrorException(x)); } return(false); } catch (IOException x) { if (!cached) { loader.UpdateProgress(status.ChangeErrorException(x)); } return(false); } catch (Exception x) { if (!cached) { x = new Exception(string.Format(Resources.XHunterLibrary_Load_Failed_loading_library__0__, FilePath), x); loader.UpdateProgress(status.ChangeErrorException(x)); } return(false); } finally { if (ReadStream != null) { // Close the read stream to ensure we never leak it. // This only costs on extra open, the first time the // active document tries to read. try { ReadStream.CloseStream(); } catch (IOException) { } } } }
// ReSharper restore UnusedMember.Local private bool CreateCache(ILoadMonitor loader, IProgressStatus status, int percent) { var sm = loader.StreamManager; BufferedStream stream = new BufferedStream(CreateStream(loader), 32 * 1024); int version = 1; string id = string.Empty, revision = string.Empty; int size = ReadSize(stream); int i; if (size == 0) { version = 2; size = ReadSize(stream); const int countLibHeader = 256 - 8; byte[] libHeader = new byte[countLibHeader]; if (stream.Read(libHeader, 0, libHeader.Length) != libHeader.Length) { throw new InvalidDataException(Resources.XHunterLibrary_CreateCache_Data_truncation_in_library_header_File_may_be_corrupted); } for (i = 0; i < libHeader.Length; i++) { if (libHeader[i] == 0) { break; } } string header = Encoding.UTF8.GetString(libHeader, 0, i); Match match = REGEX_HEADER.Match(header); if (match.Success) { version = int.Parse(match.Groups[1].Value); id = match.Groups[2].Value; revision = match.Groups[3].Value; } } var setLibKeys = new HashSet <LibKey>(size); var libraryEntries = new List <XHunterSpectrumInfo>(size); const int countHeader = ((int)SpectrumHeaders2.count) * sizeof(int); byte[] specHeader = new byte[1024]; byte[] specSequence = new byte[1024]; i = 0; while (stream.Read(specHeader, 0, countHeader) == countHeader) { int percentComplete = (i++ *percent / size); if (status.PercentComplete != percentComplete) { // Check for cancellation after each integer change in percent loaded. if (loader.IsCanceled) { loader.UpdateProgress(status.Cancel()); return(false); } // If not cancelled, update progress. loader.UpdateProgress(status = status.ChangePercentComplete(percentComplete)); } int charge = (version == 1 ? GetInt32(specHeader, ((int)SpectrumHeaders1.charge)) : GetInt32(specHeader, ((int)SpectrumHeaders2.charge))); float i2 = (version == 1 ? GetSingle(specHeader, ((int)SpectrumHeaders1.i2)) : GetSingle(specHeader, ((int)SpectrumHeaders2.i2))); int seqLength = (version == 1 ? GetInt32(specHeader, ((int)SpectrumHeaders1.seq_len)) : GetInt32(specHeader, ((int)SpectrumHeaders2.seq_len))); float expect = (version == 1 ? 0.001f : GetSingle(specHeader, (int)SpectrumHeaders2.expect)); // Read sequence information ReadComplete(stream, specSequence, seqLength); specSequence[seqLength] = 0; short numPeaks = (short)ReadSize(stream); // Save spectrum location long location = stream.Position; // Read over spectrum int countPeaks = (sizeof(byte) + sizeof(float)) * numPeaks; stream.Seek(countPeaks, SeekOrigin.Current); // Skip spectrum // Read modifications int numMods = ReadSize(stream); string modifiedSequence = Encoding.UTF8.GetString(specSequence, 0, seqLength); if (numMods > 0) { StringBuilder sb = new StringBuilder(); ReadComplete(stream, specHeader, (4 + sizeof(double)) * numMods); int iLast = 0; double modTotal = 0; for (int j = 0; j < numMods; j++) { int iPos = GetInt32(specHeader, j * 3); double mod = BitConverter.ToDouble(specHeader, (j * 3 + 1) * 4); // X! Hunter allows multiple modifications on the same // residue. So, they need to be totaled, and assigned to a // single residue to allow them to match Skyline modification // settings. if (iPos > iLast) { if (modTotal != 0) { sb.Append(SequenceMassCalc.GetModDiffDescription(modTotal)); } sb.Append(Encoding.UTF8.GetString(specSequence, iLast, iPos - iLast)); modTotal = 0; } modTotal += mod; iLast = iPos; } if (modTotal != 0) { sb.Append(SequenceMassCalc.GetModDiffDescription(modTotal)); } sb.Append(Encoding.UTF8.GetString(specSequence, iLast, seqLength - iLast)); modifiedSequence = sb.ToString(); } // Skip over homologs (list of protein IDs and start positions from a FASTA // file used to generate the library) int numHomologs = ReadSize(stream); for (int j = 0; j < numHomologs; j++) { stream.Seek(ReadSize(stream) + 4, SeekOrigin.Current); } // These libraries should not have duplicates, but just in case. // Apparently, GPM libraries do contain redundancies, as we found // when a revision lost this test. var key = new LibKey(modifiedSequence, charge); if (setLibKeys.Add(key)) { libraryEntries.Add(new XHunterSpectrumInfo(key, i2, expect, numPeaks, location)); } } libraryEntries = FilterInvalidLibraryEntries(ref status, libraryEntries); using (FileSaver fs = new FileSaver(CachePath, sm)) using (Stream outStream = sm.CreateStream(fs.SafeName, FileMode.Create, true)) { foreach (var info in libraryEntries) { info.Key.Write(outStream); PrimitiveArrays.WriteOneValue(outStream, info.Location); PrimitiveArrays.WriteOneValue(outStream, info.ProcessedIntensity); PrimitiveArrays.WriteOneValue(outStream, info.NumPeaks); PrimitiveArrays.WriteOneValue(outStream, info.Expect); } byte[] revisionBytes = Encoding.UTF8.GetBytes(revision); outStream.Write(revisionBytes, 0, revisionBytes.Length); byte[] idBytes = Encoding.UTF8.GetBytes(id); outStream.Write(idBytes, 0, idBytes.Length); outStream.Write(BitConverter.GetBytes(revisionBytes.Length), 0, sizeof(int)); outStream.Write(BitConverter.GetBytes(idBytes.Length), 0, sizeof(int)); outStream.Write(BitConverter.GetBytes(FORMAT_VERSION_CACHE), 0, sizeof(int)); outStream.Write(BitConverter.GetBytes(libraryEntries.Count), 0, sizeof(int)); outStream.Write(BitConverter.GetBytes((long)0), 0, sizeof(long)); sm.Finish(outStream); fs.Commit(); sm.SetCache(FilePath, CachePath); } loader.UpdateProgress(status.Complete()); return(true); }
public void Run(ProcessStartInfo psi, string stdin, IProgressMonitor progress, ref IProgressStatus status, TextWriter writer) { // Make sure required streams are redirected. psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; _messageLog.Clear(); var proc = Process.Start(psi); if (proc == null) { throw new IOException(string.Format(@"Failure starting {0} command.", psi.FileName)); } if (stdin != null) { try { proc.StandardInput.Write(stdin); } finally { proc.StandardInput.Close(); } } var reader = new ProcessStreamReader(proc); StringBuilder sbError = new StringBuilder(); int percentLast = 0; string line; while ((line = reader.ReadLine(progress)) != null) { if (writer != null && !line.StartsWith(HideLinePrefix)) { writer.WriteLine(line); } if (progress == null || line.ToLowerInvariant().StartsWith(@"error")) { sbError.AppendLine(line); } else // if (progress != null) { if (progress.IsCanceled) { proc.Kill(); progress.UpdateProgress(status = status.Cancel()); return; } if (!string.IsNullOrEmpty(MessagePrefix) && line.StartsWith(MessagePrefix)) { _messageLog.Add(line.Substring(MessagePrefix.Length)); } else if (line.EndsWith(@"%")) { double percent; string[] parts = line.Split(' '); string percentPart = parts[parts.Length - 1]; if (double.TryParse(percentPart.Substring(0, percentPart.Length - 1), out percent)) { percentLast = (int)percent; status = status.ChangePercentComplete(percentLast); if (percent >= 100 && status.SegmentCount > 0) { status = status.NextSegment(); } progress.UpdateProgress(status); } } else if (StatusPrefix == null || line.StartsWith(StatusPrefix)) { // Remove prefix, if there is one. if (StatusPrefix != null) { line = line.Substring(StatusPrefix.Length); } status = status.ChangeMessage(line); progress.UpdateProgress(status); } } } proc.WaitForExit(); int exit = proc.ExitCode; if (exit != 0) { line = proc.StandardError.ReadLine(); if (line != null) { sbError.AppendLine(line); } if (sbError.Length == 0) { sbError.AppendLine(@"Error occurred running process."); } string processPath = Path.GetDirectoryName(psi.FileName)?.Length == 0 ? Path.Combine(Environment.CurrentDirectory, psi.FileName) : psi.FileName; // ReSharper disable LocalizableElement sbError.AppendFormat("\r\nCommand-line: {0} {1}\r\nWorking directory: {2}{3}", processPath, // ReSharper restore LocalizableElement string.Join(" ", proc.StartInfo.Arguments), psi.WorkingDirectory, stdin != null ? "\r\nStandard input:\r\n" + stdin : ""); throw new IOException(sbError.ToString()); } // Make to complete the status, if the process succeeded, but never // printed 100% to the console if (percentLast < 100) { status = status.ChangePercentComplete(100); if (status.SegmentCount > 0) { status = status.NextSegment(); } if (progress != null) { progress.UpdateProgress(status); } } }
public override Uri SendZipFile(Server server, string folderPath, string zipFilePath, IProgressMonitor progressMonitor) { _progressMonitor = progressMonitor; _progressStatus = new ProgressStatus(String.Empty); var zipFileName = Path.GetFileName(zipFilePath) ?? string.Empty; // Upload zip file to pipeline folder. using (_webClient = new NonStreamBufferingWebClient()) { _webClient.UploadProgressChanged += webClient_UploadProgressChanged; _webClient.UploadFileCompleted += webClient_UploadFileCompleted; _webClient.Headers.Add(HttpRequestHeader.Authorization, server.AuthHeader); var webDav = PanoramaUtil.Call(server.URI, "pipeline", folderPath, "getPipelineContainer", true); // Not L10N var webDavInfo = _webClient.UploadString(webDav, PanoramaUtil.FORM_POST, string.Empty); JObject jsonWebDavInfo = JObject.Parse(webDavInfo); string webDavUrl = (string)jsonWebDavInfo["webDavURL"]; // Not L10N // Upload Url minus the name of the zip file. var baseUploadUri = new Uri(server.URI, webDavUrl); // Use Uri.EscapeDataString instead of Uri.EscapleUriString. // The latter will not escape characters such as '+' or '#' var escapedZipFileName = Uri.EscapeDataString(zipFileName); var tmpUploadUri = new Uri(baseUploadUri, escapedZipFileName + ".part"); // Not L10N var uploadUri = new Uri(baseUploadUri, escapedZipFileName); lock (this) { // Write to a temp file first. This will be renamed after a successful upload or deleted if the upload is canceled. // Add a "Temporary" header so that LabKey marks this as a temporary file. // https://www.labkey.org/issues/home/Developer/issues/details.view?issueId=19220 _webClient.Headers.Add("Temporary", "T"); // Not L10N _webClient.UploadFileAsync(tmpUploadUri, "PUT", zipFilePath); // Not L10N // Wait for the upload to complete Monitor.Wait(this); } if (progressMonitor.IsCanceled) { // Delete the temporary file on the server progressMonitor.UpdateProgress( _progressStatus = _progressStatus.ChangeMessage( Resources.WebPanoramaPublishClient_SendZipFile_Deleting_temporary_file_on_server)); DeleteTempZipFile(tmpUploadUri, server.AuthHeader); return(null); } // Make sure the temporary file was uploaded to the server ConfirmFileOnServer(tmpUploadUri, server.AuthHeader); // Rename the temporary file _progressStatus = _progressStatus.ChangeMessage( Resources.WebPanoramaPublishClient_SendZipFile_Renaming_temporary_file_on_server); progressMonitor.UpdateProgress(_progressStatus); RenameTempZipFile(tmpUploadUri, uploadUri, server.AuthHeader); _progressStatus = _progressStatus.ChangeMessage(Resources.WebPanoramaPublishClient_SendZipFile_Waiting_for_data_import_completion___); progressMonitor.UpdateProgress(_progressStatus = _progressStatus.ChangePercentComplete(-1)); // Data must be completely uploaded before we can import. Uri importUrl = PanoramaUtil.Call(server.URI, "targetedms", folderPath, "skylineDocUploadApi"); // Not L10N // Need to tell server which uploaded file to import. var dataImportInformation = new NameValueCollection { // For now, we only have one root that user can upload to { "path", "./" }, // Not L10N { "file", zipFileName } // Not L10N }; byte[] responseBytes = _webClient.UploadValues(importUrl, PanoramaUtil.FORM_POST, dataImportInformation); // Not L10N string response = Encoding.UTF8.GetString(responseBytes); JToken importResponse = JObject.Parse(response); // ID to check import status. var details = importResponse["UploadedJobDetails"]; // Not L10N int rowId = (int)details[0]["RowId"]; // Not L10N Uri statusUri = PanoramaUtil.Call(server.URI, "query", folderPath, "selectRows", // Not L10N "query.queryName=job&schemaName=pipeline&query.rowId~eq=" + rowId); // Not L10N bool complete = false; // Wait for import to finish before returning. Uri result = null; while (!complete) { if (progressMonitor.IsCanceled) { return(null); } string statusResponse = _webClient.UploadString(statusUri, PanoramaUtil.FORM_POST, string.Empty); JToken jStatusResponse = JObject.Parse(statusResponse); JToken rows = jStatusResponse["rows"]; // Not L10N var row = rows.FirstOrDefault(r => (int)r["RowId"] == rowId); // Not L10N if (row == null) { continue; } string status = (string)row["Status"]; // Not L10N result = new Uri(server.URI, (string)row["_labkeyurl_Description"]); // Not L10N if (string.Equals(status, "ERROR")) // Not L10N { var jobUrl = new Uri(server.URI, (string)row["_labkeyurl_RowId"]); // Not L10N var e = new PanoramaImportErrorException(server.URI, jobUrl); progressMonitor.UpdateProgress( _progressStatus = _progressStatus.ChangeErrorException(e)); throw e; } complete = string.Equals(status, "COMPLETE"); // Not L10N } progressMonitor.UpdateProgress(_progressStatus.Complete()); return(result); } }
private bool Load(ILoadMonitor loader, IProgressStatus status, bool cached) { try { int loadPercent = 100; if (!cached) { // Building the cache will take 95% of the load time. loadPercent = 5; status = status.ChangeMessage(string.Format(Resources.XHunterLibrary_Load_Building_binary_cache_for__0__library, Path.GetFileName(FilePath))); status = status.ChangePercentComplete(0); loader.UpdateProgress(status); if (!CreateCache(loader, status, 100 - loadPercent)) { return(false); } } status = status.ChangeMessage(string.Format(Resources.XHunterLibrary_Load_Loading__0__library, Path.GetFileName(FilePath))); loader.UpdateProgress(status); var sm = loader.StreamManager; using (Stream stream = sm.CreateStream(CachePath, FileMode.Open, true)) { // Read library header from the end of the cache int countHeader = (int)LibHeaders.count * sizeof(int); stream.Seek(-countHeader, SeekOrigin.End); byte[] libHeader = new byte[countHeader]; ReadComplete(stream, libHeader, countHeader); int version = GetInt32(libHeader, (int)LibHeaders.format_version); if (version != FORMAT_VERSION_CACHE) { return(false); } int countRevisionBytes = GetInt32(libHeader, (int)LibHeaders.revision_byte_count); int countIdBytes = GetInt32(libHeader, (int)LibHeaders.id_byte_count); stream.Seek(-countHeader - countRevisionBytes - countIdBytes, SeekOrigin.End); Revision = ReadString(stream, countRevisionBytes); Id = ReadString(stream, countIdBytes); int numSpectra = GetInt32(libHeader, (int)LibHeaders.num_spectra); var setSequences = new Dictionary <LibSeqKey, bool>(numSpectra); var libraryEntries = new XHunterSpectrumInfo[numSpectra]; // Seek to beginning of spectrum headers long locationHeaders = BitConverter.ToInt64(libHeader, ((int)LibHeaders.location_headers_lo) * sizeof(int)); stream.Seek(locationHeaders, SeekOrigin.Begin); byte[] specSequence = new byte[1024]; byte[] specHeader = new byte[1024]; countHeader = (int)SpectrumCacheHeader.count * 4; for (int i = 0; i < numSpectra; i++) { int percent = (100 - loadPercent) + (i * loadPercent / numSpectra); if (status.PercentComplete != percent) { // Check for cancellation after each integer change in percent loaded. if (loader.IsCanceled) { loader.UpdateProgress(status.Cancel()); return(false); } // If not cancelled, update progress. loader.UpdateProgress(status = status.ChangePercentComplete(percent)); } // Read spectrum header ReadComplete(stream, specHeader, countHeader); int seqKeyHash = GetInt32(specHeader, ((int)SpectrumCacheHeader.seq_key_hash)); int seqKeyLength = GetInt32(specHeader, ((int)SpectrumCacheHeader.seq_key_length)); int charge = GetInt32(specHeader, ((int)SpectrumCacheHeader.charge)); if (charge == 0 || charge > TransitionGroup.MAX_PRECURSOR_CHARGE) { throw new InvalidDataException(Resources.XHunterLibrary_Load_Invalid_precursor_charge_found_File_may_be_corrupted); } float i2 = BitConverter.ToSingle(specHeader, ((int)SpectrumCacheHeader.i2) * 4); long location = BitConverter.ToInt64(specHeader, ((int)SpectrumCacheHeader.location_lo) * 4); int numPeaks = GetInt32(specHeader, ((int)SpectrumCacheHeader.num_peaks)); float expect = BitConverter.ToSingle(specHeader, ((int)SpectrumCacheHeader.expect) * 4); int seqLength = GetInt32(specHeader, (int)SpectrumCacheHeader.seq_len); // Read sequence information ReadComplete(stream, specSequence, seqLength); LibKey key = new LibKey(specSequence, 0, seqLength, charge); libraryEntries[i] = new XHunterSpectrumInfo(key, i2, expect, (short)numPeaks, location); if (seqKeyLength > 0) { LibSeqKey seqKey = new LibSeqKey(key, seqKeyHash, seqKeyLength); setSequences.Add(seqKey, true); } } // Checksum = checksum.ChecksumValue; _libraryEntries = libraryEntries; _setSequences = setSequences; loader.UpdateProgress(status.Complete()); // Create the stream from which the spectra will be read CreateStream(loader); } return(true); } catch (InvalidDataException x) { if (!cached) { loader.UpdateProgress(status.ChangeErrorException(x)); } return(false); } catch (IOException x) { if (!cached) { loader.UpdateProgress(status.ChangeErrorException(x)); } return(false); } catch (Exception x) { if (!cached) { x = new Exception(string.Format(Resources.XHunterLibrary_Load_Failed_loading_library__0__, FilePath), x); loader.UpdateProgress(status.ChangeErrorException(x)); } return(false); } finally { if (ReadStream != null) { // Close the read stream to ensure we never leak it. // This only costs on extra open, the first time the // active document tries to read. try { ReadStream.CloseStream(); } catch (IOException) { } } } }
// ReSharper restore LocalizableElement public static List <string> ConvertPilotFiles(IList <string> inputFiles, IProgressMonitor progress, IProgressStatus status) { string groupConverterExePath = null; var inputFilesPilotConverted = new List <string>(); for (int index = 0; index < inputFiles.Count; index++) { string inputFile = inputFiles[index]; if (!inputFile.EndsWith(BiblioSpecLiteBuilder.EXT_PILOT)) { inputFilesPilotConverted.Add(inputFile); continue; } string outputFile = Path.ChangeExtension(inputFile, BiblioSpecLiteBuilder.EXT_PILOT_XML); // Avoid re-converting files that have already been converted if (File.Exists(outputFile)) { // Avoid duplication, in case the user accidentally adds both .group and .group.xml files // for the same results if (!inputFiles.Contains(outputFile)) { inputFilesPilotConverted.Add(outputFile); } continue; } string message = string.Format(Resources.VendorIssueHelper_ConvertPilotFiles_Converting__0__to_xml, Path.GetFileName(inputFile)); int percent = index * 100 / inputFiles.Count; progress.UpdateProgress(status = status.ChangeMessage(message).ChangePercentComplete(percent)); if (groupConverterExePath == null) { var key = Registry.LocalMachine.OpenSubKey(KEY_PROTEIN_PILOT, false); if (key != null) { string proteinPilotCommandWithArgs = (string)key.GetValue(string.Empty); var proteinPilotCommandWithArgsSplit = // ReSharper disable LocalizableElement proteinPilotCommandWithArgs.Split(new[] { "\" \"" }, StringSplitOptions.RemoveEmptyEntries); // Remove " "%1" // ReSharper restore LocalizableElement string path = Path.GetDirectoryName(proteinPilotCommandWithArgsSplit[0].Trim(new[] { '\\', '\"' })); // Remove preceding " if (!string.IsNullOrEmpty(path)) { var groupFileExtractorPath = Path.Combine(path, EXE_GROUP_FILE_EXTRACTOR); if (File.Exists(groupFileExtractorPath)) { groupConverterExePath = groupFileExtractorPath; } else { var group2XmlPath = Path.Combine(path, EXE_GROUP2_XML); if (File.Exists(group2XmlPath)) { groupConverterExePath = group2XmlPath; } else { string errorMessage = string.Format(Resources.VendorIssueHelper_ConvertPilotFiles_Unable_to_find__0__or__1__in_directory__2____Please_reinstall_ProteinPilot_software_to_be_able_to_handle__group_files_, EXE_GROUP_FILE_EXTRACTOR, EXE_GROUP2_XML, path); throw new IOException(errorMessage); } } } } if (groupConverterExePath == null) { throw new IOException(Resources.VendorIssueHelper_ConvertPilotFiles_ProteinPilot_software__trial_or_full_version__must_be_installed_to_convert___group__files_to_compatible___group_xml__files_); } } // run group2xml // ReSharper disable LocalizableElement var argv = new[] { "XML", "\"" + inputFile + "\"", "\"" + outputFile + "\"" }; // ReSharper restore LocalizableElement var psi = new ProcessStartInfo(groupConverterExePath) { CreateNoWindow = true, UseShellExecute = false, // Common directory includes the directory separator // ReSharper disable once ConstantNullCoalescingCondition WorkingDirectory = Path.GetDirectoryName(groupConverterExePath) ?? string.Empty, Arguments = string.Join(@" ", argv.ToArray()), RedirectStandardError = true, RedirectStandardOutput = true, }; var sbOut = new StringBuilder(); var proc = new Process { StartInfo = psi }; proc.Start(); var reader = new ProcessStreamReader(proc); string line; while ((line = reader.ReadLine()) != null) { if (progress.IsCanceled) { proc.Kill(); throw new LoadCanceledException(status.Cancel()); } sbOut.AppendLine(line); } while (!proc.WaitForExit(200)) { if (progress.IsCanceled) { proc.Kill(); return(inputFilesPilotConverted); } } if (proc.ExitCode != 0) { throw new IOException(TextUtil.LineSeparate(string.Format(Resources.VendorIssueHelper_ConvertPilotFiles_Failure_attempting_to_convert_file__0__to__group_xml_, inputFile), string.Empty, sbOut.ToString())); } inputFilesPilotConverted.Add(outputFile); } progress.UpdateProgress(status.ChangePercentComplete(100)); return(inputFilesPilotConverted); }