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();
            }

        }
예제 #2
0
        public void GetStudy(string studyInstanceUid, Uri baseUri, string serverAE, bool singleImage)
        {
            Console.WriteLine("[{0}] : Loading {1}", _id, studyInstanceUid);
            string           uri      = String.Format("http://{0}:{1}/HeaderStreaming/HeaderStreaming", "localhost", 50221);
            EndpointAddress  endpoint = new EndpointAddress(uri);
            BasicHttpBinding binding  = new BasicHttpBinding(BasicHttpSecurityMode.None);

            binding.TransferMode           = TransferMode.Streamed;
            binding.MessageEncoding        = WSMessageEncoding.Mtom;
            binding.MaxReceivedMessageSize = Int32.MaxValue;
            binding.TextEncoding           = Encoding.UTF8;

            HeaderStreamingServiceClient headerClient = new HeaderStreamingServiceClient(binding, endpoint);

            using (headerClient)
            {
                HeaderStreamingParameters parms = new HeaderStreamingParameters();
                parms.StudyInstanceUID = studyInstanceUid;
                parms.ReferenceID      = Guid.NewGuid().ToString();
                parms.ServerAETitle    = "ImageServer";
                Stream stream = headerClient.GetStudyHeader("TEST", parms);

                XmlDocument doc = new XmlDocument();
                StudyXmlIo.ReadGzip(doc, stream);
                _studyXml = new StudyXml(studyInstanceUid);
                _studyXml.SetMemento(doc);
                stream.Close();
                headerClient.Close();
            }

            if (singleImage)
            {
                ulong           size   = 0;
                StreamingClient client = new StreamingClient(baseUri);
                foreach (SeriesXml series in _studyXml)
                {
                    foreach (InstanceXml instance in series)
                    {
                        do
                        {
                            Stream image =
                                client.RetrieveImage(serverAE, studyInstanceUid, series.SeriesInstanceUid,
                                                     instance.SopInstanceUid);
                            byte[] buffer = new byte[image.Length];
                            image.Read(buffer, 0, buffer.Length);
                            image.Close();
                            Console.Write(".");
                        } while (true);
                    }

                    Console.WriteLine("\n[{0}] : Finish Loading {1} [{2}]", _id, studyInstanceUid,
                                      ByteCountFormatter.Format(size));
                }
            }
            else
            {
                Random ran = new Random();
                do
                {
                    ulong           size   = 0;
                    StreamingClient client = new StreamingClient(baseUri);
                    foreach (SeriesXml series in _studyXml)
                    {
                        foreach (InstanceXml instance in series)
                        {
                            Stream image =
                                client.RetrieveImage(serverAE, studyInstanceUid, series.SeriesInstanceUid,
                                                     instance.SopInstanceUid);

                            byte[] buffer = new byte[image.Length];
                            image.Read(buffer, 0, buffer.Length);
                            image.Close();
                            size += (ulong)buffer.Length;
                            Console.Write(".");
                        }

                        Console.WriteLine("\n[{0}] : Finish Loading {1} [{2}]", _id, studyInstanceUid,
                                          ByteCountFormatter.Format(size));
                    }

                    Thread.Sleep(ran.Next(1000, 5000));
                } while (true);
            }
        }
예제 #3
0
 public Stream GetStudyHeader(string callingAETitle, HeaderStreamingParameters parameters)
 {
     return(Channel.GetStudyHeader(callingAETitle, parameters));
 }
예제 #4
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));
                }
            }
        }
예제 #5
0
        private StudyXml RetrieveStudyXml(StudyLoaderArgs studyLoaderArgs)
        {
            var headerParams = new HeaderStreamingParameters
            {
                StudyInstanceUID = studyLoaderArgs.StudyInstanceUid,
                ServerAETitle    = _serverAe.AETitle,
                ReferenceID      = Guid.NewGuid().ToString(),
                IgnoreInUse      = studyLoaderArgs.Options != null && studyLoaderArgs.Options.IgnoreInUse
            };

            HeaderStreamingServiceClient client = null;

            try
            {
                string uri = String.Format(StreamingSettings.Default.FormatHeaderServiceUri,
                                           _serverAe.ScpParameters.HostName, _serverAe.StreamingParameters.HeaderServicePort);

                client = new HeaderStreamingServiceClient(new Uri(uri));
                client.Open();
                var studyXml = client.GetStudyXml(ServerDirectory.GetLocalServer().AETitle, headerParams);
                client.Close();
                return(studyXml);
            }
            catch (FaultException <StudyIsInUseFault> e)
            {
                throw new InUseLoadStudyException(studyLoaderArgs.StudyInstanceUid, e);
            }
            catch (FaultException <StudyIsNearlineFault> e)
            {
                throw new NearlineLoadStudyException(studyLoaderArgs.StudyInstanceUid, e)
                      {
                          IsStudyBeingRestored = e.Detail.IsStudyBeingRestored
                      };
            }
            catch (FaultException <StudyNotFoundFault> e)
            {
                throw new NotFoundLoadStudyException(studyLoaderArgs.StudyInstanceUid, e);
            }
            catch (FaultException e)
            {
                //TODO: Some versions (pre-Team) of the ImageServer
                //throw a generic fault when a study is nearline, instead of the more specialized one.
                string message = e.Message.ToLower();
                if (message.Contains("nearline"))
                {
                    throw new NearlineLoadStudyException(studyLoaderArgs.StudyInstanceUid, e)
                          {
                              IsStudyBeingRestored = true
                          }
                }
                ;                                                                                                                                //assume true in legacy case.

                throw new LoadStudyException(studyLoaderArgs.StudyInstanceUid, e);
            }
            catch (Exception e)
            {
                if (client != null)
                {
                    client.Abort();
                }

                throw new LoadStudyException(studyLoaderArgs.StudyInstanceUid, e);
            }
        }
예제 #6
0
        public Stream GetStudyHeader(string callingAETitle, HeaderStreamingParameters parameters)
        {
            ConnectionMonitor.GetMonitor(OperationContext.Current.Host).AddContext(OperationContext.Current);

            HeaderStreamingStatistics stats = new HeaderStreamingStatistics();

            stats.ProcessTime.Start();

            HeaderLoader loader = null;

            try
            {
                Platform.CheckForEmptyString(callingAETitle, "callingAETitle");
                Platform.CheckForNullReference(parameters, "parameters");
                Platform.CheckForEmptyString(parameters.ReferenceID, "parameters.ReferenceID");
                Platform.CheckForEmptyString(parameters.ServerAETitle, "parameters.ServerAETitle");
                Platform.CheckForEmptyString(parameters.StudyInstanceUID, "parameters.StudyInstanceUID");

                Platform.Log(LogLevel.Debug, "Received request from {0}. Ref # {1} ", callingAETitle, parameters.ReferenceID);

                HeaderStreamingContext context = new HeaderStreamingContext();
                context.ServiceInstanceID = ID;
                context.CallerAE          = callingAETitle;
                context.Parameters        = parameters;

                // TODO: perform permission check on callingAETitle

                loader = new HeaderLoader(context);

                if (!parameters.IgnoreInUse)
                {
                    if (!loader.StudyLocation.CanBeUsedForDiagnostics())
                    {
                        throw new StudyAccessException(SR.FaultFaultStudyTemporarilyNotAccessible, loader.StudyLocation.QueueStudyStateEnum, null);
                    }
                }

                Stream stream = loader.Load();
                if (stream == null)
                {
                    throw new FaultException(loader.FaultDescription);
                }

                Platform.Log(LogLevel.Debug, "Response sent to {0}. Ref # {1} ", callingAETitle, parameters.ReferenceID);

                return(stream);
            }
            catch (ArgumentException e)
            {
                throw new FaultException(e.Message);
            }
            catch (StudyNotFoundException)
            {
                throw new FaultException <StudyNotFoundFault>(
                          new StudyNotFoundFault(), String.Format(SR.FaultNotExists, parameters.StudyInstanceUID, parameters.ServerAETitle));
            }
            catch (StudyIsNearlineException e)
            {
                throw new FaultException <StudyIsNearlineFault>(
                          new StudyIsNearlineFault()
                {
                    IsStudyBeingRestored = e.RestoreRequested
                },
                          String.Format(SR.FaultStudyIsNearline, parameters.StudyInstanceUID));
            }
            catch (StudyAccessException e)
            {
                if (e.InnerException != null)
                {
                    if (e.InnerException is FileNotFoundException)
                    {
                        throw new FaultException <StudyIsInUseFault>(
                                  new StudyIsInUseFault(e.StudyState.Description),
                                  String.Format(SR.FaultFaultStudyTemporarilyNotAccessible, parameters.StudyInstanceUID, e.StudyState));
                    }
                }
                throw new FaultException <StudyIsInUseFault>(
                          new StudyIsInUseFault(e.StudyState.Description),
                          String.Format(SR.FaultFaultStudyTemporarilyNotAccessible, parameters.StudyInstanceUID, e.StudyState));
            }
            catch (FilesystemNotReadableException e)
            {
                //interpret as generic fault
                throw new FaultException(e.Message);
            }
            catch (FileNotFoundException e)
            {
                // OOPS.. the header is missing
                Platform.Log(LogLevel.Error, e, "Unable to process study header request from {0}", callingAETitle);
                throw new FaultException(SR.FaultHeaderIsNotAvailable);
            }
            catch (Exception e)
            {
                if (!(e is FaultException))
                {
                    Platform.Log(LogLevel.Error, e, "Unable to process study header request from {0}", callingAETitle);
                }

                throw new FaultException(e.Message);
            }
            finally
            {
                stats.ProcessTime.End();

                if (loader != null && Settings.Default.LogStatistics)
                {
                    stats.AddField("StudyInstanceUid", parameters.StudyInstanceUID);

                    stats.AddSubStats(loader.Statistics);
                    StatisticsLogger.Log(LogLevel.Info, stats);
                }
            }
        }
예제 #7
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();
                }
            }
        }
예제 #8
0
파일: Program.cs 프로젝트: nhannd/Xian
        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));
                }
                
                
            }
          
        }