Esempio n. 1
0
        /// <summary>
        /// Do the actual Study migration.
        /// </summary>
        /// <param name="fs">The filesystem</param>
        /// <param name="item">The ServiceLock item being processed.</param>
        private void DoStudyMigrate(ServerFilesystemInfo fs, Model.ServiceLock item)
        {
            FilesystemQueueTypeEnum type = FilesystemQueueTypeEnum.TierMigrate;

            while (_bytesToRemove > 0)
            {
                TimeSpanStatistics queryTime = new TimeSpanStatistics("Query Time");
                queryTime.Start();
                IList <FilesystemQueue> list = GetFilesystemQueueCandidates(item, Platform.Time, type, false);
                queryTime.End();
                Platform.Log(LogLevel.Info,
                             "{1:0.0} MBs needs to be removed from '{0}'. Found {2} studies that can be migrated in {3} seconds",
                             fs.Filesystem.Description, _bytesToRemove / (1024 * 1024),
                             list.Count,
                             queryTime.Value.TotalSeconds);
                if (list.Count > 0)
                {
                    ProcessStudyMigrateCandidates(list);
                    if (CancelPending)
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Measures the elapsed time taken by an code block.
        /// </summary>
        /// <param name="executionBlock">Delegate to the code block which will be executed by this method and its elapsed will be measured</param>
        /// <returns>The <see cref="TimeSpanStatistics"/> object contains the elapsed time of the execution</returns>
        static public TimeSpanStatistics Measure(ExecutationBlock executionBlock)
        {
            TimeSpanStatistics stat = new TimeSpanStatistics();

            stat.Start();
            try
            {
                executionBlock();
                return stat;
            }
            finally
            {
                stat.End();
            }
        }
        /// <summary>
        /// Measures the elapsed time taken by an code block.
        /// </summary>
        /// <param name="executionBlock">Delegate to the code block which will be executed by this method and its elapsed will be measured</param>
        /// <returns>The <see cref="TimeSpanStatistics"/> object contains the elapsed time of the execution</returns>
        static public TimeSpanStatistics Measure(ExecutationBlock executionBlock)
        {
            TimeSpanStatistics stat = new TimeSpanStatistics();

            stat.Start();
            try
            {
                executionBlock();
                return(stat);
            }
            finally
            {
                stat.End();
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Writes the statistics to the log.
        /// </summary>
        public void WriteStatisticsToLog()
        {
            Log.Write("Duration statistics:");

            TimeSpanStatistics.Sort();
            string LastGroupName = "";

            foreach (TimeSpanStatisticsItem TSI in TimeSpanStatistics)
            {
                if (LastGroupName != TSI.GroupName)
                {
                    Log.Write("  {0}".Build(TSI.GroupName));
                    LastGroupName = TSI.GroupName;
                }
                Log.Write("    - {0}".Build(TSI.ToString()));
            }
        }
Esempio n. 5
0
        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))
                            {
                                XmlDocument doc = new XmlDocument();
                                Console.WriteLine("Reading into xml");
                                StudyXmlIo.Read(doc, 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));
                }
            }
        }
        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>
		/// Do the actual Study migration.
		/// </summary>
		/// <param name="fs">The filesystem</param>
		/// <param name="item">The ServiceLock item being processed.</param>
        private void DoStudyMigrate( ServerFilesystemInfo fs, Model.ServiceLock item)
        {
            FilesystemQueueTypeEnum type = FilesystemQueueTypeEnum.TierMigrate;

            while (_bytesToRemove > 0)
            {
				TimeSpanStatistics queryTime = new TimeSpanStatistics("Query Time");
				queryTime.Start();
                IList<FilesystemQueue> list = GetFilesystemQueueCandidates(item, Platform.Time, type, false);
				queryTime.End();
				Platform.Log(LogLevel.Info,
							 "{1:0.0} MBs needs to be removed from '{0}'. Found {2} studies that can be migrated in {3} seconds",
							 fs.Filesystem.Description, _bytesToRemove / (1024 * 1024),
							 list.Count,
							 queryTime.Value.TotalSeconds);
				if (list.Count > 0)
                {
                    ProcessStudyMigrateCandidates(list);
					if (CancelPending) break;
                }
                else
                {
                    break;
                }
            }
        }
Esempio n. 8
0
        private static void RetrieveImages(string serverAE, string studyPath)
        {
            Console.WriteLine("server={0}", serverAE);
            string          baseUri         = String.Format("http://{0}:{1}", serverHost, serverPort);
            StreamingClient client          = new StreamingClient(new Uri(baseUri));
            int             totalFrameCount = 0;

            DirectoryInfo directoryInfo = new DirectoryInfo(studyPath);
            string        studyUid      = directoryInfo.Name;

            RateStatistics        frameRate    = new RateStatistics("Speed", "frame");
            RateStatistics        speed        = new RateStatistics("Speed", RateType.BYTES);
            AverageRateStatistics averageSpeed = new AverageRateStatistics(RateType.BYTES);
            ByteCountStatistics   totalSize    = new ByteCountStatistics("Size");

            frameRate.Start();
            speed.Start();

            Console.WriteLine("\n------------------------------------------------------------------------------------------------------------------------");

            string[] seriesDirs = Directory.GetDirectories(studyPath);
            foreach (string seriesPath in seriesDirs)
            {
                DirectoryInfo dirInfo       = new DirectoryInfo(seriesPath);
                string        seriesUid     = dirInfo.Name;
                string[]      objectUidPath = Directory.GetFiles(seriesPath, "*.dcm");

                foreach (string uidPath in objectUidPath)
                {
                    FileInfo fileInfo = new FileInfo(uidPath);
                    string   uid      = fileInfo.Name.Replace(".dcm", "");
                    Console.Write("{0,-64}... ", uid);

                    try
                    {
                        Stream imageStream;
                        StreamingResultMetaData      imageMetaData;
                        FrameStreamingResultMetaData frameMetaData;

                        switch (type)
                        {
                        case ContentTypes.Dicom:
                            imageStream = client.RetrieveImage(serverAE, studyUid, seriesUid, uid, out imageMetaData);
                            totalFrameCount++;
                            averageSpeed.AddSample(imageMetaData.Speed);
                            totalSize.Value += (ulong)imageMetaData.ContentLength;

                            Console.WriteLine("1 dicom sop [{0,10}] in {1,12}\t[mime={2}]", ByteCountFormatter.Format((ulong)imageStream.Length), TimeSpanFormatter.Format(imageMetaData.Speed.ElapsedTime), imageMetaData.ResponseMimeType);

                            break;

                        case ContentTypes.RawPixel:
                            TimeSpanStatistics elapsedTime = new TimeSpanStatistics();
                            elapsedTime.Start();
                            ulong instanceSize = 0;
                            int   frameCount   = 0;
                            do
                            {
                                RetrievePixelDataResult result = client.RetrievePixelData(serverAE, studyUid, seriesUid, uid, frameCount);
                                frameMetaData = result.MetaData;
                                totalFrameCount++;
                                frameCount++;
                                averageSpeed.AddSample(frameMetaData.Speed);
                                totalSize.Value += (ulong)frameMetaData.ContentLength;
                                instanceSize    += (ulong)frameMetaData.ContentLength;
                            } while (!frameMetaData.IsLast);

                            elapsedTime.End();
                            Console.WriteLine("{0,3} frame(s) [{1,10}] in {2,12}\t[mime={3}]", frameCount, ByteCountFormatter.Format(instanceSize), elapsedTime.FormattedValue, frameMetaData.ResponseMimeType);
                            break;

                        default:

                            imageStream = client.RetrieveImage(serverAE, studyUid, seriesUid, uid, out imageMetaData);
                            totalFrameCount++;
                            averageSpeed.AddSample(imageMetaData.Speed);
                            totalSize.Value += (ulong)imageMetaData.ContentLength;

                            Console.WriteLine("1 object [{0,10}] in {1,12}\t[mime={2}]", ByteCountFormatter.Format((ulong)imageStream.Length), TimeSpanFormatter.Format(imageMetaData.Speed.ElapsedTime), imageMetaData.ResponseMimeType);

                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is WebException)
                        {
                            HttpWebResponse rsp = ((ex as WebException).Response as HttpWebResponse);

                            string msg = String.Format("Error: {0} : {1}", rsp.StatusCode, HttpUtility.HtmlDecode(rsp.StatusDescription)
                                                       );
                            Console.WriteLine(msg);
                        }
                        else
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
            }
            frameRate.SetData(totalFrameCount);
            frameRate.End();
            speed.SetData(totalSize.Value);
            speed.End();


            Console.WriteLine("\nTotal {0,3} image(s)/frame(s) [{1,10}] in {2,12}   ==>  [ Speed: {3,12} or {4,12}]",
                              totalFrameCount, totalSize.FormattedValue,
                              TimeSpanFormatter.Format(frameRate.ElapsedTime),
                              frameRate.FormattedValue,
                              speed.FormattedValue
                              );
        }
Esempio n. 9
0
        private static void RetrieveImages(string serverAE, string studyPath)
        {
            Console.WriteLine("server={0}", serverAE);
            string baseUri = String.Format("http://{0}:{1}", serverHost, serverPort);
            StreamingClient client = new StreamingClient(new Uri(baseUri));
            int totalFrameCount = 0;
            
            DirectoryInfo directoryInfo = new DirectoryInfo(studyPath);
            string studyUid = directoryInfo.Name;

            RateStatistics frameRate = new RateStatistics("Speed", "frame");
            RateStatistics speed = new RateStatistics("Speed", RateType.BYTES);
            AverageRateStatistics averageSpeed = new AverageRateStatistics(RateType.BYTES);
            ByteCountStatistics totalSize = new ByteCountStatistics("Size");
            
            frameRate.Start();
            speed.Start();

            Console.WriteLine("\n------------------------------------------------------------------------------------------------------------------------");

            string[] seriesDirs = Directory.GetDirectories(studyPath);
            foreach(string seriesPath in seriesDirs)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(seriesPath);
                string seriesUid = dirInfo.Name;
                string[] objectUidPath = Directory.GetFiles(seriesPath, "*.dcm");
                
                foreach (string uidPath in objectUidPath)
                {
                    FileInfo fileInfo = new FileInfo(uidPath);
                    string uid = fileInfo.Name.Replace(".dcm", "");
                    Console.Write("{0,-64}... ", uid);
                                    
                    try
                    {
                        Stream imageStream;
                        StreamingResultMetaData imageMetaData;
                        FrameStreamingResultMetaData frameMetaData;
                                   
                        switch(type)
                        {
                            case ContentTypes.Dicom:
                                imageStream = client.RetrieveImage(serverAE, studyUid, seriesUid, uid, out imageMetaData);
                                totalFrameCount++;
                                averageSpeed.AddSample(imageMetaData.Speed);
                                totalSize.Value += (ulong)imageMetaData.ContentLength;

                                Console.WriteLine("1 dicom sop [{0,10}] in {1,12}\t[mime={2}]", ByteCountFormatter.Format((ulong)imageStream.Length), TimeSpanFormatter.Format(imageMetaData.Speed.ElapsedTime), imageMetaData.ResponseMimeType);
                                
                                break;

                            case ContentTypes.RawPixel:
                                TimeSpanStatistics elapsedTime = new TimeSpanStatistics();
                                elapsedTime.Start();
                                ulong instanceSize = 0;
                                int frameCount = 0;
                                do
                                {
									RetrievePixelDataResult result = client.RetrievePixelData(serverAE, studyUid, seriesUid, uid, frameCount);
                                	frameMetaData = result.MetaData;
									totalFrameCount++;
                                    frameCount++;
                                    averageSpeed.AddSample(frameMetaData.Speed);
                                    totalSize.Value += (ulong)frameMetaData.ContentLength;
                                    instanceSize += (ulong)frameMetaData.ContentLength;

                                } while (!frameMetaData.IsLast);

                                elapsedTime.End();
                                Console.WriteLine("{0,3} frame(s) [{1,10}] in {2,12}\t[mime={3}]", frameCount, ByteCountFormatter.Format(instanceSize), elapsedTime.FormattedValue, frameMetaData.ResponseMimeType);
                                break;

                            default:

                                imageStream = client.RetrieveImage(serverAE, studyUid, seriesUid, uid, out imageMetaData);
                                totalFrameCount++;
                                averageSpeed.AddSample(imageMetaData.Speed);
                                totalSize.Value += (ulong)imageMetaData.ContentLength;

                                Console.WriteLine("1 object [{0,10}] in {1,12}\t[mime={2}]", ByteCountFormatter.Format((ulong)imageStream.Length), TimeSpanFormatter.Format(imageMetaData.Speed.ElapsedTime), imageMetaData.ResponseMimeType);

                                break;
                        }

                    }
                    catch(Exception ex)
                    {
                        if (ex is WebException)
                        {
                            HttpWebResponse rsp = ( (ex as WebException).Response as HttpWebResponse);
                        
                            string msg = String.Format("Error: {0} : {1}", rsp.StatusCode,HttpUtility.HtmlDecode(rsp.StatusDescription)
                                );
                            Console.WriteLine(msg);
                        }
                        else
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
            }
            frameRate.SetData(totalFrameCount);
            frameRate.End();
            speed.SetData(totalSize.Value);
            speed.End();


            Console.WriteLine("\nTotal {0,3} image(s)/frame(s) [{1,10}] in {2,12}   ==>  [ Speed: {3,12} or {4,12}]",
                    totalFrameCount, totalSize.FormattedValue,
                    TimeSpanFormatter.Format(frameRate.ElapsedTime),
                    frameRate.FormattedValue,
                    speed.FormattedValue
                    );

                                        
        }
Esempio n. 10
0
        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();
                }
            }
        }
Esempio n. 11
0
        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))
                            {
                                XmlDocument doc = new XmlDocument();
                                Console.WriteLine("Reading into xml");
                                StudyXmlIo.Read(doc, 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));
                }
                
                
            }
          
        }