private static DicomDataset ReadFragment(byte[] bytes, Endian endian, bool explicitVr)
 {
   var dataset = new DicomDataset();
   var reader = new DicomReader { IsExplicitVR = explicitVr };
   var byteSource = new ByteBufferByteSource(new MemoryByteBuffer(bytes)) { Endian = endian };
   reader.Read(byteSource, new DicomDatasetReaderObserver(dataset));
   return dataset;
 }
예제 #2
0
 public static IAsyncResult BeginRead(
     this DicomReader @this,
     IByteSource source,
     IDicomReaderObserver observer,
     Func <ParseState, bool> stop,
     AsyncCallback callback,
     object state)
 {
     return(AsyncFactory.ToBegin(@this.ReadAsync(source, observer, stop), callback, state));
 }
예제 #3
0
        public void Read_ValidExplicitVRSequence_YieldsSuccess(byte[] bytes)
        {
            var stream = new MemoryStream(bytes);
            var source = new StreamByteSource(stream);
            var reader = new DicomReader {
                IsExplicitVR = true
            };

            var observer = new MockObserver();
            var result   = reader.Read(source, observer);

            Assert.Equal(DicomReaderResult.Success, result);
        }
예제 #4
0
        public void BeginRead_ValidExplicitVRData_YieldsSuccess(DicomTag tag, DicomVR vr, string data, byte[] bytes)
        {
            var stream = new MemoryStream(bytes);
            var source = new StreamByteSource(stream);
            var reader = new DicomReader { IsExplicitVR = true };

            var observer = new LastElementObserver();
            var result = reader.EndRead(reader.BeginRead(source, observer, null, null, null));

            Assert.Equal(DicomReaderResult.Success, result);
            Assert.Equal(tag, observer.Tag);
            Assert.Equal(vr, observer.VR);
            Assert.Equal(data, observer.Data);
        }
    private DicomDataset DeepClone_(DicomDataset dataset)
    {
      var ms = new MemoryStream();
      var target = new StreamByteTarget(ms);
      var writer = new DicomWriter(DicomTransferSyntax.ImplicitVRLittleEndian, DicomWriteOptions.Default, target);
      var walker = new DicomDatasetWalker(dataset);
      walker.Walk(writer);

      var clone = new DicomDataset();
      var reader = new DicomReader { IsExplicitVR = false };
      var byteSource = new ByteBufferByteSource(
        new MemoryByteBuffer(ms.ToArray()));
      reader.Read(byteSource, new DicomDatasetReaderObserver(clone));
      return clone;
    }
예제 #6
0
        public void BeginRead_ValidExplicitVRData_YieldsSuccess(DicomTag tag, DicomVR vr, string data, byte[] bytes)
        {
            var stream = new MemoryStream(bytes);
            var source = new StreamByteSource(stream);
            var reader = new DicomReader {
                IsExplicitVR = true
            };

            var observer = new LastElementObserver();
            var result   = reader.EndRead(reader.BeginRead(source, observer, null, null, null));

            Assert.Equal(DicomReaderResult.Success, result);
            Assert.Equal(tag, observer.Tag);
            Assert.Equal(vr, observer.VR);
            Assert.Equal(data, observer.Data);
        }
예제 #7
0
 public static DicomReaderResult EndRead(this DicomReader @this, IAsyncResult result)
 {
     return(AsyncFactory.ToEnd <DicomReaderResult>(result));
 }
예제 #8
0
        private static async Task <Tuple <DicomReaderResult, DicomFileFormat, DicomTransferSyntax> > DoParseAsync(
            IByteSource source,
            IDicomReaderObserver fileMetasetInfoObserver,
            IDicomReaderObserver datasetObserver,
            Func <ParseState, bool> stop,
            DicomTransferSyntax syntax,
            DicomFileFormat fileFormat)
        {
            string code = null, uid = null;
            var    obs = new DicomReaderCallbackObserver();

            if (fileFormat != DicomFileFormat.DICOM3)
            {
                obs.Add(
                    DicomTag.RecognitionCodeRETIRED,
                    (sender, ea) =>
                {
                    try
                    {
                        code = Encoding.UTF8.GetString(ea.Data.Data, 0, ea.Data.Data.Length);
                    }
                    catch
                    {
                    }
                });
            }
            obs.Add(
                DicomTag.TransferSyntaxUID,
                (sender, ea) =>
            {
                try
                {
                    uid = Encoding.UTF8.GetString(ea.Data.Data, 0, ea.Data.Data.Length);
                }
                catch
                {
                }
            });

            var reader = new DicomReader {
                IsExplicitVR = syntax.IsExplicitVR, IsDeflated = false
            };

            DicomReaderResult result;

            if (fileFormat == DicomFileFormat.DICOM3NoFileMetaInfo)
            {
                result =
                    await
                    reader.ReadAsync(source, new DicomReaderMultiObserver(obs, datasetObserver), stop).ConfigureAwait(false);

                UpdateFileFormatAndSyntax(code, uid, ref fileFormat, ref syntax);
            }
            else
            {
                if (
                    await
                    reader.ReadAsync(
                        source,
                        new DicomReaderMultiObserver(obs, fileMetasetInfoObserver),
                        _FileMetaInfoStopCriterion).ConfigureAwait(false) != DicomReaderResult.Stopped)
                {
                    throw new DicomReaderException("DICOM File Meta Info ended prematurely");
                }

                UpdateFileFormatAndSyntax(code, uid, ref fileFormat, ref syntax);

                // rewind to last marker (start of previous tag)... ugly because
                // it requires knowledge of how the parser is implemented
                source.Rewind();

                source.Endian       = syntax.Endian;
                reader.IsExplicitVR = syntax.IsExplicitVR;
                reader.IsDeflated   = syntax.IsDeflate;
                result = await reader.ReadAsync(source, datasetObserver, stop).ConfigureAwait(false);
            }

            return(Tuple.Create(result, fileFormat, syntax));
        }
예제 #9
0
        /// <summary>
        /// Process P-DATA-TF PDUs.
        /// </summary>
        /// <param name="pdu">PDU to process.</param>
        private async Task ProcessPDataTFAsync(PDataTF pdu)
        {
            try
            {
                foreach (var pdv in pdu.PDVs)
                {
                    if (_dimse == null)
                    {
                        // create stream for receiving command
                        if (_dimseStream == null)
                        {
                            _dimseStream = new MemoryStream();
                            _dimseStreamFile = null;
                        }
                    }
                    else
                    {
                        // create stream for receiving dataset
                        if (_dimseStream == null)
                        {
                            if (_dimse.Type == DicomCommandField.CStoreRequest)
                            {
                                var pc = Association.PresentationContexts.FirstOrDefault(x => x.ID == pdv.PCID);

                                var file = new DicomFile();
                                file.FileMetaInfo.MediaStorageSOPClassUID = pc.AbstractSyntax;
                                file.FileMetaInfo.MediaStorageSOPInstanceUID =
                                    _dimse.Command.Get<DicomUID>(DicomTag.AffectedSOPInstanceUID);
                                file.FileMetaInfo.TransferSyntax = pc.AcceptedTransferSyntax;
                                file.FileMetaInfo.ImplementationClassUID = Association.RemoteImplemetationClassUID;
                                file.FileMetaInfo.ImplementationVersionName = Association.RemoteImplementationVersion;
                                file.FileMetaInfo.SourceApplicationEntityTitle = Association.CallingAE;

                                CreateCStoreReceiveStream(file);
                            }
                            else
                            {
                                _dimseStream = new MemoryStream();
                                _dimseStreamFile = null;
                            }
                        }
                    }

                    await this._dimseStream.WriteAsync(pdv.Value, 0, pdv.Value.Length).ConfigureAwait(false);

                    if (pdv.IsLastFragment)
                    {
                        if (pdv.IsCommand)
                        {
                            _dimseStream.Seek(0, SeekOrigin.Begin);

                            var command = new DicomDataset();

                            var reader = new DicomReader();
                            reader.IsExplicitVR = false;
                            reader.Read(new StreamByteSource(_dimseStream), new DicomDatasetReaderObserver(command));

                            _dimseStream = null;
                            _dimseStreamFile = null;

                            var type = command.Get<DicomCommandField>(DicomTag.CommandField);
                            switch (type)
                            {
                                case DicomCommandField.CStoreRequest:
                                    _dimse = new DicomCStoreRequest(command);
                                    break;
                                case DicomCommandField.CStoreResponse:
                                    _dimse = new DicomCStoreResponse(command);
                                    break;
                                case DicomCommandField.CFindRequest:
                                    _dimse = new DicomCFindRequest(command);
                                    break;
                                case DicomCommandField.CFindResponse:
                                    _dimse = new DicomCFindResponse(command);
                                    break;
                                case DicomCommandField.CMoveRequest:
                                    _dimse = new DicomCMoveRequest(command);
                                    break;
                                case DicomCommandField.CMoveResponse:
                                    _dimse = new DicomCMoveResponse(command);
                                    break;
                                case DicomCommandField.CEchoRequest:
                                    _dimse = new DicomCEchoRequest(command);
                                    break;
                                case DicomCommandField.CEchoResponse:
                                    _dimse = new DicomCEchoResponse(command);
                                    break;
                                case DicomCommandField.NActionRequest:
                                    _dimse = new DicomNActionRequest(command);
                                    break;
                                case DicomCommandField.NActionResponse:
                                    _dimse = new DicomNActionResponse(command);
                                    break;
                                case DicomCommandField.NCreateRequest:
                                    _dimse = new DicomNCreateRequest(command);
                                    break;
                                case DicomCommandField.NCreateResponse:
                                    _dimse = new DicomNCreateResponse(command);
                                    break;
                                case DicomCommandField.NDeleteRequest:
                                    _dimse = new DicomNDeleteRequest(command);
                                    break;
                                case DicomCommandField.NDeleteResponse:
                                    _dimse = new DicomNDeleteResponse(command);
                                    break;
                                case DicomCommandField.NEventReportRequest:
                                    _dimse = new DicomNEventReportRequest(command);
                                    break;
                                case DicomCommandField.NEventReportResponse:
                                    _dimse = new DicomNEventReportResponse(command);
                                    break;
                                case DicomCommandField.NGetRequest:
                                    _dimse = new DicomNGetRequest(command);
                                    break;
                                case DicomCommandField.NGetResponse:
                                    _dimse = new DicomNGetResponse(command);
                                    break;
                                case DicomCommandField.NSetRequest:
                                    _dimse = new DicomNSetRequest(command);
                                    break;
                                case DicomCommandField.NSetResponse:
                                    _dimse = new DicomNSetResponse(command);
                                    break;
                                default:
                                    _dimse = new DicomMessage(command);
                                    break;
                            }
                            _dimse.PresentationContext =
                                Association.PresentationContexts.FirstOrDefault(x => x.ID == pdv.PCID);
                            if (!_dimse.HasDataset)
                            {
                                this.PerformDimse(this._dimse);
                                _dimse = null;
                                return;
                            }
                        }
                        else
                        {
                            if (_dimse.Type != DicomCommandField.CStoreRequest)
                            {
                                _dimseStream.Seek(0, SeekOrigin.Begin);

                                var pc = Association.PresentationContexts.FirstOrDefault(x => x.ID == pdv.PCID);

                                _dimse.Dataset = new DicomDataset();
                                _dimse.Dataset.InternalTransferSyntax = pc.AcceptedTransferSyntax;

                                var source = new StreamByteSource(_dimseStream);
                                source.Endian = pc.AcceptedTransferSyntax.Endian;

                                var reader = new DicomReader();
                                reader.IsExplicitVR = pc.AcceptedTransferSyntax.IsExplicitVR;
                                reader.Read(source, new DicomDatasetReaderObserver(_dimse.Dataset));

                                _dimseStream = null;
                                _dimseStreamFile = null;
                            }
                            else
                            {
                                var request = _dimse as DicomCStoreRequest;

                                try
                                {
                                    var dicomFile = GetCStoreDicomFile();
                                    _dimseStream = null;
                                    _dimseStreamFile = null;

                                    // NOTE: dicomFile will be valid with the default implementation of CreateCStoreReceiveStream() and
                                    // GetCStoreDicomFile(), but can be null if a child class overrides either method and changes behavior.
                                    // See documentation on CreateCStoreReceiveStream() and GetCStoreDicomFile() for information about why
                                    // this might be desired.
                                    request.File = dicomFile;
                                    if (request.File != null)
                                    {
                                        request.Dataset = request.File.Dataset;
                                    }
                                }
                                catch (Exception e)
                                {
                                    // failed to parse received DICOM file; send error response instead of aborting connection
                                    SendResponse(
                                        new DicomCStoreResponse(
                                            request,
                                            new DicomStatus(DicomStatus.ProcessingFailure, e.Message)));
                                    Logger.Error("Error parsing C-Store dataset: {@error}", e);
                                    (this as IDicomCStoreProvider).OnCStoreRequestException(
                                        _dimseStreamFile != null ? _dimseStreamFile.Name : null, e);
                                    return;
                                }
                            }

                            this.PerformDimse(this._dimse);
                            _dimse = null;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                SendAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified);
                Logger.Error("Exception processing P-Data-TF PDU: {@error}", e);
            }
            finally
            {
                SendNextMessage();
            }
        }
예제 #10
0
        private static async Task<Tuple<DicomReaderResult, DicomFileFormat, DicomTransferSyntax>> DoParseAsync(
            IByteSource source,
            IDicomReaderObserver fileMetasetInfoObserver,
            IDicomReaderObserver datasetObserver,
            Func<ParseState, bool> stop,
            DicomTransferSyntax syntax,
            DicomFileFormat fileFormat)
        {
            string code = null, uid = null;
            var obs = new DicomReaderCallbackObserver();
            if (fileFormat != DicomFileFormat.DICOM3)
            {
                obs.Add(
                    DicomTag.RecognitionCodeRETIRED,
                    (sender, ea) =>
                        {
                            try
                            {
                                code = Encoding.UTF8.GetString(ea.Data.Data, 0, ea.Data.Data.Length);
                            }
                            catch
                            {
                            }
                        });
            }
            obs.Add(
                DicomTag.TransferSyntaxUID,
                (sender, ea) =>
                    {
                        try
                        {
                            uid = Encoding.UTF8.GetString(ea.Data.Data, 0, ea.Data.Data.Length);
                        }
                        catch
                        {
                        }
                    });

            var reader = new DicomReader { IsExplicitVR = syntax.IsExplicitVR, IsDeflated = false };

            DicomReaderResult result;
            if (fileFormat == DicomFileFormat.DICOM3NoFileMetaInfo)
            {
                result =
                    await
                    reader.ReadAsync(source, new DicomReaderMultiObserver(obs, datasetObserver), stop).ConfigureAwait(false);
                UpdateFileFormatAndSyntax(code, uid, ref fileFormat, ref syntax);
            }
            else
            {
                if (
                    await
                    reader.ReadAsync(
                        source,
                        new DicomReaderMultiObserver(obs, fileMetasetInfoObserver),
                        FileMetaInfoStopCriterion).ConfigureAwait(false) != DicomReaderResult.Stopped)
                {
                    throw new DicomReaderException("DICOM File Meta Info ended prematurely");
                }

                UpdateFileFormatAndSyntax(code, uid, ref fileFormat, ref syntax);

                // rewind to last marker (start of previous tag)... ugly because 
                // it requires knowledge of how the parser is implemented
                source.Rewind();

                source.Endian = syntax.Endian;
                reader.IsExplicitVR = syntax.IsExplicitVR;
                reader.IsDeflated = syntax.IsDeflate;
                result = await reader.ReadAsync(source, datasetObserver, stop).ConfigureAwait(false);
            }

            return Tuple.Create(result, fileFormat, syntax);
        }
예제 #11
0
		private void ProcessPDataTF(object state) {
			var pdu = (PDataTF)state;
			try {
				foreach (var pdv in pdu.PDVs) {
					if (_dimse == null) {
						// create stream for receiving command
						if (_dimseStream == null)
							_dimseStream = new MemoryStream();
					} else {
						// create stream for receiving dataset
						if (_dimseStream == null) {
							if (_dimse.Type == DicomCommandField.CStoreRequest) {
								var pc = Association.PresentationContexts.FirstOrDefault(x => x.ID == pdv.PCID);

								var file = new DicomFile();
								file.FileMetaInfo.MediaStorageSOPClassUID = pc.AbstractSyntax;
								file.FileMetaInfo.MediaStorageSOPInstanceUID = _dimse.Command.Get<DicomUID>(DicomTag.AffectedSOPInstanceUID);
								file.FileMetaInfo.TransferSyntax = pc.AcceptedTransferSyntax;
								file.FileMetaInfo.ImplementationClassUID = Association.RemoteImplemetationClassUID;
								file.FileMetaInfo.ImplementationVersionName = Association.RemoteImplementationVersion;
								file.FileMetaInfo.SourceApplicationEntityTitle = Association.CallingAE;

								var fileName = TemporaryFile.Create();

								file.Save(fileName);

								_dimseStream = File.OpenWrite(fileName);
								_dimseStream.Seek(0, SeekOrigin.End);
							} else {
								_dimseStream = new MemoryStream();
							}
						}
					}

					_dimseStream.Write(pdv.Value, 0, pdv.Value.Length);

					if (pdv.IsLastFragment) {
						if (pdv.IsCommand) {
							_dimseStream.Seek(0, SeekOrigin.Begin);

							var command = new DicomDataset();

							var reader = new DicomReader();
							reader.IsExplicitVR = false;
							reader.Read(new StreamByteSource(_dimseStream), new DicomDatasetReaderObserver(command));

							_dimseStream = null;

							var type = command.Get<DicomCommandField>(DicomTag.CommandField);
							switch (type) {
							case DicomCommandField.CStoreRequest:
								_dimse = new DicomCStoreRequest(command);
								break;
							case DicomCommandField.CStoreResponse:
								_dimse = new DicomCStoreResponse(command);
								break;
							case DicomCommandField.CFindRequest:
								_dimse = new DicomCFindRequest(command);
								break;
							case DicomCommandField.CFindResponse:
								_dimse = new DicomCFindResponse(command);
								break;
							case DicomCommandField.CMoveRequest:
								_dimse = new DicomCMoveRequest(command);
								break;
							case DicomCommandField.CMoveResponse:
								_dimse = new DicomCMoveResponse(command);
								break;
							case DicomCommandField.CEchoRequest:
								_dimse = new DicomCEchoRequest(command);
								break;
							case DicomCommandField.CEchoResponse:
								_dimse = new DicomCEchoResponse(command);
								break;
							case DicomCommandField.NActionRequest:
								_dimse = new DicomNActionRequest(command);
								break;
							case DicomCommandField.NActionResponse:
								_dimse = new DicomNActionResponse(command);
								break;
							case DicomCommandField.NCreateRequest:
								_dimse = new DicomNCreateRequest(command);
								break;
							case DicomCommandField.NCreateResponse:
								_dimse = new DicomNCreateResponse(command);
								break;
							case DicomCommandField.NDeleteRequest:
								_dimse = new DicomNDeleteRequest(command);
								break;
							case DicomCommandField.NDeleteResponse:
								_dimse = new DicomNDeleteResponse(command);
								break;
							case DicomCommandField.NEventReportRequest:
								_dimse = new DicomNEventReportRequest(command);
								break;
							case DicomCommandField.NEventReportResponse:
								_dimse = new DicomNEventReportResponse(command);
								break;
							case DicomCommandField.NGetRequest:
								_dimse = new DicomNGetRequest(command);
								break;
							case DicomCommandField.NGetResponse:
								_dimse = new DicomNGetResponse(command);
								break;
							case DicomCommandField.NSetRequest:
								_dimse = new DicomNSetRequest(command);
								break;
							case DicomCommandField.NSetResponse:
								_dimse = new DicomNSetResponse(command);
								break;
							default:
								_dimse = new DicomMessage(command);
								break;
							}

							if (!_dimse.HasDataset) {
								if (DicomMessage.IsRequest(_dimse.Type))
									ThreadPool.QueueUserWorkItem(PerformDimseCallback, _dimse);
								else
									_processQueue.Queue((_dimse as DicomResponse).RequestMessageID, PerformDimseCallback, _dimse);
								_dimse = null;
								return;
							}
						} else {
							if (_dimse.Type != DicomCommandField.CStoreRequest) {
								_dimseStream.Seek(0, SeekOrigin.Begin);

								var pc = Association.PresentationContexts.FirstOrDefault(x => x.ID == pdv.PCID);

								_dimse.Dataset = new DicomDataset();
								_dimse.Dataset.InternalTransferSyntax = pc.AcceptedTransferSyntax;

								var source = new StreamByteSource(_dimseStream);
								source.Endian = pc.AcceptedTransferSyntax.Endian;

								var reader = new DicomReader();
								reader.IsExplicitVR = pc.AcceptedTransferSyntax.IsExplicitVR;
								reader.Read(source, new DicomDatasetReaderObserver(_dimse.Dataset));

								_dimseStream = null;
							} else {
								var fileName = (_dimseStream as FileStream).Name;
								_dimseStream.Close();
								_dimseStream = null;

								var request = _dimse as DicomCStoreRequest;

								try {
									request.File = DicomFile.Open(fileName);
								} catch (Exception e) {
									// failed to parse received DICOM file; send error response instead of aborting connection
									SendResponse(new DicomCStoreResponse(request, new DicomStatus(DicomStatus.ProcessingFailure, e.Message)));
									Logger.Error("Error parsing C-Store dataset: " + e.ToString());
									(this as IDicomCStoreProvider).OnCStoreRequestException(fileName, e);
									return;
								}

								request.File.File.IsTempFile = true;
								request.Dataset = request.File.Dataset;
							}

							if (DicomMessage.IsRequest(_dimse.Type))
								ThreadPool.QueueUserWorkItem(PerformDimseCallback, _dimse);
							else
								_processQueue.Queue((_dimse as DicomResponse).RequestMessageID, PerformDimseCallback, _dimse);
							_dimse = null;
						}
					}
				}
			} catch (Exception e) {
				SendAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified);
				Logger.Error("Exception processing P-Data-TF PDU: " + e.ToString());
			} finally {
				SendNextMessage();
			}
		}
예제 #12
-1
        public void Read_ValidExplicitVRSequence_YieldsSuccess(byte[] bytes)
        {
            var stream = new MemoryStream(bytes);
            var source = new StreamByteSource(stream);
            var reader = new DicomReader { IsExplicitVR = true };

            var observer = new MockObserver();
            var result = reader.Read(source, observer);

            Assert.Equal(DicomReaderResult.Success, result);
        }