public async Task SendAsync_SingleRequest_DataSufficientlyTransported()
        {
            int port = Ports.GetNext();
            using (new DicomServer<SimpleCStoreProvider>(port))
            {
                DicomDataset command = null, dataset = null;
                var request = new DicomCStoreRequest(@".\Test Data\CT1_J2KI");
                request.OnResponseReceived = (req, res) =>
                {
                    command = request.Command;
                    dataset = request.Dataset;
                };

                var client = new DicomClient();
                client.AddRequest(request);

                await client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");

                var commandField = command.Get<ushort>(DicomTag.CommandField);
                Assert.Equal((ushort)1, commandField);

                var modality = dataset.Get<string>(DicomTag.Modality);
                Assert.Equal("CT", modality);
            }
        }
Example #2
1
 private void CStoreTask(object state)
 {
     Interlocked.Increment(ref index);
     string file = (string)state;
     DicomCStoreRequest cstoreReq = new DicomCStoreRequest(file);
     DicomClient client = new DicomClient();
     client.AddRequest(cstoreReq);
     client.Send("127.0.0.1", 104, false, string.Format("ZSSURE_{0}",index), "STORESCP");
 }
Example #3
0
        public void OldDicomClientSend_ToAcceptedAssociation_ShouldSendRequest()
        {
            var port = Ports.GetNext();

            using (DicomServer.Create <DicomClientTest.MockCEchoProvider>(port))
            {
                var locker = new object();

                var         expected = DicomStatus.Success;
                DicomStatus actual   = null;

                var client = new Dicom.Network.DicomClient();
                client.AddRequest(
                    new DicomCEchoRequest
                {
                    OnResponseReceived = (rq, rsp) =>
                    {
                        lock (locker) actual = rsp.Status;
                    }
                });
                client.Send("localhost", port, false, "SCU", "ANY-SCP");

                Assert.Equal(expected, actual);
            }
        }
Example #4
0
        public void OldDicomClientSend_ToRejectedAssociation_ShouldNotSendRequest()
        {
            var port = Ports.GetNext();

            using (DicomServer.Create <DicomClientTest.MockCEchoProvider>(port))
            {
                var         locker = new object();
                DicomStatus status = null;

                var client = new Dicom.Network.DicomClient();
                client.AddRequest(
                    new DicomCEchoRequest
                {
                    OnResponseReceived = (rq, rsp) =>
                    {
                        lock (locker) status = rsp.Status;
                    }
                });

                try
                {
                    client.Send("localhost", port, false, "SCU", "WRONG-SCP");
                }
                catch
                {
                }

                Assert.Null(status);
            }
        }
Example #5
0
        public void DicomCGetRequest_OneImageInSeries_Received()
        {
            var client = new DicomClient();
            client.Options = new DicomServiceOptions { IgnoreAsyncOps = true };

            var pcs = DicomPresentationContext.GetScpRolePresentationContextsFromStorageUids(
                DicomStorageCategory.Image,
                DicomTransferSyntax.ExplicitVRLittleEndian,
                DicomTransferSyntax.ImplicitVRLittleEndian,
                DicomTransferSyntax.ImplicitVRBigEndian);
            client.AdditionalPresentationContexts.AddRange(pcs);

            DicomDataset dataset = null;
            client.OnCStoreRequest = request =>
                {
                    dataset = request.Dataset;
                    return new DicomCStoreResponse(request, DicomStatus.Success);
                };

            var get = new DicomCGetRequest(
                "1.2.840.113619.2.1.1.322987881.621.736170080.681",
                "1.2.840.113619.2.1.2411.1031152382.365.736169244");

            var handle = new ManualResetEventSlim();
            get.OnResponseReceived = (request, response) =>
            {
                handle.Set();
            };
            client.AddRequest(get);
            client.Send("localhost", 11112, false, "SCU", "COMMON");
            handle.Wait();

            Assert.Equal("RT ANKLE", dataset.Get<string>(DicomTag.StudyDescription));
        }
Example #6
0
        static void Main(string[] args)
        {
            //构造要发送的C-FIND-RQ消息,如果查看DicomCFindRequest类的话
            //可以看到其定义与DICOM3.0标准第7部分第9章中规定的编码格式一致

            //在构造Study级别的查询时,我们的参数patientID会被填充到消息的Indentifier部分,用来在SCP方进行匹配查询
            var cfind = DicomCFindRequest.CreateStudyQuery(patientId: "12345");


            //当接收到对方发挥的响应消息时,进行相应的操作【注】:该操作在DICOM3.0协议
            //第7部分第8章中有说明,DIMSE协议并未对其做出规定,而应该有用户自己设定
            
            cfind.OnResponseReceived = (rq, rsp) =>
                {
                    //此处我们只是简单的将查询到的结果输出到屏幕
                    Console.WriteLine("PatientAge:{0} PatientName:{1}", rsp.Dataset.Get<string>(DicomTag.PatientAge), rsp.Dataset.Get<string>(DicomTag.PatientName));
                };

            //发起C-FIND-RQ:
            //该部分就是利用A-ASSOCIATE服务来建立DICOM实体双方之间的连接。
            var client = new DicomClient();
            client.AddRequest(cfind);
            client.Send(host:"127.0.0.1",port: 12345,useTls: false,callingAe: "SCU-AE",calledAe: "SCP-AE");
            Console.ReadLine();
        }
Example #7
0
        static void OneClient2MultiServers(int[] ports)
        {
            DicomClient client = new DicomClient();
            foreach (var port in ports)
            {

            }

        }
Example #8
0
        public async Task DicomService_reading_messages_with_invalid_UIDs_does_not_fail()
        {
            int port         = Ports.GetNext();
            var clientLogger = _output.IncludePrefix(nameof(Network.DicomClient));
            var serverLogger = _output.IncludePrefix(nameof(DicomCEchoProvider));
            var source       = new CancellationTokenSource();

            using (var server = DicomServer.Create <SimpleCStoreProvider>(port,
                                                                          logger: serverLogger,
                                                                          options: new DicomServiceOptions
            {
                LogDataPDUs = true,
                LogDimseDatasets = true
            }))
            {
                while (!server.IsListening)
                {
                    await Task.Delay(50);
                }

                var client = new DicomClient
                {
                    Logger = clientLogger
                };

                var command = new DicomDataset();
                command.ValidateItems = false;
                command.Add(DicomTag.CommandField, (ushort)DicomCommandField.CStoreRequest);
                command.Add(DicomTag.MessageID, (ushort)1);
                command.Add(DicomTag.AffectedSOPClassUID, DicomUID.CTImageStorage);
                command.Add(new DicomUniqueIdentifier(DicomTag.AffectedSOPInstanceUID, "1.2.3.04"));

                var request = new DicomCStoreRequest(command)
                {
                    File    = new DicomFile(),
                    Dataset = new DicomDataset()
                };
                request.Dataset.ValidateItems = false;
                request.Dataset.Add(DicomTag.SOPClassUID, DicomUID.CTImageStorage);
                request.Dataset.Add(new DicomUniqueIdentifier(DicomTag.SOPInstanceUID, "1.2.3.04"));

                request.OnResponseReceived += (e, args) =>
                {
                    _output.Info("Response received. Cancelling in 500ms.");
                    source.CancelAfter(100);
                };

                client.AddRequest(request);

                await client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");
            }
        }
Example #9
0
        static void ThreadProcess(object state)
        {
            string clientID = state.ToString();
            DicomCFindRequest cfindReq = DicomCFindRequest.CreatePatientQuery("1111", "test");
            cfindReq.OnResponseReceived += (req, rsp) =>
            {
                System.Console.WriteLine(rsp.ToString()+"ClientID="+clientID);
            };
            DicomClient client = new DicomClient();
            client.AddRequest(cfindReq);
            client.Send("127.0.0.1", 104, false, "FINDSCU", "FINDSCP");

        }
Example #10
0
        public void DicomClientSend_StorePart10File_ShouldSucceed()
        {
            var port = Ports.GetNext();

            using (var server = DicomServer.Create<CStoreScp>(port))
            {
                var file = DicomFile.Open(@".\Test Data\CT-MONO2-16-ankle");

                var client = new DicomClient();
                client.AddRequest(new DicomCStoreRequest(file));

                var exception = Record.Exception(() => client.Send("127.0.0.1", port, false, "SCU", "SCP"));
                Assert.Null(exception);
            }
        }
Example #11
0
        public void Send_MultipleRequests_AllRecognized(int expected)
        {
            int port = Ports.GetNext();
            using (new DicomServer<DicomCEchoProvider>(port))
            {
                var actual = 0;

                var client = new DicomClient();
                for (var i = 0; i < expected; ++i) client.AddRequest(new DicomCEchoRequest { OnResponseReceived = (req, res) => ++actual });

                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");

                Assert.Equal(expected, actual);
            }
        }
		public void Send_ToDicomServer_ReturnsSuccess()
		{
			Task.Run(() => new DicomServer<DicomCEchoProvider>(104)).Wait(100);

			var client = new DicomClient();
			client.NegotiateAsyncOps();

			DicomStatus status = null;
			var request = new DicomCEchoRequest { OnResponseReceived = (echoRequest, response) => status = response.Status };
			client.AddRequest(request);
			client.Send("localhost", 104, false, "ECHOSCU", "ECHOSCP");

			while (status == null) Thread.Sleep(10);
			Assert.AreEqual(DicomStatus.Success, status);
		}
        public async Task OldDicomClient_SendEchos()
        {
            var client = new Dicom.Network.DicomClient();

            client.NegotiateAsyncOps(1, 1);
            client.Linger = 0;

            var requests = Enumerable.Range(0, 1000).Select(i => new DicomCEchoRequest());

            foreach (var request in requests)
            {
                client.AddRequest(request);
            }

            await client.SendAsync("127.0.0.1", _server.Port, false, "SCU", "ANY-SCP").ConfigureAwait(false);
        }
Example #14
0
        public void Send_SingleRequest_Recognized()
        {
            int port = Ports.GetNext();
            using (DicomServer.Create<DicomCEchoProvider>(port))
            {
                var counter = 0;
                var request = new DicomCEchoRequest { OnResponseReceived = (req, res) => ++counter };

                var client = new DicomClient();
                client.AddRequest(request);

                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");

                Assert.Equal(1, counter);
            }
        }
        public void Send_FromDicomClient_DoesNotDeadlock()
        {
            LogManager.SetImplementation(new StringLogManager());

            int port = Ports.GetNext();
            using (new DicomServer<DicomCEchoProvider>(port))
            {
                var client = new DicomClient();
                for (var i = 0; i < 10; i++)
                    client.AddRequest(new DicomCEchoRequest());

                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");
                
                var log = LogManager.GetLogger(null).ToString();
                Assert.True(log.Length > 0);
            }
        }
Example #16
0
        public void Release_AfterAssociation_SendIsCompleted()
        {
            int port = Ports.GetNext();

            using (new DicomServer <MockCEchoProvider>(port))
            {
                var client = new DicomClient();
                client.AddRequest(new DicomCEchoRequest());
                var task = client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");

                client.WaitForAssociation();
                Thread.Sleep(10);
                Assert.False(task.IsCompleted);

                client.Release();
                Thread.Sleep(10);
                Assert.True(task.IsCompleted);
            }
        }
Example #17
0
        public void Send_Ipv6AnyListenerKnownSOPClass_SendSucceeds()
        {
            var port = Ports.GetNext();

            using (DicomServer.Create <SimpleCStoreProvider>(NetworkManager.IPv6Any, port))
            {
                DicomStatus status  = null;
                var         request = new DicomCStoreRequest(@".\Test Data\CT-MONO2-16-ankle");
                request.OnResponseReceived = (req, res) =>
                { status = res.Status; };

                var client = new DicomClient();
                client.AddRequest(request);

                client.Send(NetworkManager.IPv6Loopback, port, false, "SCU", "ANY-SCP");

                Assert.Equal(DicomStatus.Success, status);
            }
        }
Example #18
0
        public void Send_SingleRequest_Recognized()
        {
            int port = Ports.GetNext();

            using (DicomServer.Create <DicomCEchoProvider>(port))
            {
                var counter = 0;
                var request = new DicomCEchoRequest {
                    OnResponseReceived = (req, res) => Interlocked.Increment(ref counter)
                };

                var client = new DicomClient();
                client.AddRequest(request);

                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");

                Assert.Equal(1, counter);
            }
        }
Example #19
0
        public void Send_PrivateNotRegisteredSOPClass_SendFails()
        {
            var port = Ports.GetNext();

            using (DicomServer.Create <SimpleCStoreProvider>(port))
            {
                DicomStatus status  = null;
                var         request = new DicomCStoreRequest(@".\Test Data\GH355.dcm");
                request.OnResponseReceived = (req, res) =>
                { status = res.Status; };

                var client = new DicomClient();
                client.AddRequest(request);

                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");

                Assert.Equal(DicomStatus.SOPClassNotSupported, status);
            }
        }
Example #20
0
        public void BeginSend_SingleRequest_Recognized()
        {
            int port = Ports.GetNext();

            using (new DicomServer <DicomCEchoProvider>(port))
            {
                var counter = 0;
                var request = new DicomCEchoRequest {
                    OnResponseReceived = (req, res) => ++ counter
                };

                var client = new DicomClient();
                client.AddRequest(request);

                client.EndSend(client.BeginSend("127.0.0.1", port, false, "SCU", "ANY-SCP", null, null));

                Assert.Equal(1, counter);
            }
        }
Example #21
0
        public void AssociationReleased_SuccessfulSend_IsInvoked()
        {
            var port = Ports.GetNext();

            using (DicomServer.Create <DicomCEchoProvider>(port))
            {
                var client = new DicomClient();

                var released = false;
                var handle   = new ManualResetEventSlim();
                client.AssociationReleased += (sender, args) => { released = true; handle.Set(); };

                client.AddRequest(new DicomCEchoRequest());
                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");

                handle.Wait(1000);
                Assert.True(released);
            }
        }
Example #22
0
        public void Send_FromDicomClient_DoesNotDeadlock()
        {
            LogManager.SetImplementation(new StringLogManager());

            int port = Ports.GetNext();

            using (new DicomServer <DicomCEchoProvider>(port))
            {
                var client = new DicomClient();
                for (var i = 0; i < 10; i++)
                {
                    client.AddRequest(new DicomCEchoRequest());
                }

                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");

                var log = LogManager.GetLogger(null).ToString();
                Assert.True(log.Length > 0);
            }
        }
Example #23
0
        public async Task SendAsync_SingleRequest_Recognized()
        {
            int port = Ports.GetNext();

            using (DicomServer.Create <DicomCEchoProvider>(port))
            {
                var counter = 0;
                var request = new DicomCEchoRequest {
                    OnResponseReceived = (req, res) => Interlocked.Increment(ref counter)
                };

                var client = new DicomClient();
                client.AddRequest(request);

                var task = client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");
                await Task.WhenAny(task, Task.Delay(10000));

                Assert.Equal(1, counter);
            }
        }
Example #24
0
        public async Task ReleaseAsync_AfterAssociation_SendIsCompleted()
        {
            int port = Ports.GetNext();

            using (DicomServer.Create <MockCEchoProvider>(port))
            {
                Task task   = null;
                var  client = new DicomClient();
                client.AssociationAccepted += HandleAssociationAccepted;
                client.AddRequest(new DicomCEchoRequest());
                task = client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");

                void HandleAssociationAccepted(object sender, AssociationAcceptedEventArgs e)
                {
                    (sender as DicomClient).ReleaseAsync().Wait();
                    Thread.Sleep(10);
                    Assert.True(task.IsCompleted);
                }
            }
        }
Example #25
0
        public void Send_KnownSOPClass_SendSucceeds()
        {
            var port = Ports.GetNext();

            using (DicomServer.Create <SimpleCStoreProvider>(port))
            {
                DicomStatus status  = null;
                var         request = new DicomCStoreRequest(@".\Test Data\CT-MONO2-16-ankle")
                {
                    OnResponseReceived = (req, res) => status = res.Status
                };

                var client = new DicomClient();
                client.AddRequest(request);

                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");

                Assert.Equal(DicomStatus.Success, status);
            }
        }
Example #26
0
            internal DicomServiceUser(
                DicomClient client,
                INetworkStream stream,
                DicomAssociation association,
                DicomServiceOptions options,
                Encoding fallbackEncoding,
                Logger log)
                : base(stream, fallbackEncoding, log)
            {
                _client = client;

                if (options != null)
                {
                    Options = options;
                }

                List <DicomRequest> requests;

                lock (_client._lock)
                {
                    requests = _client._requests.Select(s => s.Value).ToList();
                }

                foreach (var request in requests)
                {
                    association.PresentationContexts.AddFromRequest(request);
                }

                foreach (var context in client.AdditionalPresentationContexts)
                {
                    association.PresentationContexts.Add(
                        context.AbstractSyntax,
                        context.UserRole,
                        context.ProviderRole,
                        context.GetTransferSyntaxes().ToArray());
                }

                _association      = association;
                _isInitialized    = false;
                _releaseRequested = 0;
            }
Example #27
0
        public void BeginSend_MultipleRequests_AllRecognized(int expected)
        {
            int port = Ports.GetNext();

            using (new DicomServer <DicomCEchoProvider>(port))
            {
                var actual = 0;

                var client = new DicomClient();
                for (var i = 0; i < expected; ++i)
                {
                    client.AddRequest(new DicomCEchoRequest {
                        OnResponseReceived = (req, res) => ++ actual
                    });
                }

                client.EndSend(client.BeginSend("127.0.0.1", port, false, "SCU", "ANY-SCP", null, null));

                Assert.Equal(expected, actual);
            }
        }
Example #28
0
        public void Send_MultipleTimes_AllRecognized(int expected)
        {
            int port  = Ports.GetNext();
            var @lock = new object();

            using (new DicomServer <DicomCEchoProvider>(port))
            {
                var actual = 0;

                var client = new DicomClient();
                for (var i = 0; i < expected; ++i)
                {
                    client.AddRequest(new DicomCEchoRequest {
                        OnResponseReceived = (req, res) => { lock (@lock) ++actual; }
                    });
                    client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");
                }

                Assert.Equal(expected, actual);
            }
        }
Example #29
0
        public void Send_FromDicomClient_DoesNotDeadlock()
        {
            LogManager.SetImplementation(NLogManager.Instance);
            var target = NLogHelper.AssignMemoryTarget(
                nameof(DicomCEchoProviderTest),
                @"${message}",
                NLog.LogLevel.Trace);

            var port = Ports.GetNext();
            using (DicomServer.Create<DicomCEchoProvider>(port))
            {
                var client = new DicomClient();
                for (var i = 0; i < 10; i++)
                {
                    client.AddRequest(new DicomCEchoRequest());
                }

                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");
                Assert.True(target.Logs.Count > 0);
            }
        }
Example #30
0
        public void IsSendRequired_AddedRequestNotConnected_ReturnsTrue()
        {
            var port = Ports.GetNext();

            using (DicomServer.Create <DicomCEchoProvider>(port))
            {
                var client = new DicomClient();
                client.AddRequest(new DicomCEchoRequest {
                    OnResponseReceived = (req, res) => Thread.Sleep(100)
                });
                Assert.True(client.IsSendRequired);
                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");

                Thread.Sleep(100);
                client.AddRequest(new DicomCEchoRequest {
                    OnResponseReceived = (req, res) => Thread.Sleep(100)
                });

                Assert.True(client.IsSendRequired);
            }
        }
Example #31
0
        public void Send_ToDicomServer_ReturnsSuccess()
        {
            Task.Run(() => new DicomServer <DicomCEchoProvider>(104)).Wait(100);

            var client = new DicomClient();

            client.NegotiateAsyncOps();

            DicomStatus status  = null;
            var         request = new DicomCEchoRequest {
                OnResponseReceived = (echoRequest, response) => status = response.Status
            };

            client.AddRequest(request);
            client.Send("localhost", 104, false, "ECHOSCU", "ECHOSCP");

            while (status == null)
            {
                Thread.Sleep(10);
            }
            Assert.AreEqual(DicomStatus.Success, status);
        }
Example #32
0
            internal DicomServiceUser(
                DicomClient client,
                INetworkStream stream,
                DicomAssociation association,
                DicomServiceOptions options,
                Encoding fallbackEncoding,
                Logger log)
                : base(stream, fallbackEncoding, log)
            {
                this.client = client;

                if (options != null)
                {
                    Options = options;
                }

                List <DicomRequest> requests;

                lock (this.client.locker)
                {
                    requests = new List <DicomRequest>(this.client.requests);
                }

                foreach (var request in requests)
                {
                    association.PresentationContexts.AddFromRequest(request);
                }

                foreach (var context in client.AdditionalPresentationContexts)
                {
                    association.PresentationContexts.Add(
                        context.AbstractSyntax,
                        context.UserRole,
                        context.ProviderRole,
                        context.GetTransferSyntaxes().ToArray());
                }

                SendAssociationRequest(association);
            }
Example #33
0
        public async Task SendAsync_MultipleRequests_AllRecognized(int expected)
        {
            int port = Ports.GetNext();

            using (new DicomServer <DicomCEchoProvider>(port))
            {
                var actual = 0;

                var client = new DicomClient();
                for (var i = 0; i < expected; ++i)
                {
                    client.AddRequest(new DicomCEchoRequest {
                        OnResponseReceived = (req, res) => ++ actual
                    });
                }

                var task = client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");
                await Task.WhenAny(task, Task.Delay(10000));

                Assert.Equal(expected, actual);
            }
        }
        public void Send_FromDicomClient_DoesNotDeadlock()
        {
            LogManager.SetImplementation(NLogManager.Instance);
            var target = NLogHelper.AssignMemoryTarget(
                "Dicom.Network",
                @"${message}",
                NLog.LogLevel.Trace);

            var port = Ports.GetNext();

            using (DicomServer.Create <DicomCEchoProvider>(port))
            {
                var client = new DicomClient();
                for (var i = 0; i < 10; i++)
                {
                    client.AddRequest(new DicomCEchoRequest());
                }

                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");
                Assert.True(target.Logs.Count > 0);
            }
        }
Example #35
0
        public void DicomCGetRequest_PickCTImagesInStudy_OnlyCTImagesRetrieved()
        {
            var client = new DicomClient();

            var pc = DicomPresentationContext.GetScpRolePresentationContext(DicomUID.CTImageStorage);

            client.AdditionalPresentationContexts.Add(pc);

            var counter = 0;
            var locker  = new object();

            client.OnCStoreRequest = request =>
            {
                lock (locker)
                {
                    ++counter;
                }

                return(new DicomCStoreResponse(request, DicomStatus.Success));
            };

            var get = new DicomCGetRequest("1.2.840.113619.2.55.3.2609388324.145.1222836278.84");

            var handle = new ManualResetEventSlim();

            get.OnResponseReceived = (request, response) =>
            {
                if (response.Remaining == 0)
                {
                    handle.Set();
                }
            };
            client.AddRequest(get);
            client.Send("localhost", 11112, false, "SCU", "COMMON");
            handle.Wait();

            Assert.Equal(140, counter);
        }
Example #36
0
        public void Send_MultipleRequests_AllRecognized(int expected)
        {
            int port = Ports.GetNext();

            using (DicomServer.Create <DicomCEchoProvider>(port))
            {
                var actual = 0;

                var client = new DicomClient();
                client.NegotiateAsyncOps(expected, 1);

                for (var i = 0; i < expected; ++i)
                {
                    client.AddRequest(new DicomCEchoRequest {
                        OnResponseReceived = (req, res) => Interlocked.Increment(ref actual)
                    });
                }

                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");

                Assert.Equal(expected, actual);
            }
        }
Example #37
0
        public void Send_PrivateRegisteredSOPClass_SendSucceeds()
        {
            var uid = new DicomUID("1.3.46.670589.11.0.0.12.1", "Private MR Spectrum Storage", DicomUidType.SOPClass);

            DicomUID.Register(uid);

            var port = Ports.GetNext();

            using (DicomServer.Create <SimpleCStoreProvider>(port))
            {
                DicomStatus status  = null;
                var         request = new DicomCStoreRequest(@".\Test Data\GH355.dcm");
                request.OnResponseReceived = (req, res) =>
                { status = res.Status; };

                var client = new DicomClient();
                client.AddRequest(request);

                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");

                Assert.Equal(DicomStatus.Success, status);
            }
        }
Example #38
0
        public void Send_PrivateNotRegisteredSOPClass_SendFails()
        {
            var          uid = new DicomUID("1.1.1.1", "Private Fo-Dicom Storage", DicomUidType.SOPClass);
            DicomDataset ds  = new DicomDataset(
                new DicomUniqueIdentifier(DicomTag.SOPClassUID, uid),
                new DicomUniqueIdentifier(DicomTag.SOPInstanceUID, "1.2.3.4.5"));
            var port = Ports.GetNext();

            using (DicomServer.Create <SimpleCStoreProvider>(port))
            {
                DicomStatus status  = null;
                var         request = new DicomCStoreRequest(new DicomFile(ds));
                request.OnResponseReceived = (req, res) =>
                { status = res.Status; };

                var client = new DicomClient();
                client.AddRequest(request);

                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");

                Assert.Equal(DicomStatus.SOPClassNotSupported, status);
            }
        }
Example #39
0
        public void Send_MultipleTimes_AllRecognized(int expected)
        {
            var port = Ports.GetNext();
            var flag = new ManualResetEventSlim();

            using (var server = DicomServer.Create <DicomCEchoProvider>(port))
            {
                while (!server.IsListening)
                {
                    Thread.Sleep(50);
                }

                var actual = 0;

                var client = new DicomClient();
                for (var i = 0; i < expected; ++i)
                {
                    client.AddRequest(
                        new DicomCEchoRequest
                    {
                        OnResponseReceived = (req, res) =>
                        {
                            _testOutputHelper.WriteLine($"{i}");
                            Interlocked.Increment(ref actual);
                            if (actual == expected)
                            {
                                flag.Set();
                            }
                        }
                    });
                    client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");
                }

                flag.Wait(10000);
                Assert.Equal(expected, actual);
            }
        }
Example #40
0
        public void DicomCGetRequest_OneImageInSeries_Received()
        {
            var client = new DicomClient();

            var pcs = DicomPresentationContext.GetScpRolePresentationContextsFromStorageUids(
                DicomStorageCategory.Image,
                DicomTransferSyntax.ExplicitVRLittleEndian,
                DicomTransferSyntax.ImplicitVRLittleEndian,
                DicomTransferSyntax.ImplicitVRBigEndian);

            client.AdditionalPresentationContexts.AddRange(pcs);

            DicomDataset dataset = null;

            client.OnCStoreRequest = request =>
            {
                dataset = request.Dataset;
                return(new DicomCStoreResponse(request, DicomStatus.Success));
            };

            var get = new DicomCGetRequest(
                "1.2.840.113619.2.1.1.322987881.621.736170080.681",
                "1.2.840.113619.2.1.2411.1031152382.365.736169244");

            var handle = new ManualResetEventSlim();

            get.OnResponseReceived = (request, response) =>
            {
                handle.Set();
            };
            client.AddRequest(get);
            client.Send("localhost", 11112, false, "SCU", "COMMON");
            handle.Wait();

            Assert.Equal("RT ANKLE", dataset.Get <string>(DicomTag.StudyDescription));
        }
Example #41
0
        public void DicomCGetRequest_PickCTImagesInStudy_OnlyCTImagesRetrieved()
        {
            var client = new DicomClient();
            client.Options = new DicomServiceOptions { IgnoreAsyncOps = true };

            var pc = DicomPresentationContext.GetScpRolePresentationContext(DicomUID.CTImageStorage);
            client.AdditionalPresentationContexts.Add(pc);

            var counter = 0;
            var locker = new object();
            client.OnCStoreRequest = request =>
            {
                lock (locker)
                {
                    ++counter;
                }

                return new DicomCStoreResponse(request, DicomStatus.Success);
            };

            var get = new DicomCGetRequest("1.2.840.113619.2.55.3.2609388324.145.1222836278.84");

            var handle = new ManualResetEventSlim();
            get.OnResponseReceived = (request, response) =>
            {
                if (response.Remaining == 0)
                {
                    handle.Set();
                }
            };
            client.AddRequest(get);
            client.Send("localhost", 11112, false, "SCU", "COMMON");
            handle.Wait();

            Assert.Equal(140, counter);
        }
Example #42
0
        public async Task SendAsync_MultipleTimes_AllRecognized(int expected)
        {
            var port = Ports.GetNext();
            var flag = new ManualResetEventSlim();

            using (var server = DicomServer.Create <DicomCEchoProvider>(port))
            {
                while (!server.IsListening)
                {
                    await Task.Delay(50);
                }

                var actual = 0;

                var client = new DicomClient();
                for (var i = 0; i < expected; i++)
                {
                    client.AddRequest(
                        new DicomCEchoRequest
                    {
                        OnResponseReceived = (req, res) =>
                        {
                            Interlocked.Increment(ref actual);
                            if (actual == expected)
                            {
                                flag.Set();
                            }
                        }
                    });
                    await client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");
                }

                flag.Wait(10000);
                Assert.Equal(expected, actual);
            }
        }
Example #43
0
        public async Task SendAsync_MultipleTimesParallel_AllRecognized(int expected)
        {
            int port = Ports.GetNext();

            using (
                var server = DicomServer.Create <DicomCEchoProvider>(port))
            {
                await Task.Delay(500);

                Assert.True(server.IsListening, "Server is not listening");

                var actual = 0;

                var requests = Enumerable.Range(0, expected).Select(
                    async requestIndex =>
                {
                    var client = new DicomClient();
                    client.AddRequest(
                        new DicomCEchoRequest
                    {
                        OnResponseReceived = (req, res) =>
                        {
                            _testOutputHelper.WriteLine("Response #{0}", requestIndex);
                            Interlocked.Increment(ref actual);
                        }
                    });

                    _testOutputHelper.WriteLine("Sending #{0}", requestIndex);
                    await client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");
                    _testOutputHelper.WriteLine("Sent (or timed out) #{0}", requestIndex);
                }).ToList();
                await Task.WhenAll(requests);

                Assert.Equal(expected, actual);
            }
        }
Example #44
0
 public async Task SendAsync_RejectedAssociation_ShouldYieldException()
 {
     var port = Ports.GetNext();
     using (DicomServer.Create<MockCEchoProvider>(port))
     {
         var client = new DicomClient();
         client.AddRequest(new DicomCEchoRequest());
         var exception =
             await
             Record.ExceptionAsync(() => client.SendAsync("127.0.0.1", port, false, "SCU", "INVALID"))
                 .ConfigureAwait(false);
         Assert.IsType<DicomAssociationRejectedException>(exception);
     }
 }
Example #45
0
        public void Send_RecordAssociationData_AssociationContainsHostAndPort()
        {
            int port = Ports.GetNext();
            using (DicomServer.Create<MockCEchoProvider>(port))
            {
                var client = new DicomClient();
                client.AddRequest(new DicomCEchoRequest());
                client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");

                Assert.NotNull(remoteHost);
                Assert.True(remotePort > 0);
                Assert.NotEqual(port, remotePort);
            }
        }
Example #46
0
        public async Task ReleaseAsync_AfterAssociation_SendIsCompleted()
        {
            int port = Ports.GetNext();
            using (DicomServer.Create<MockCEchoProvider>(port))
            {
                var client = new DicomClient();
                client.AddRequest(new DicomCEchoRequest());
                var task = client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");

                client.WaitForAssociation();

                await client.ReleaseAsync();
                Thread.Sleep(10);
                Assert.True(task.IsCompleted);
            }
        }
Example #47
0
        public async Task WaitForAssociationAsync_Aborted_ReturnsFalse()
        {
            int port = Ports.GetNext();
            using (DicomServer.Create<MockCEchoProvider>(port))
            {
                var client = new DicomClient();
                client.AddRequest(new DicomCEchoRequest());
                var task = client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");
                client.Abort();

                var actual = await client.WaitForAssociationAsync(500);

                Assert.Equal(false, actual);
            }
        }
Example #48
0
        public void WaitForAssociation_TooShortTimeout_ReturnsFalse()
        {
            int port = Ports.GetNext();
            using (DicomServer.Create<MockCEchoProvider>(port))
            {
                var client = new DicomClient();
                client.AddRequest(new DicomCEchoRequest());
                var task = client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");

                var actual = client.WaitForAssociation(1);
                task.Wait(10000);
                Assert.Equal(false, actual);
            }
        }
Example #49
0
        public async Task SendAsync_MultipleTimesParallel_AllRecognized(int expected)
        {
            int port = Ports.GetNext();

            using (
                var server = DicomServer.Create<DicomCEchoProvider>(port))
            {
                await Task.Delay(500);
                Assert.True(server.IsListening, "Server is not listening");

                var actual = 0;

                var requests = Enumerable.Range(0, expected).Select(
                    async requestIndex =>
                        {
                            var client = new DicomClient();
                            client.AddRequest(
                                new DicomCEchoRequest
                                    {
                                        OnResponseReceived = (req, res) =>
                                            {
                                                _testOutputHelper.WriteLine("Response #{0}", requestIndex);
                                                Interlocked.Increment(ref actual);
                                            }
                                    });

                            _testOutputHelper.WriteLine("Sending #{0}", requestIndex);
                            await client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");
                            _testOutputHelper.WriteLine("Sent (or timed out) #{0}", requestIndex);
                        }).ToList();
                await Task.WhenAll(requests);

                Assert.Equal(expected, actual);
            }
        }
Example #50
0
        public async Task SendAsync_MultipleRequests_AllRecognized(int expected)
        {
            int port = Ports.GetNext();
            using (DicomServer.Create<DicomCEchoProvider>(port))
            {
                var actual = 0;

                var client = new DicomClient();
                client.NegotiateAsyncOps(expected, 1);

                for (var i = 0; i < expected; ++i) client.AddRequest(new DicomCEchoRequest { OnResponseReceived = (req, res) => ++actual });

                var task = client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");
                await Task.WhenAny(task, Task.Delay(10000));

                Assert.Equal(expected, actual);
            }
        }
Example #51
0
        public async Task SendAsync_SingleRequest_Recognized()
        {
            int port = Ports.GetNext();
            using (DicomServer.Create<DicomCEchoProvider>(port))
            {
                var counter = 0;
                var request = new DicomCEchoRequest { OnResponseReceived = (req, res) => ++counter };

                var client = new DicomClient();
                client.AddRequest(request);

                var task = client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");
                await Task.WhenAny(task, Task.Delay(10000));

                Assert.Equal(1, counter);
            }
        }
Example #52
0
        public async Task SendAsync_MultipleTimes_AllRecognized(int expected)
        {
            int port = Ports.GetNext();
            var @lock = new object();

            using (new DicomServer<DicomCEchoProvider>(port))
            {
                var actual = 0;

                var client = new DicomClient();
                for (var i = 0; i < expected; ++i)
                {
                    client.AddRequest(new DicomCEchoRequest { OnResponseReceived = (req, res) => { lock (@lock) ++actual; } });
                    var task = client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");
                    await Task.WhenAny(task, Task.Delay(1000));
                }

                Assert.Equal(expected, actual);
            }
        }
Example #53
0
        public async Task WaitForAssociationAsync_WithinTimeout_ReturnsTrue()
        {
            int port = Ports.GetNext();
            using (new DicomServer<MockCEchoProvider>(port))
            {
                var client = new DicomClient();
                client.AddRequest(new DicomCEchoRequest());
                var task = client.SendAsync("127.0.0.1", port, false, "SCU", "ANY-SCP");

                var actual = await client.WaitForAssociationAsync(10000);
                task.Wait(10000);
                Assert.Equal(true, actual);
            }
        }
Example #54
0
        private static void Main(string[] args)
        {
            try
            {
                // Initialize log manager.
                LogManager.SetImplementation(NLogManager.Instance);

                DicomException.OnException += delegate(object sender, DicomExceptionEventArgs ea)
                    {
                        ConsoleColor old = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine(ea.Exception);
                        Console.ForegroundColor = old;
                    };

                var config = new LoggingConfiguration();

                var target = new ColoredConsoleTarget();
                target.Layout = @"${date:format=HH\:mm\:ss}  ${message}";
                config.AddTarget("Console", target);
                config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Debug, target));

                NLog.LogManager.Configuration = config;

                //var server = new DicomServer<DicomCEchoProvider>(12345);


                var client = new DicomClient();
                //client.NegotiateAsyncOps();
                //for (int i = 0; i < 10; i++)
                //    client.AddRequest(new DicomCEchoRequest());
                client.AddRequest(new DicomCStoreRequest(@"Z:\test1.dcm"));
                client.AddRequest(new DicomCStoreRequest(@"Z:\test2.dcm"));
                client.Send("127.0.0.1", 104, false, "SCU", "ANY-SCP");

                foreach (DicomPresentationContext ctr in client.AdditionalPresentationContexts)
                {
                    Console.WriteLine("PresentationContext: " + ctr.AbstractSyntax + " Result: " + ctr.Result);
                }

                var samplesDir = Path.Combine(
                    Path.GetPathRoot(Environment.CurrentDirectory),
                    "Development",
                    "fo-dicom-samples");
                var testDir = Path.Combine(samplesDir, "Test");

                if (!Directory.Exists(testDir)) Directory.CreateDirectory(testDir);

                //var img = new DicomImage(samplesDir + @"\ClearCanvas\CRStudy\1.3.51.5145.5142.20010109.1105627.1.0.1.dcm");
                //img.RenderImage().Save(testDir + @"\test.jpg");

                //var df = DicomFile.Open(samplesDir + @"\User Submitted\overlays.dcm");

                //Console.WriteLine(df.FileMetaInfo.Get<DicomTransferSyntax>(DicomTag.TransferSyntaxUID).UID.Name);
                //Console.WriteLine(df.Dataset.Get<PlanarConfiguration>(DicomTag.PlanarConfiguration));

                //var img = new DicomImage(df.Dataset);
                //img.RenderImage().Save(testDir + @"\test.jpg");

                //df = df.ChangeTransferSyntax(DicomTransferSyntax.JPEGLSLossless);
                //df.Save(testDir + @"\test-jls.dcm");

                //df = df.ChangeTransferSyntax(DicomTransferSyntax.JPEG2000Lossless);
                //df.Save(testDir + @"\test-j2k.dcm");

                //df = df.ChangeTransferSyntax(DicomTransferSyntax.JPEGProcess14SV1);
                //df.Save(testDir + @"\test-jll.dcm");

                //df = df.ChangeTransferSyntax(DicomTransferSyntax.RLELossless);
                //df.Save(testDir + @"\test-rle.dcm");

                //df = df.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRLittleEndian);
                //df.Save(testDir + @"\test-ele.dcm");

                //df = df.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRBigEndian);
                //df.Save(testDir + @"\test-ebe.dcm");

                //df = df.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRLittleEndian);
                //df.Save(testDir + @"\test-ile.dcm");

                //Console.WriteLine("End...");
                //Console.ReadLine();

                //df.WriteToLog(LogManager.GetCurrentClassLogger(), LogLevel.Info);

                //Console.WriteLine(DicomValueMultiplicity.Parse("1"));
                //Console.WriteLine(DicomValueMultiplicity.Parse("3"));
                //Console.WriteLine(DicomValueMultiplicity.Parse("1-3"));
                //Console.WriteLine(DicomValueMultiplicity.Parse("1-n"));
                //Console.WriteLine(DicomValueMultiplicity.Parse("2-2n"));

                //Console.WriteLine(DicomTag.Parse("00200020"));
                //Console.WriteLine(DicomTag.Parse("0008,0040"));
                //Console.WriteLine(DicomTag.Parse("(3000,0012)"));
                //Console.WriteLine(DicomTag.Parse("2000,2000:TEST CREATOR"));
                //Console.WriteLine(DicomTag.Parse("(4000,4000:TEST_CREATOR:2)"));

                //Console.WriteLine(DicomMaskedTag.Parse("(30xx,xx90)"));
                //Console.WriteLine(DicomMaskedTag.Parse("(3000-3021,0016)"));

                //DicomRange<DateTime> r = new DicomRange<DateTime>(DateTime.Now.AddSeconds(-5), DateTime.Now.AddSeconds(5));
                //Console.WriteLine(r.Contains(DateTime.Now));
                //Console.WriteLine(r.Contains(DateTime.Today));
                //Console.WriteLine(r.Contains(DateTime.Now.AddSeconds(60)));

                //DicomDictionary dict = new DicomDictionary();
                //dict.Load(@"F:\Development\fo-dicom\DICOM\Dictionaries\dictionary.xml", DicomDictionaryFormat.XML);

                //string output = Dicom.Generators.DicomTagGenerator.Generate("Dicom", "DicomTag", dict);
                //File.WriteAllText(@"F:\Development\fo-dicom\DICOM\DicomTagGenerated.cs", output);

                //output = Dicom.Generators.DicomDictionaryGenerator.Generate("Dicom", "DicomDictionary", "LoadInternalDictionary", dict);
                //File.WriteAllText(@"F:\Development\fo-dicom\DICOM\DicomDictionaryGenerated.cs", output);

                //string output = Dicom.Generators.DicomUIDGenerator.Process(@"F:\Development\fo-dicom\DICOM\Dictionaries\dictionary.xml");
                //File.WriteAllText(@"F:\Development\fo-dicom\DICOM\DicomUIDGenerated.cs", output);
            }
            catch (Exception e)
            {
                if (!(e is DicomException)) Console.WriteLine(e.ToString());
            }
        }
Example #55
0
        public void Send_EchoRequestToExternalServer_ShouldSucceed()
        {
            var result = false;
            var awaiter = new ManualResetEventSlim();

            var client = new DicomClient();
            var req = new DicomCEchoRequest();
            req.OnResponseReceived = (rq, rsp) =>
                {
                    if (rsp.Status == DicomStatus.Success)
                    {
                        result = true;
                    }
                    awaiter.Set();
                };
            client.AddRequest(req);

            try
            {
                client.Send("localhost", 11112, false, "SCU", "COMMON");
                awaiter.Wait();
            }
            catch (Exception ex)
            {
                result = false;
                Console.WriteLine(ex);
                awaiter.Set();
            }

            Assert.True(result);
        }
Example #56
0
 public DicomServiceUser(DicomClient client, Stream stream, DicomAssociation association, Logger log)
     : base(stream, log)
 {
     _client = client;
     if (_client.Options != null) Options = _client.Options;
     SendAssociationRequest(association);
 }
Example #57
0
        public void Print()
        {
            var dicomClient = new DicomClient();
            dicomClient.AddRequest(new DicomNCreateRequest(FilmSession.SOPClassUID, FilmSession.SOPInstanceUID, 0)
            {
                Dataset = FilmSession
            });


            foreach (var filmbox in FilmSession.BasicFilmBoxes)
            {

                var imageBoxRequests = new List<DicomNSetRequest>();

                var filmBoxRequest = new DicomNCreateRequest(FilmBox.SOPClassUID, filmbox.SOPInstanceUID, 0)
                {
                    Dataset = filmbox
                };
                filmBoxRequest.OnResponseReceived = (request, response) =>
                {
                    if (response.HasDataset)
                    {
                        var seq = response.Dataset.Get<DicomSequence>(DicomTag.ReferencedImageBoxSequence);
                        for (int i = 0; i < seq.Items.Count; i++)
                        {
                            var req = imageBoxRequests[i];
                            var imageBox = req.Dataset;
                            var sopInstanceUid = seq.Items[i].Get<string>(DicomTag.ReferencedSOPInstanceUID);
                            imageBox.Add(DicomTag.SOPInstanceUID, sopInstanceUid);
                            req.Command.Add(DicomTag.RequestedSOPInstanceUID, sopInstanceUid);
                        }
                    }
                };
                dicomClient.AddRequest(filmBoxRequest);



                foreach (var image in filmbox.BasicImageBoxes)
                {
                    var req = new DicomNSetRequest(image.SOPClassUID, image.SOPInstanceUID)
                    {
                        Dataset = image
                    };

                    imageBoxRequests.Add(req);
                    dicomClient.AddRequest(req);
                }
            }

            dicomClient.AddRequest(new DicomNActionRequest(FilmSession.SOPClassUID, FilmSession.SOPInstanceUID, 0x0001));

            dicomClient.Send(RemoteAddress, RemotePort, false, CallingAE, CalledAE);
        }
Example #58
0
        //[InlineData(100)]
        public void Send_MultipleTimes_AllRecognized(int expected)
        {
            int port = Ports.GetNext();

            using (var server = DicomServer.Create<DicomCEchoProvider>(port))
            {
                while (!server.IsListening) Thread.Sleep(50);

                var actual = 0;

                var client = new DicomClient();
                for (var i = 0; i < expected; ++i)
                {
                    client.AddRequest(new DicomCEchoRequest { OnResponseReceived = (req, res) => Interlocked.Increment(ref actual) });
                    client.Send("127.0.0.1", port, false, "SCU", "ANY-SCP");
                }

                client.Release();
                Assert.Equal(expected, actual);
            }
        }
Example #59
0
 internal DicomServiceUser(
     DicomClient client,
     Stream stream,
     DicomAssociation association,
     DicomServiceOptions options,
     Logger log)
     : base(stream, log)
 {
     this.client = client;
     this.isLingering = false;
     if (options != null) this.Options = options;
     this.SendAssociationRequest(association);
 }
Example #60
-1
        public DicomSender(String targetIP, int port, String callingAE, String calledAE, Boolean useTLS = false)
        {
            this.targetIP = targetIP;
            this.port = port;
            this.useTLS = useTLS;
            this.callingAE = callingAE;
            this.calledAE = calledAE;

            client = new DicomClient();
        }