public static void Write(StudyXmlMemento theMemento, Stream theStream) { if (theMemento.RootNode != null) { var sw = new StreamWriter(theStream, Encoding.UTF8); sw.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); theMemento.RootNode.WriteTo(sw); sw.Flush(); } else { var xmlSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, ConformanceLevel = ConformanceLevel.Document, Indent = false, NewLineOnAttributes = false, CheckCharacters = true, IndentChars = string.Empty }; XmlWriter tw = XmlWriter.Create(theStream, xmlSettings); theMemento.Document.WriteTo(tw); tw.Flush(); tw.Close(); } }
public static void Write(StudyXmlMemento theMemento, string filename) { if (theMemento.RootNode != null) { using (var fs = FileStreamOpener.OpenForSoleUpdate(filename, FileMode.CreateNew)) { Write(theMemento, fs); } } else { var xmlSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, ConformanceLevel = ConformanceLevel.Document, Indent = false, NewLineOnAttributes = false, CheckCharacters = true, IndentChars = string.Empty }; XmlWriter tw = XmlWriter.Create(filename, xmlSettings); theMemento.Document.WriteTo(tw); tw.Flush(); tw.Close(); } }
/// <summary> /// Load the first instance from the first series of the StudyXml file for a study. /// </summary> /// <param name="location">The storage location of the study.</param> /// <returns></returns> protected static DicomFile LoadInstance(StudyStorageLocation location) { string studyXml = Path.Combine(location.GetStudyPath(), location.StudyInstanceUid + ".xml"); if (!File.Exists(studyXml)) { return null; } FileStream stream = FileStreamOpener.OpenForRead(studyXml, FileMode.Open); var theMemento = new StudyXmlMemento(); StudyXmlIo.Read(theMemento, stream); stream.Close(); stream.Dispose(); var xml = new StudyXml(); xml.SetMemento(theMemento); IEnumerator<SeriesXml> seriesEnumerator = xml.GetEnumerator(); if (seriesEnumerator.MoveNext()) { SeriesXml seriesXml = seriesEnumerator.Current; IEnumerator<InstanceXml> instanceEnumerator = seriesXml.GetEnumerator(); if (instanceEnumerator.MoveNext()) { InstanceXml instance = instanceEnumerator.Current; var file = new DicomFile("file.dcm",new DicomAttributeCollection(), instance.Collection) {TransferSyntax = instance.TransferSyntax}; return file; } } return null; }
/// <summary> /// Get an XML document representing the <see cref="StudyXml"/>. /// </summary> /// <remarks> /// This method can be called multiple times as DICOM SOP Instances are added /// to the <see cref="StudyXml"/>. Note that caching is done of the /// XmlDocument to improve performance. If the collections in the InstanceStreams /// are modified, the caching mechanism may cause the updates not to be contained /// in the generated XmlDocument. /// </remarks> /// <returns></returns> public StudyXmlMemento GetMemento(StudyXmlOutputSettings settings) { var memento = new StudyXmlMemento(); if (_doc == null) { _doc = new XmlDocument(); } else { _doc.RemoveAll(); } memento.Document = _doc; if (settings.OptimizedMemento) { memento.RootNode = new StudyXmlMemento.StudyXmlNode { ElementName = "ClearCanvasStudyXml", }; var studyElement = new StudyXmlMemento.StudyXmlNode { ElementName = "Study", }; studyElement.AddAttribute("UID", _studyInstanceUid); memento.RootNode.AddChild(studyElement); foreach (SeriesXml series in this) { var seriesElement = series.GetMemento(memento, settings); studyElement.AddChild(seriesElement); } } else { XmlElement clearCanvas = _doc.CreateElement("ClearCanvasStudyXml"); XmlElement study = _doc.CreateElement("Study"); XmlAttribute studyInstanceUid = _doc.CreateAttribute("UID"); studyInstanceUid.Value = _studyInstanceUid; study.Attributes.Append(studyInstanceUid); foreach (SeriesXml series in this) { XmlElement seriesElement = series.GetMemento(_doc, settings); study.AppendChild(seriesElement); } clearCanvas.AppendChild(study); _doc.AppendChild(clearCanvas); } return(memento); }
/// <summary> /// Apply the rules. /// </summary> /// <remarks> /// When rules are applied, we are simply adding new <see cref="ServerDatabaseCommand"/> instances /// for the rules to the currently executing <see cref="ServerCommandProcessor"/>. They will be /// executed after all other rules have been executed. /// </remarks> protected override void OnExecute(CommandProcessor theProcessor) { string studyXmlFile = Path.Combine(_directory, String.Format("{0}.xml", _studyInstanceUid)); StudyXml theXml = new StudyXml(_studyInstanceUid); if (File.Exists(studyXmlFile)) { using (Stream fileStream = FileStreamOpener.OpenForRead(studyXmlFile, FileMode.Open)) { var theMemento = new StudyXmlMemento(); StudyXmlIo.Read(theMemento, fileStream); theXml.SetMemento(theMemento); fileStream.Close(); } } else { string errorMsg = String.Format("Unable to load study XML file of restored study: {0}", studyXmlFile); Platform.Log(LogLevel.Error, errorMsg); throw new ApplicationException(errorMsg); } DicomFile defaultFile = null; bool rulesExecuted = false; foreach (SeriesXml seriesXml in theXml) { foreach (InstanceXml instanceXml in seriesXml) { // Skip non-image objects if (instanceXml.SopClass.Equals(SopClass.KeyObjectSelectionDocumentStorage) || instanceXml.SopClass.Equals(SopClass.GrayscaleSoftcopyPresentationStateStorageSopClass) || instanceXml.SopClass.Equals(SopClass.BlendingSoftcopyPresentationStateStorageSopClass) || instanceXml.SopClass.Equals(SopClass.ColorSoftcopyPresentationStateStorageSopClass)) { // Save the first one encountered, just in case the whole study is non-image objects. if (defaultFile == null) defaultFile = new DicomFile("test", new DicomAttributeCollection(), instanceXml.Collection); continue; } DicomFile file = new DicomFile("test", new DicomAttributeCollection(), instanceXml.Collection); _context.Message = file; _engine.Execute(_context); rulesExecuted = true; break; } if (rulesExecuted) break; } if (!rulesExecuted && defaultFile != null) { _context.Message = defaultFile; _engine.Execute(_context); } }
public static void Read(StudyXmlMemento theMemento, Stream theStream) { if (theMemento.Document == null) { theMemento.Document = new XmlDocument(); } theMemento.Document.Load(theStream); }
internal StudyXmlMemento.StudyXmlNode GetMemento(StudyXmlMemento theDocument, StudyXmlOutputSettings settings) { _dirty = false; // Calc the base attributes CalculateBaseCollectionForSeries(); var seriesElement = new StudyXmlMemento.StudyXmlNode { ElementName = "Series" }; seriesElement.AddAttribute("UID", _seriesInstanceUid); // If there's only 1 total image in the series, leave an empty base instance // and just have the entire image be stored. if (_instanceList.Count > 1) { if (!string.IsNullOrEmpty(_seriesTagsStream.XmlFragment)) { seriesElement.AddChild(new StudyXmlMemento.StudyXmlNode(_seriesTagsStream.XmlFragment)); } else { XmlElement baseElement = theDocument.Document.CreateElement("BaseInstance"); XmlElement baseInstance = _seriesTagsStream.GetMemento(theDocument.Document, settings); baseElement.AppendChild(baseInstance); var baseNode = new StudyXmlMemento.StudyXmlNode(baseElement); _seriesTagsStream.XmlFragment = baseNode.XmlElementFragment; seriesElement.AddChild(baseNode); } } else { _seriesTagsStream = null; seriesElement.AddChild(new StudyXmlMemento.StudyXmlNode("<BaseInstance/>")); } foreach (InstanceXml instance in _instanceList.Values) { instance.SetBaseInstance(_seriesTagsStream); if (!string.IsNullOrEmpty(instance.XmlFragment)) { seriesElement.AddChild(new StudyXmlMemento.StudyXmlNode(instance.XmlFragment)); } else { XmlElement instanceElement = instance.GetMemento(theDocument.Document, settings); var node = new StudyXmlMemento.StudyXmlNode(instanceElement); instance.XmlFragment = node.XmlElementFragment; seriesElement.AddChild(node); } } return(seriesElement); }
public static void ReadGzip(StudyXmlMemento theMemento, Stream theStream) { var zipStream = new GZipStream(theStream, CompressionMode.Decompress); if (theMemento.Document == null) { theMemento.Document = new XmlDocument(); } theMemento.Document.Load(zipStream); }
public static void WriteGzip(StudyXmlMemento theMemento, Stream theStream) { using (var compressedZipStream = new GZipStream(theStream, CompressionMode.Compress, true)) { Write(theMemento, compressedZipStream); // Close the stream. compressedZipStream.Flush(); compressedZipStream.Close(); } // Force a flush theStream.Flush(); }
/// <summary> /// Load the StudyXml file. /// </summary> /// <param name="studyXmlFile"></param> public void LoadStudyXml(string studyXmlFile) { using (Stream fileStream = FileStreamOpener.OpenForRead(studyXmlFile, FileMode.Open)) { var theMemento = new StudyXmlMemento(); StudyXmlIo.Read(theMemento, fileStream); _studyXml = new StudyXml(_storageLocation.StudyInstanceUid); _studyXml.SetMemento(theMemento); fileStream.Close(); } }
public static void WriteGzip(StudyXmlMemento theMemento, Stream theStream) { var ms = new MemoryStream(); Write(theMemento, ms); byte[] buffer = ms.GetBuffer(); var compressedzipStream = new GZipStream(theStream, CompressionMode.Compress, true); compressedzipStream.Write(buffer, 0, buffer.Length); // Close the stream. compressedzipStream.Flush(); compressedzipStream.Close(); // Force a flush theStream.Flush(); }
public static void WriteXmlAndGzip(StudyXmlMemento theMemento, Stream theXmlStream, Stream theGzipStream) { // Write to a memory stream, then flush to disk and to gzip file var ms = new LargeMemoryStream(); Write(theMemento, ms); var compressedzipStream = new GZipStream(theGzipStream, CompressionMode.Compress, true); ms.Seek(0, SeekOrigin.Begin); ms.WriteTo(compressedzipStream); // Close the stream. compressedzipStream.Flush(); compressedzipStream.Close(); ms.Seek(0, SeekOrigin.Begin); ms.WriteTo(theXmlStream); // Force a flush. theXmlStream.Flush(); theGzipStream.Flush(); }
/// <summary> /// Load a <see cref="StudyXml"/> file for the <see cref="StudyLocation"/> /// </summary> /// <returns>The <see cref="StudyXml"/> instance</returns> public StudyXml LoadStudyXml() { var theXml = new StudyXml(); string streamFile = GetStudyXmlPath(); if (File.Exists(streamFile)) { using (Stream fileStream = FileStreamOpener.OpenForRead(streamFile, FileMode.Open)) { var memento = new StudyXmlMemento(); StudyXmlIo.Read(memento, fileStream); theXml.SetMemento(memento); fileStream.Close(); } } return theXml; }
public void Run() { HeaderStreamingServiceClient client = null; studies = null; StudyInfo study = null; while (true) { Random r = new Random(); if (String.IsNullOrEmpty(FixedStudyInstanceUid)) { bool refresh = false; if (studies == null) refresh = r.Next() % 10 == 0; else { refresh = r.NextDouble() < (1.0f/studies.Count/1000f); } if (refresh) { studies = new List<StudyInfo>(); CFindSCU cfind = new CFindSCU(); cfind.AETitle = LocalAE; cfind.OnResultReceive += new CFindSCU.ResultReceivedHandler(cfind_OnResultReceive); cfind.OnQueryCompleted += new CFindSCU.QueryCompletedHandler(cfind_OnQueryCompleted); cfind.Query(RemoteAE, RemoteHost, RemotePort); waitHandle.WaitOne(); } } else { studies = new List<StudyInfo>(); study = new StudyInfo(); study.StudyUid = FixedStudyInstanceUid; studies.Add(study); } if (studies!=null && studies.Count > 0) { try { if (client==null) { client = new HeaderStreamingServiceClient(); client.ClientCredentials.ClientCertificate.SetCertificate( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, Dns.GetHostName()); client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None; } study = studies[r.Next(studies.Count - 1)]; HeaderStreamingParameters param = new HeaderStreamingParameters(); param.ServerAETitle = RemoteAE; param.StudyInstanceUID = study.StudyUid; param.ReferenceID = Guid.NewGuid().ToString(); TimeSpanStatistics ts = new TimeSpanStatistics(); ts.Start(); Console.WriteLine("************ RETRIEVING... {0} **************", LocalAE); Stream input = client.GetStudyHeader(LocalAE, param); if (input!=null) { string outputdir = Path.Combine("./output", LocalAE); if (!Directory.Exists(outputdir)) Directory.CreateDirectory(outputdir); string temp = Path.Combine(outputdir, study.StudyUid + ".xml"); Console.WriteLine("Reading"); using (FileStream output = new FileStream(temp, FileMode.OpenOrCreate)) { GZipStream gzStream = new GZipStream(input, CompressionMode.Decompress); byte[] buffer = new byte[32*1024*1024]; int size = gzStream.Read(buffer, 0, buffer.Length); int count = 0; while(size>0) { output.Write(buffer, 0, size); count += size; Console.Write("\r{0} KB", count/1024); size = gzStream.Read(buffer, 0, buffer.Length); } output.Close(); } using (FileStream output = new FileStream(temp, FileMode.Open)) { var theMemento = new StudyXmlMemento(); Console.WriteLine("Reading into xml"); StudyXmlIo.Read(theMemento, output); Console.WriteLine("Done"); } } else { Console.WriteLine("{2} - {1,-16} {0,-64}... NOT FOUND", study.StudyUid, LocalAE, System.Diagnostics.Stopwatch.GetTimestamp()); } ts.End(); input.Close(); //File.Delete(temp); Console.WriteLine("{3} - {2,-16} {0,-64}... OK {1}", study.StudyUid, ts.FormattedValue, LocalAE, System.Diagnostics.Stopwatch.GetTimestamp()); } catch(TimeoutException) { // try again Console.WriteLine("{2} - {1,-16} {0,-64}... TIMEOUT", study.StudyUid, LocalAE, System.Diagnostics.Stopwatch.GetTimestamp()); } catch (Exception fault) { Console.WriteLine("{3} - {2,-16} {0,-64}... FAILED {1}", study.StudyUid, fault.Message, LocalAE, System.Diagnostics.Stopwatch.GetTimestamp()); if (client!=null) { client.Abort(); client.Close(); client = null; } } Thread.Sleep(r.Next(Delay)); } else { Thread.Sleep(r.Next(1000,3000)); } } }
/// <summary> /// Load a <see cref="StudyXml"/> file for a given <see cref="StudyStorageLocation"/> /// </summary> /// <param name="location">The location a study is stored.</param> /// <returns>The <see cref="StudyXml"/> instance for <paramref name="location"/></returns> protected virtual StudyXml LoadStudyXml(StudyStorageLocation location) { StudyXml theXml = new StudyXml(); String streamFile = Path.Combine(location.GetStudyPath(), location.StudyInstanceUid + ".xml"); if (File.Exists(streamFile)) { using (Stream fileStream = FileStreamOpener.OpenForRead(streamFile, FileMode.Open)) { var theMemento = new StudyXmlMemento(); StudyXmlIo.Read(theMemento, fileStream); theXml.SetMemento(theMemento); fileStream.Close(); } } return theXml; }
/// <summary> /// Load a <see cref="StudyXml"/> file for a given <see cref="StudyStorageLocation"/> /// </summary> /// <returns>The <see cref="StudyXml"/> instance for the study</returns> private StudyXml LoadStudyXml() { var theXml = new StudyXml(); String streamFile = Path.Combine(_rootPath, _studyInstanceUid + ".xml"); if (File.Exists(streamFile)) { using (Stream fileStream = FileStreamOpener.OpenForRead(streamFile, FileMode.Open)) { var theMemento = new StudyXmlMemento(); StudyXmlIo.Read(theMemento, fileStream); theXml.SetMemento(theMemento); fileStream.Close(); } } return theXml; }
public static void WriteXmlAndGzip(StudyXmlMemento theMemento, Stream theXmlStream, Stream theGzipStream) { // Write to a memory stream, then flush to disk and to gzip file var ms = new LargeMemoryStream(); Write(theMemento, ms); using (var compressedZipStream = new GZipStream(theGzipStream, CompressionMode.Compress, true)) { ms.Seek(0, SeekOrigin.Begin); ms.WriteTo(compressedZipStream); // Close the stream. compressedZipStream.Flush(); compressedZipStream.Close(); } ms.Seek(0, SeekOrigin.Begin); ms.WriteTo(theXmlStream); // Force a flush. theXmlStream.Flush(); theGzipStream.Flush(); }
/// <summary> /// Get a list of paths to the first image in each series within the study being processed. /// </summary> /// <returns></returns> private List<string> GetFirstInstanceInEachStudySeries() { var fileList = new List<string>(); if (_studyXml == null) { string studyXml = _location.GetStudyXmlPath(); if (!File.Exists(studyXml)) { return fileList; } _studyXml = new StudyXml(); using (FileStream stream = FileStreamOpener.OpenForRead(studyXml, FileMode.Open)) { var theMemento = new StudyXmlMemento(); StudyXmlIo.Read(theMemento, stream); stream.Close(); _studyXml.SetMemento(theMemento); } } // Note, we try and force ourselves to have an uncompressed // image, if one exists. That way the rules will be reapplied on the object // if necessary for compression. foreach (SeriesXml seriesXml in _studyXml) { InstanceXml saveInstance = null; foreach (InstanceXml instance in seriesXml) { if (instance.TransferSyntax.Encapsulated) { if (saveInstance == null) saveInstance = instance; } else { saveInstance = instance; break; } } if (saveInstance != null) { string path = Path.Combine(_location.GetStudyPath(), seriesXml.SeriesInstanceUid); path = Path.Combine(path, saveInstance.SopInstanceUid + ServerPlatform.DicomFileExtension); fileList.Add(path); } } return fileList; }
private void PopulateSeries(string studyInstanceUid) { LogTextPanel.Text = ""; StatisticsLog.Text = ""; HeaderStreamingServiceClient proxy = null; try { proxy = new HeaderStreamingServiceClient(); HeaderStreamingParameters parms = new HeaderStreamingParameters(); parms.StudyInstanceUID = studyInstanceUid; parms.ServerAETitle = ServerAE.Text; parms.ReferenceID = Guid.NewGuid().ToString(); TimeSpanStatistics servicecall = new TimeSpanStatistics(); servicecall.Start(); Stream stream = proxy.GetStudyHeader(AETitle.Text, parms); servicecall.End(); var decompression = new TimeSpanStatistics(); decompression.Start(); //GZipStream gzipStream = new GZipStream(stream, CompressionMode.Decompress); var theMemento = new StudyXmlMemento(); StudyXmlIo.ReadGzip(theMemento, stream); //doc.Load(gzipStream); decompression.End(); var settings = new XmlWriterSettings(); //settings.Indent = true; settings.NewLineOnAttributes = false; settings.OmitXmlDeclaration = true; settings.Encoding = Encoding.UTF8; StringWriter sw = new StringWriter(); XmlWriter writer = XmlWriter.Create(sw, settings); theMemento.Document.WriteTo(writer); writer.Flush(); Log(sw.ToString()); TimeSpanStatistics loading = new TimeSpanStatistics(); loading.Start(); StudyXml xml = new StudyXml(); xml.SetMemento(theMemento); loading.End(); int sopCounter = 0; SeriesTree.Nodes.Clear(); foreach(SeriesXml series in xml) { TreeNode seriesNode = new TreeNode(series.SeriesInstanceUid); SeriesTree.Nodes.Add(seriesNode); foreach(InstanceXml instance in series) { TreeNode instanceNode = new TreeNode(instance.SopInstanceUid); seriesNode.Nodes.Add(instanceNode); sopCounter++; } } StatisticsLog.Text=""; StatisticsLog.Text += String.Format("\r\nHeader Size (Decompressed): {0} KB", sw.ToString().Length / 1024); StatisticsLog.Text += String.Format("\r\nWCF Service call : {0} ms", servicecall.Value.TotalMilliseconds); StatisticsLog.Text += String.Format("\r\nDecompression : {0} ms", decompression.Value.TotalMilliseconds); StatisticsLog.Text += String.Format("\r\nLoading StudyXml : {0} ms", loading.Value.TotalMilliseconds); SeriesLabel.Text = String.Format("Series : {0} \tInstances: {1}", SeriesTree.Nodes.Count, sopCounter); stream.Close(); } catch(FaultException<StudyIsInUseFault> ex) { timer1.Stop(); MessageBox.Show(String.Format("StudyIsInUseFault received:{0}\n\nState={1}" , ex.Message, ex.Detail.StudyState)); } catch (FaultException<StudyIsNearlineFault> ex) { timer1.Stop(); MessageBox.Show("StudyIsNearlineFault received:\n" + ex.Message); } catch (FaultException<StudyNotFoundFault> ex) { timer1.Stop(); MessageBox.Show("StudyNotFoundFault received:\n" + ex.Message); } catch (Exception ex) { timer1.Stop(); MessageBox.Show(ex.Message); } finally { if (proxy.State == CommunicationState.Opened) proxy.Close(); } }
/// <summary> /// Populate this <see cref="StudyXml"/> object based on the supplied XML document. /// </summary> /// <param name="theMemento"></param> public void SetMemento(StudyXmlMemento theMemento) { // This should only happen in unit tests, but force the stream into a // memory stream, and then load in the xml document from there. if (theMemento.RootNode != null) { using (var ms = new MemoryStream()) { StudyXmlIo.Write(theMemento, ms); using (var ms2 = new MemoryStream(ms.ToArray())) theMemento.Document.Load(ms2); } } XmlDocument theDocument = theMemento.Document; if (!theDocument.HasChildNodes) { return; } // There should be one root node. XmlNode rootNode = theDocument.FirstChild; while (rootNode != null && !rootNode.Name.Equals("ClearCanvasStudyXml")) { rootNode = rootNode.NextSibling; } if (rootNode == null) { return; } XmlNode studyNode = rootNode.FirstChild; while (studyNode != null) { // Just search for the first study node, parse it, then break if (studyNode.Name.Equals("Study")) { _studyInstanceUid = studyNode.Attributes["UID"].Value; if (studyNode.HasChildNodes) { XmlNode seriesNode = studyNode.FirstChild; while (seriesNode != null) { String seriesInstanceUid = seriesNode.Attributes["UID"].Value; SeriesXml seriesStream = new SeriesXml(seriesInstanceUid); _seriesList.Add(seriesInstanceUid, seriesStream); seriesStream.SetMemento(seriesNode); // Go to next node in doc seriesNode = seriesNode.NextSibling; } } } studyNode = studyNode.NextSibling; } }
public static void ReadGzip(StudyXmlMemento theMemento, Stream theStream) { using (var zipStream = new GZipStream(theStream, CompressionMode.Decompress)) { if (theMemento.Document == null) theMemento.Document = new XmlDocument(); theMemento.Document.Load(zipStream); } }
public static void Read(StudyXmlMemento theMemento, Stream theStream) { if (theMemento.Document == null) theMemento.Document = new XmlDocument(); theMemento.Document.Load(theStream); }