Exemplo n.º 1
0
        /// <inheritdoc/>
        public async Task WriteRetryableExceptionAsync(ChangeFeedEntry changeFeedEntry, int retryNum, Exception exceptionToStore, CancellationToken cancellationToken)
        {
            string tableName = Constants.TransientRetryTableName;

            DicomDataset dataset            = changeFeedEntry.Metadata;
            string       studyUid           = dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID);
            string       seriesUid          = dataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID);
            string       instanceUid        = dataset.GetSingleValue <string>(DicomTag.SOPInstanceUID);
            long         changeFeedSequence = changeFeedEntry.Sequence;

            CloudTable  table  = _client.GetTableReference(tableName);
            TableEntity entity = new RetryableEntity(studyUid, seriesUid, instanceUid, changeFeedSequence, retryNum, exceptionToStore);

            TableOperation operation = TableOperation.InsertOrMerge(entity);

            try
            {
                await table.ExecuteAsync(operation, cancellationToken);

                _logger.LogInformation("Retryable error when processsing changefeed entry: {ChangeFeedSequence} for DICOM instance with StudyUID: {StudyUID}, SeriesUID: {SeriesUID}, InstanceUID: {InstanceUID}. Tried {retryNum} time(s). Stored into table: {Table} in table storage.", changeFeedSequence, studyUid, seriesUid, instanceUid, retryNum, tableName);
            }
            catch
            {
                _logger.LogInformation("Retryable error when processsing changefeed entry: {ChangeFeedSequence} for DICOM instance with StudyUID: {StudyUID}, SeriesUID: {SeriesUID}, InstanceUID: {InstanceUID}. Tried {retryNum} time(s). Failed to store to table storage.", changeFeedSequence, studyUid, seriesUid, instanceUid, retryNum);
                throw;
            }
        }
Exemplo n.º 2
0
        public ImageRecord AddImageItem(DicomDataset dicom)
        {
            string seriesUID = dicom.GetSingleValue <string>(DicomTag.SeriesInstanceUID);
            var    series    = SeriesCollection.FirstOrDefault(s => s.SeriesUID == seriesUID);

            if (series == null)
            {
                series = DicomRecord.ToSeries(dicom);
                _seriesItems.Add(series);
                // Add new series.
                AddNewSeriesEvent(this);
            }

            string      imageUID = dicom.GetSingleValue <string>(DicomTag.SOPInstanceUID);
            ImageRecord image    = series.ImageCollection.FirstOrDefault(i => i.SOPInstanceUID == imageUID);

            if (image == null)
            {
                image = new ImageRecord();
                image.SOPInstanceUID = dicom.GetSingleValue <string>(DicomTag.SOPInstanceUID);
                image.ImageNumber    = dicom.GetSingleValueOrDefault <string>(DicomTag.InstanceNumber, null);
                // Add new image.
                series.AddImage(image);
                AddNewImageEvent(this);
            }
            else
            {
            }
            return(image);
        }
        public void CheckRemovals()
        {
            var ds = new DicomDataset(new DicomShortString(DicomTag.PerformedProcedureStepID, "123"));

            var cp = new ConfidentialityProfile();

            var anonymizer = new AnonymizeEngine(Mode.blank);

            anonymizer.RegisterHandler(cp);
            var nds_blank = anonymizer.Anonymize(ds);

            Assert.IsFalse(nds_blank.Contains(DicomTag.PerformedProcedureStepID));
            Assert.AreEqual("123", ds.GetSingleValue <string>(DicomTag.PerformedProcedureStepID));

            anonymizer = new AnonymizeEngine(Mode.clone);
            anonymizer.RegisterHandler(cp);
            var nds_clone = anonymizer.Anonymize(ds);

            Assert.IsFalse(nds_clone.Contains(DicomTag.PerformedProcedureStepID));
            Assert.AreEqual("123", ds.GetSingleValue <string>(DicomTag.PerformedProcedureStepID));

            anonymizer = new AnonymizeEngine(Mode.inplace);
            anonymizer.RegisterHandler(cp);
            anonymizer.Anonymize(ds);
            Assert.IsFalse(ds.Contains(DicomTag.PerformedProcedureStepID));
        }
        static internal unsafe void Start(string[] args)
        {
            const string       sourceFilePath  = "/media/nikolaev_ov/CEFE3C54FE3C36D5/DICOM/gsps.pre";
            const string       destFilePath    = "/media/nikolaev_ov/CEFE3C54FE3C36D5/DICOM/gsps2.pre";
            DicomDataset       sourceDataset   = DicomFile.Open(sourceFilePath).Dataset;
            HashSet <DicomTag> notRemovingTags = new HashSet <DicomTag>
            {
                DicomTag.StudyInstanceUID,
                DicomTag.SeriesInstanceUID,
                DicomTag.SOPInstanceUID,
                DicomTag.SOPClassUID,
                DicomTag.Modality,
                DicomTag.SpecificCharacterSet,


                DicomTag.ReferencedSeriesSequence,
                DicomTag.GraphicAnnotationSequence,
                DicomTag.GraphicLayerSequence,
                DicomTag.DisplayedAreaSelectionSequence,
                DicomTag.SoftcopyVOILUTSequence,
            };
            string          StudyInstanceUID  = sourceDataset.GetSingleValue <string>(DicomTag.StudyInstanceUID);  //1.3.6.1.4.1.14519.5.2.1.6279.6001.298806137288633453246975630178
            string          SeriesInstanceUID = sourceDataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID); //1.3.6.1.4.1.14519.5.2.1.6279.6001.298806137288633453246.1.2
            string          SOPInstanceUID    = sourceDataset.GetSingleValue <string>(DicomTag.SOPInstanceUID);    //1.3.6.1.4.1.14519.5.2.1.6279.6001.179049373636438705059.1.2
            string          SOPClassUID       = sourceDataset.GetSingleValue <string>(DicomTag.SOPClassUID);       //1.2.840.10008.5.1.4.1.1.11.1
            string          Modality          = sourceDataset.GetSingleValue <string>(DicomTag.Modality);          //1.2.840.10008.5.1.4.1.1.11.1
            List <DicomTag> removingTags      = new List <DicomTag>();

            foreach (DicomItem item in sourceDataset)
            {
                if (!notRemovingTags.Contains(item.Tag))
                {
                    removingTags.Add(item.Tag);
                }
            }
            sourceDataset.Remove(removingTags.ToArray());

            sourceDataset.AddOrUpdate(DicomTag.StudyInstanceUID, new DicomUID
                                      (
                                          "1.3.6.1.4.1.14519.5.2.1.6279.6001.298806137288633453246975630178",
                                          "Study Instance UID",
                                          DicomUidType.SOPInstance
                                      ));
            sourceDataset.AddOrUpdate(DicomTag.SeriesInstanceUID, new DicomUID
                                      (
                                          "1.3.6.1.4.1.14519.5.2.1.6279.6001.298806137288633453246.1.2",
                                          "Series Instance UID",
                                          DicomUidType.SOPInstance
                                      ));
            sourceDataset.AddOrUpdate(DicomTag.SOPInstanceUID, new DicomUID
                                      (
                                          "1.3.6.1.4.1.14519.5.2.1.6279.6001.179049373636438705059.1.2",
                                          "SOP Instance UID",
                                          DicomUidType.SOPInstance
                                      ));
            sourceDataset.AddOrUpdate(DicomTag.SOPClassUID, "1.2.840.10008.5.1.4.1.1.11.1");
            sourceDataset.AddOrUpdate(DicomTag.Modality, "PR");
            sourceDataset.AddOrUpdate(DicomTag.SpecificCharacterSet, "ISO_IR 192");
            new DicomFile(sourceDataset).Save(destFilePath);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Read properties from the given DicomDataset, throwing if Type 1 parameters are not present.
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static DicomCommonImage Read(DicomDataset ds)
        {
            var sopCommon = DicomSOPCommon.Read(ds);
            //throw
            // Changed for new OSS fo-dicom-desktop
            var position     = ds.GetValues <double>(DicomTag.ImagePositionPatient);
            var pixelSpacing = ds.GetValues <double>(DicomTag.PixelSpacing);
            var rows         = ds.GetSingleValue <int>(DicomTag.Rows);
            var columns      = ds.GetSingleValue <int>(DicomTag.Columns);
            var imageType    = ds.GetValues <string>(DicomTag.ImageType);
            //var position = ds.Get<double[]>(DicomTag.ImagePositionPatient);
            //var pixelSpacing = ds.Get<double[]>(DicomTag.PixelSpacing);
            //var rows = ds.Get<int>(DicomTag.Rows);
            //var columns = ds.Get<int>(DicomTag.Columns);
            //var imageType = ds.Get<string[]>(DicomTag.ImageType);
            var pPosition = new Point3D(position);
            // Note that DICOM encodes this as (Y,X)!!!
            var pSpacing = new Point2D(pixelSpacing[1], pixelSpacing[0]);

            // no throw
            // Changed for new OSS fo-dicom-desktop
            var location     = ds.GetSingleValueOrDefault <double>(DicomTag.SliceLocation, 0d);
            var windowCenter = ds.GetSingleValueOrDefault <double>(DicomTag.WindowCenter, 0d);
            var windowWidth  = ds.GetSingleValueOrDefault <double>(DicomTag.WindowWidth, 0d);

            //var location = ds.Get(DicomTag.SliceLocation, 0d);
            //var windowCenter = ds.Get(DicomTag.WindowCenter, 0d);
            //var windowWidth = ds.Get(DicomTag.WindowWidth, 0d);

            return(new DicomCommonImage(sopCommon, pPosition, pSpacing, location, imageType, rows, columns, windowCenter, windowWidth));
        }
        public void CheckWhitelistTags()
        {
            var cp = new ConfidentialityProfile(SecurityProfileOptions.BasicProfile | SecurityProfileOptions.RetainUIDs);

            var ds = new DicomDataset(new DicomUniqueIdentifier(DicomTag.RequestedSOPInstanceUID, "123"));

            var anonymizer = new AnonymizeEngine(Mode.blank);

            anonymizer.RegisterHandler(cp);
            var nds_blank = anonymizer.Anonymize(ds);

            Assert.AreEqual("123", ds.GetSingleValue <string>(DicomTag.RequestedSOPInstanceUID));
            Assert.AreEqual("123", nds_blank.GetSingleValue <string>(DicomTag.RequestedSOPInstanceUID));

            anonymizer = new AnonymizeEngine(Mode.clone);
            anonymizer.RegisterHandler(cp);
            var nds_clone = anonymizer.Anonymize(ds);

            Assert.AreEqual("123", ds.GetSingleValue <string>(DicomTag.RequestedSOPInstanceUID));
            Assert.AreEqual("123", nds_clone.GetSingleValue <string>(DicomTag.RequestedSOPInstanceUID));

            anonymizer = new AnonymizeEngine(Mode.inplace);
            anonymizer.RegisterHandler(cp);
            anonymizer.Anonymize(ds);
            Assert.AreEqual("123", ds.GetSingleValue <string>(DicomTag.RequestedSOPInstanceUID));
        }
        public async Task GivenSearchRequest_ReferringPhysicianNameFuzzyMatch_MatchResult()
        {
            string       randomNamePart = RandomString(7);
            DicomDataset matchInstance  = await PostDicomFileAsync(new DicomDataset()
            {
                { DicomTag.ReferringPhysicianName, $"dr^{randomNamePart}^Stone Hall^^" },
            });

            var studyId = matchInstance.GetSingleValue <string>(DicomTag.StudyInstanceUID);

            // Retrying the query 3 times, to give sql FT index time to catch up
            int          retryCount       = 0;
            DicomDataset testDataResponse = null;

            DicomDataset[] responseDatasets = null;

            while (retryCount < 3 || testDataResponse == null)
            {
                using DicomWebAsyncEnumerableResponse <DicomDataset> response = await _client.QueryStudyAsync(
                          $"ReferringPhysicianName={randomNamePart}&FuzzyMatching=true");

                if (response.ContentHeaders.ContentType != null)
                {
                    Assert.Equal(KnownContentTypes.ApplicationDicomJson, response.ContentHeaders.ContentType.MediaType);
                }

                responseDatasets = await response.ToArrayAsync();

                testDataResponse = responseDatasets?.FirstOrDefault(ds => ds.GetSingleValue <string>(DicomTag.StudyInstanceUID) == studyId);
                retryCount++;
            }

            Assert.NotNull(testDataResponse);
            Assert.Equal(matchInstance.GetSingleValue <string>(DicomTag.ReferringPhysicianName), testDataResponse.GetSingleValue <string>(DicomTag.ReferringPhysicianName));
        }
Exemplo n.º 8
0
        /// <inheritdoc/>
        public async Task WriteRetryableExceptionAsync(ChangeFeedEntry changeFeedEntry, int retryNum, TimeSpan nextDelayTimeSpan, Exception exceptionToStore, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(changeFeedEntry, nameof(changeFeedEntry));

            DicomDataset dataset            = changeFeedEntry.Metadata;
            string       studyInstanceUid   = dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID);
            string       seriesInstanceUid  = dataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID);
            string       sopInstanceUid     = dataset.GetSingleValue <string>(DicomTag.SOPInstanceUID);
            long         changeFeedSequence = changeFeedEntry.Sequence;

            var tableClient = _tableServiceClient.GetTableClient(Constants.TransientRetryTableName);
            var entity      = new RetryableEntity(studyInstanceUid, seriesInstanceUid, sopInstanceUid, changeFeedSequence, retryNum, exceptionToStore);

            try
            {
                await tableClient.UpsertEntityAsync(entity, cancellationToken : cancellationToken);

                _logger.LogInformation("Retryable error when processing changefeed entry: {ChangeFeedSequence} for DICOM instance with StudyUID: {StudyInstanceUid}, SeriesUID: {SeriesInstanceUid}, InstanceUID: {SopInstanceUid}. Tried {RetryNum} time(s). Waiting {Milliseconds} milliseconds . Stored into table: {Table} in table storage.", changeFeedSequence, studyInstanceUid, seriesInstanceUid, sopInstanceUid, retryNum, nextDelayTimeSpan.TotalMilliseconds, Constants.TransientRetryTableName);
            }
            catch
            {
                _logger.LogInformation("Retryable error when processing changefeed entry: {ChangeFeedSequence} for DICOM instance with StudyUID: {StudyInstanceUid}, SeriesUID: {SeriesInstanceUid}, InstanceUID: {SopInstanceUid}. Tried {RetryNum} time(s). Failed to store to table storage.", changeFeedSequence, studyInstanceUid, seriesInstanceUid, sopInstanceUid, retryNum);
                throw;
            }
        }
Exemplo n.º 9
0
        public static DicomStudy CreateFromDicom(DicomDataset dicom)
        {
            string studyUID        = dicom.GetSingleValue <string>(DicomTag.StudyInstanceUID);
            string studyId         = dicom.GetSingleValueOrDefault <string>(DicomTag.StudyID, null);
            string studyDate       = dicom.GetSingleValueOrDefault <string>(DicomTag.StudyDate, null);
            string studyTime       = dicom.GetSingleValueOrDefault <string>(DicomTag.StudyTime, null);
            string accessionNumber = dicom.GetSingleValueOrDefault <string>(DicomTag.AccessionNumber, null);
            string description     = dicom.GetSingleValueOrDefault <string>(DicomTag.StudyDescription, null);

            PatientRecord patient = DicomRecord.ToPatient(dicom);
            var           result  = new DicomStudy(studyUID, studyId, studyDate, studyTime, accessionNumber, patient, description);

            SeriesRecord series = DicomRecord.ToSeries(dicom);
            ImageRecord  image  = new ImageRecord();

            image.SOPInstanceUID = dicom.GetSingleValue <string>(DicomTag.SOPInstanceUID);
            image.ImageNumber    = dicom.GetSingleValueOrDefault <string>(DicomTag.InstanceNumber, null);
            series.AddImage(image);
            result._seriesItems.Add(series);

            // Notice the event.
            AddNewStudyEvent(result);

            return(result);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DicomFileMetaInformation"/> class.
        /// </summary>
        /// <param name="dataset">
        /// The data set for which file meta information is required.
        /// </param>
        public DicomFileMetaInformation(DicomDataset dataset)
        {
            ValidateItems = dataset.ValidateItems;
            Version       = new byte[] { 0x00, 0x01 };

            MediaStorageSOPClassUID    = dataset.GetSingleValue <DicomUID>(DicomTag.SOPClassUID);
            MediaStorageSOPInstanceUID = dataset.GetSingleValue <DicomUID>(DicomTag.SOPInstanceUID);
            TransferSyntax             = dataset.InternalTransferSyntax;

            ImplementationClassUID    = DicomImplementation.ClassUID;
            ImplementationVersionName = DicomImplementation.Version;

            dataset.TryGetString(DicomTag.SourceApplicationEntityTitle, out var aet);
            if (aet != null)
            {
                SourceApplicationEntityTitle = aet;
            }

            if (dataset.TryGetSingleValue(DicomTag.SendingApplicationEntityTitle, out string sendingAETVal))
            {
                SendingApplicationEntityTitle = sendingAETVal;
            }
            if (dataset.TryGetSingleValue(DicomTag.ReceivingApplicationEntityTitle, out string receivingAETVal))
            {
                ReceivingApplicationEntityTitle = receivingAETVal;
            }
            if (dataset.TryGetSingleValue(DicomTag.PrivateInformationCreatorUID, out DicomUID privInfoCreator))
            {
                PrivateInformationCreatorUID = privInfoCreator;
            }
            if (dataset.TryGetValues(DicomTag.PrivateInformation, out byte[] privInfo))
Exemplo n.º 11
0
        /// <summary>
        /// This method gets the values for the image position, orientation, spacing, and size
        /// from ImageOrientationPatient, ImagePositionPatient, PixelSpacing, Rows, and Columns.
        /// The normal direction cosines are derived from row and column direction cosines.
        ///
        /// </summary>
        /// <param name="dicomDataset">The dataset of the frame, that is viewed by the user</param>
        /// <param name="rowDir">The row direction cosine</param>
        /// <param name="colDir">The column direction cosine</param>
        /// <param name="normalDir">The normal direction cosine</param>
        /// <param name="pos">The starting pixel position (top lefthand corner)</param>
        /// <param name="rows">The number of rows in the frame</param>
        /// <param name="cols">The number of columns in the frame</param>
        /// <param name="row_spacing">The Row spacing of the frame, derived from the first entry of the PixelSpacing tag</param>
        /// <param name="col_spacing">The Column spacing of the frame, derived from the second entry of the PixelSpacing tag</param>
        /// <param name="row_length">The row length of the frame, derived from multiplying the columns by the row spacing</param>
        /// <param name="col_length">The column length of the frame, derived from multiplying the rows by the column spacing</param>
        /// <returns></returns>
        private static bool GetPositionOrientationSpacingAndSize(DicomDataset dicomDataset,
                                                                 out Vector3D rowDir, out Vector3D colDir,
                                                                 out Vector3D normalDir, out Point3D pos,
                                                                 out int rows, out int cols,
                                                                 out double row_spacing, out double col_spacing,
                                                                 out double row_length, out double col_length)
        {
            var imageorientation = dicomDataset.GetValues <double>(DicomTag.ImageOrientationPatient);

            rowDir = new Vector3D(imageorientation, 0);
            colDir = new Vector3D(imageorientation, 3);
            // compute nrm to row and col (i.e. cross product of row and col unit vectors)
            normalDir = rowDir.CrossProduct(colDir);

            pos = new Point3D(dicomDataset.GetValues <double>(DicomTag.ImagePositionPatient));

            row_spacing = dicomDataset.GetValue <double>(DicomTag.PixelSpacing, 0);
            col_spacing = dicomDataset.GetValue <double>(DicomTag.PixelSpacing, 1);

            rows = dicomDataset.GetSingleValue <int>(DicomTag.Rows);
            cols = dicomDataset.GetSingleValue <int>(DicomTag.Columns);

            row_length = cols * row_spacing;
            col_length = rows * col_spacing;

            return(true);
        }
Exemplo n.º 12
0
        private void Import()
        {
            DicomDataset dt1 = DicomFile.Open(refRTDoseFile).Dataset;
            DicomDataset dt2 = DicomFile.Open(tarRTDoseFile).Dataset;

            float[] PixelSpacing   = dt1.GetValues <float>(DicomTag.PixelSpacing);
            float   SliceThickness = dt1.GetSingleValue <float>(DicomTag.SliceThickness);

            voxelsX       = dt1.GetSingleValue <int>(DicomTag.Columns);
            voxelsY       = dt1.GetSingleValue <int>(DicomTag.Rows);
            voxelsZ       = dt1.GetSingleValue <int>(DicomTag.NumberOfFrames);
            totalVoxelNum = voxelsX * voxelsY * voxelsZ;
            refDose       = new float[totalVoxelNum];
            tarDose       = new float[totalVoxelNum];
            gammaIndex    = new float[totalVoxelNum];

            pixelSpacing.X = PixelSpacing[0];
            pixelSpacing.Y = PixelSpacing[1];
            pixelSpacing.Z = SliceThickness;
            UInt16[] dt1dosedata     = dt1.GetValues <UInt16>(DicomTag.PixelData);
            float    DoeGridScaling1 = dt1.GetSingleValue <float>(DicomTag.DoseGridScaling);

            UInt16[] dt2dosedata     = dt2.GetValues <UInt16>(DicomTag.PixelData);
            float    DoeGridScaling2 = dt2.GetSingleValue <float>(DicomTag.DoseGridScaling);

            float maxvalue1 = dt1dosedata.Max() * DoeGridScaling1;

            // dose Normalization
            if (normalization == true)
            {
                for (int i = 0; i < totalVoxelNum; i++)
                {
                    refDose[i] = (dt1dosedata[i] * DoeGridScaling1) / maxvalue1;
                    tarDose[i] = (dt2dosedata[i] * DoeGridScaling2) / maxvalue1;
                }
            }
            else
            {
                for (int i = 0; i < totalVoxelNum; i++)
                {
                    refDose[i] = (dt1dosedata[i] * DoeGridScaling1);
                    tarDose[i] = (dt2dosedata[i] * DoeGridScaling2);
                }
            }

            //TextWriter tw = new StreamWriter("d://text.txt");
            //for (int i = 0; i < voxelsY; i++)
            //{
            //    for (int j = 0; j < voxelsX; j++)
            //    {
            //        int x = Sub2Index(j, i, 100);
            //        tw.WriteLine(refDose[x] + ",Sub:(" + j + "," + i + ",100) Index:" + x);
            //        //tw.Write(refDose[x]+" ");
            //        float dd = 1;
            //    }
            //    //tw.WriteLine();
            //}
            //tw.Flush();
        }
Exemplo n.º 13
0
        /// <summary>
        /// Create new instance of <seealso cref="BitDepth"/> from input <paramref name="dataset"/>
        /// </summary>
        /// <param name="dataset">Input dataset to extract bit depth information from</param>
        /// <returns>New <seealso cref="BitDepth"/> instance</returns>
        public static BitDepth FromDataset(DicomDataset dataset)
        {
            var allocated = dataset.GetSingleValue <ushort>(DicomTag.BitsAllocated);
            var stored    = dataset.GetSingleValue <ushort>(DicomTag.BitsStored);
            var signed    = dataset.GetSingleValue <PixelRepresentation>(DicomTag.PixelRepresentation) == PixelRepresentation.Signed;

            return(new BitDepth(allocated, stored, GetHighBit(stored, signed), signed));
        }
        public FileInfo GetPath(DirectoryInfo root, DicomDataset ds)
        {
            var filename = ds.GetSingleValue <DicomUID>(DicomTag.SOPInstanceUID).UID + ".dcm";
            var date     = ds.GetValues <DateTime>(DicomTag.StudyDate);

            switch (Layout)
            {
            case FileSystemLayout.Flat:
                return(new FileInfo(Path.Combine(root.FullName, filename)));

            case FileSystemLayout.StudyYearMonthDay:

                if (date.Length > 0)
                {
                    return(new FileInfo(Path.Combine(
                                            root.FullName,
                                            date[0].Year.ToString(),
                                            date[0].Month.ToString(),
                                            date[0].Day.ToString(),
                                            filename)));
                }
                else
                {
                    break;
                }

            case FileSystemLayout.StudyYearMonthDayAccession:

                var acc = ds.GetSingleValue <string>(DicomTag.AccessionNumber);

                if (date.Length > 0 && !string.IsNullOrWhiteSpace(acc))
                {
                    return(new FileInfo(Path.Combine(
                                            root.FullName,
                                            date[0].Year.ToString(),
                                            date[0].Month.ToString(),
                                            date[0].Day.ToString(),
                                            acc,
                                            filename)));
                }
                else
                {
                    break;
                }

            case FileSystemLayout.StudyUID:

                return(new FileInfo(Path.Combine(
                                        root.FullName,
                                        ds.GetSingleValue <DicomUID>(DicomTag.StudyInstanceUID).UID,
                                        filename)));

            default: throw new ArgumentOutOfRangeException();
            }

            return(new FileInfo(Path.Combine(root.FullName, filename)));
        }
Exemplo n.º 15
0
        private void ShowStudyLevelInfo(DicomDataset dataset)
        {
            _log("\tStudy Level Information:");
            var studyInstanceUid = dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID);

            _log($"\t-> Study Instance UID: '{studyInstanceUid}'");
            _log($"\t-> Study ID: '{dataset.GetSingleValue<string>(DicomTag.StudyID)}'");
            _log($"\t-> Study Date: '{dataset.GetSingleValue<string>(DicomTag.StudyDate)}'");
        }
Exemplo n.º 16
0
 public Beam(DicomDataset beamDcm, DicomDataset referenceBeamDcm) //incompleto
 {
     BeamNumber     = beamDcm.GetSingleValue <int>(DicomTag.BeamNumber);
     BeamName       = beamDcm.GetSingleValue <string>(DicomTag.BeamName);
     NumberOfWedges = beamDcm.GetSingleValue <int>(DicomTag.NumberOfWedges);
     //PatientPosition = beamDcm.GetSingleValue<string>(DicomTag.PatientPosition);
     BeamDose     = referenceBeamDcm.GetSingleValue <double>(DicomTag.BeamDose);
     BeamMeterset = referenceBeamDcm.GetSingleValue <double>(DicomTag.BeamMeterset);
 }
Exemplo n.º 17
0
        private void ShowSeriesLevelInfo(DicomDataset dataset)
        {
            _log("\t\tSeries Level Information:");
            var seriesInstanceUid = dataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID);

            _log($"\t\t-> Series Instance UID: '{seriesInstanceUid}'");
            var modality = dataset.GetSingleValue <string>(DicomTag.Modality);

            _log($"\t\t-> Series Modality: '{modality}'");
        }
Exemplo n.º 18
0
 public FrameGeometry(DicomDataset image)
     : this(image.GetString(DicomTag.FrameOfReferenceUID),
            image.GetValues <double>(DicomTag.ImagePositionPatient),
            image.GetValues <double>(DicomTag.ImageOrientationPatient),
            image.GetValues <double>(DicomTag.PixelSpacing),
            image.GetSingleValue <int>(DicomTag.Columns),
            image.GetSingleValue <int>(DicomTag.Rows))
 {
     // TODO: this constructor only works for single-frame images. Also handle multiframe like EnhancedCT or EnhancedMR
 }
Exemplo n.º 19
0
        public Task WriteRetryableExceptionAsync(ChangeFeedEntry changeFeedEntry, int retryNum, Exception exceptionToStore, CancellationToken cancellationToken = default)
        {
            DicomDataset dataset            = changeFeedEntry.Metadata;
            string       studyUid           = dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID);
            string       seriesUid          = dataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID);
            string       instanceUid        = dataset.GetSingleValue <string>(DicomTag.SOPInstanceUID);
            long         changeFeedSequence = changeFeedEntry.Sequence;

            _logger.LogInformation("Retryable error when processsing changefeed entry: {ChangeFeedSequence} for DICOM instance with StudyUID: {StudyUID}, SeriesUID: {SeriesUID}, InstanceUID: {InstanceUID}. Tried {retryNum} time(s).", changeFeedSequence, studyUid, seriesUid, instanceUid, retryNum);
            return(Task.CompletedTask);
        }
Exemplo n.º 20
0
        public async Task GivenDuplicatedIdentifiers_WhenValidated_ThenDatasetValidationExceptionShouldBeThrown(string firstDicomTagInString, string secondDicomTagInString)
        {
            DicomTag firstDicomTag  = DicomTag.Parse(firstDicomTagInString);
            DicomTag secondDicomTag = DicomTag.Parse(secondDicomTagInString);

            string value = _dicomDataset.GetSingleValue <string>(firstDicomTag);

            _dicomDataset.AddOrUpdate(secondDicomTag, value);

            await ExecuteAndValidateException <DatasetValidationException>(ValidationFailedFailureCode);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Read a DicomSOPInstance from the given DicomDataset, throwing if required
        /// type 1 properties are not present.
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static DicomSOPCommon Read(DicomDataset ds)
        {
            // throw
            // Changed for new OSS fo-dicom-desktop
            var sopClassUid    = ds.GetSingleValue <DicomUID>(DicomTag.SOPClassUID).UID;
            var sopInstanceUid = ds.GetSingleValue <DicomUID>(DicomTag.SOPInstanceUID).UID;

            //var sopClassUid = ds.Get<DicomUID>(DicomTag.SOPClassUID).UID;
            //var sopInstanceUid = ds.Get<DicomUID>(DicomTag.SOPInstanceUID).UID;

            return(new DicomSOPCommon(sopClassUid, sopInstanceUid));
        }
Exemplo n.º 22
0
        /// <inheritdoc/>
        public async Task WriteExceptionAsync(ChangeFeedEntry changeFeedEntry, Exception exceptionToStore, ErrorType errorType, CancellationToken cancellationToken)
        {
            CloudTable  table;
            TableEntity entity;
            string      tableName;

            EnsureArg.IsNotNull(changeFeedEntry, nameof(changeFeedEntry));

            switch (errorType)
            {
            case ErrorType.FhirError:
                tableName = Constants.FhirExceptionTableName;
                break;

            case ErrorType.DicomError:
                tableName = Constants.DicomExceptionTableName;
                break;

            case ErrorType.DicomValidationError:
                tableName = Constants.DicomValidationTableName;
                break;

            case ErrorType.TransientFailure:
                tableName = Constants.TransientFailureTableName;
                break;

            default:
                return;
            }

            DicomDataset dataset            = changeFeedEntry.Metadata;
            string       studyUid           = dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID);
            string       seriesUid          = dataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID);
            string       instanceUid        = dataset.GetSingleValue <string>(DicomTag.SOPInstanceUID);
            long         changeFeedSequence = changeFeedEntry.Sequence;

            table  = _client.GetTableReference(tableName);
            entity = new IntransientEntity(studyUid, seriesUid, instanceUid, changeFeedSequence, exceptionToStore);

            var operation = TableOperation.InsertOrMerge(entity);

            try
            {
                await table.ExecuteAsync(operation, cancellationToken);

                _logger.LogInformation("Error when processsing changefeed entry: {ChangeFeedSequence} for DICOM instance with StudyUID: {StudyUID}, SeriesUID: {SeriesUID}, InstanceUID: {InstanceUID}. Stored into table: {Table} in table storage.", changeFeedSequence, studyUid, seriesUid, instanceUid, tableName);
            }
            catch
            {
                _logger.LogInformation("Error when processsing changefeed entry: {ChangeFeedSequence} for DICOM instance with StudyUID: {StudyUID}, SeriesUID: {SeriesUID}, InstanceUID: {InstanceUID}. Failed to store to table storage.", changeFeedSequence, studyUid, seriesUid, instanceUid);
                throw;
            }
        }
Exemplo n.º 23
0
        private (string SopInstanceUid, string RetrieveUri, string SopClassUid) ConvertToReferencedSopSequenceEntry(DicomDataset dicomDataset, string partitionName)
        {
            string studyInstanceUid  = dicomDataset.GetSingleValue <string>(DicomTag.StudyInstanceUID);
            string seriesInstanceUid = dicomDataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID);
            string sopInstanceUid    = dicomDataset.GetSingleValue <string>(DicomTag.SOPInstanceUID);

            string relativeUri = $"{DicomApiVersions.Latest}/partitions/{partitionName}/studies/{studyInstanceUid}/series/{seriesInstanceUid}/instances/{sopInstanceUid}";

            return(dicomDataset.GetSingleValue <string>(DicomTag.SOPInstanceUID),
                   new Uri(_client.HttpClient.BaseAddress, relativeUri).ToString(),
                   dicomDataset.GetSingleValue <string>(DicomTag.SOPClassUID));
        }
Exemplo n.º 24
0
        public async Task ModifyAsync(DicomDataset dicom)
        {
            // Generate file name.
            string studyUID  = dicom.GetSingleValue <string>(DicomTag.StudyInstanceUID);
            string seriesUID = dicom.GetSingleValue <string>(DicomTag.SeriesInstanceUID);
            string imageUID  = dicom.GetSingleValue <string>(DicomTag.SOPInstanceUID);
            string filename  = GenerateFilename(studyUID, seriesUID, imageUID);

            // Create directory.
            FileInfo info = new FileInfo(filename);

            Directory.CreateDirectory(info.Directory.FullName);

            // Save to buffer file.
        }
Exemplo n.º 25
0
        public void DicomValidation_AddInvalidData()
        {
            var ds         = new DicomDataset();
            var invalidUid = "1.2.315.6666.008965..19187632.1";

            // trying to add this invalidUid should throw exception
            Assert.Throws <DicomValidationException>(() => ds.Add(DicomTag.StudyInstanceUID, invalidUid));

            ds.AutoValidate = false;
            // if AutoValidate is turned off, the invalidUid should be able to be added
            ds.Add(DicomTag.StudyInstanceUID, invalidUid);
            Assert.Equal(invalidUid, ds.GetSingleValue <string>(DicomTag.StudyInstanceUID));

            var tmpFile = Path.GetTempFileName();

            ds.Add(DicomTag.SOPClassUID, DicomUID.SecondaryCaptureImageStorage);
            ds.Add(DicomTag.SOPInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID().UID);
            // save this invalid dicomdataset
            (new DicomFile(ds)).Save(tmpFile);

            // reading of this invalid dicomdataset should be possible
            var dsFile = DicomFile.Open(tmpFile);

            Assert.Equal(invalidUid, dsFile.Dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID));

            // but the validation should still work
            Assert.Throws <DicomValidationException>(() => dsFile.Dataset.Validate());
            IOHelper.DeleteIfExists(tmpFile);
        }
Exemplo n.º 26
0
        internal void SaveImage(DicomDataset dataset)
        {
            //var studyUid = dataset.GetSingleValue<string>(DicomTag.StudyInstanceUID);
            var instUid = dataset.GetSingleValue <string>(DicomTag.SOPInstanceUID);

            var path = Path.GetFullPath(StoragePath);

            //path = Path.Combine(path, studyUid);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            path = Path.Combine(path, instUid) + ".dcm";

            new DicomFile(dataset).Save(path);
            var FrameExtractionSequence = dataset.GetSequence(DicomTag.FrameExtractionSequence);
            var items = FrameExtractionSequence.GetEnumerator();

            while (items.MoveNext())
            {
                var oldSOPInstancUID = items.Current.GetSingleValue <String>(DicomTag.SOPInstanceUID);
                var Framelist        = items.Current.GetValues <uint>(DicomTag.SimpleFrameList);
                for (int i = 0; i < Framelist.Length; i++)
                {
                    DataManager.SetLocalFile(oldSOPInstancUID, (int)Framelist[i], path, i);
                }
            }
        }
Exemplo n.º 27
0
        public void Constructor_FromDataset_SequenceItemsNotLinked()
        {
            var ds = new DicomDataset {
                { DicomTag.PatientID, "1" }
            };
            var sps = new DicomDataset {
                { DicomTag.ScheduledStationName, "1" }
            };
            var spcs = new DicomDataset {
                { DicomTag.ContextIdentifier, "1" }
            };

            sps.Add(new DicomSequence(DicomTag.ScheduledProtocolCodeSequence, spcs));
            ds.Add(new DicomSequence(DicomTag.ScheduledProcedureStepSequence, sps));

            var ds2 = new DicomDataset(ds);

            ds2.AddOrUpdate(DicomTag.PatientID, "2");
            ds2.GetSequence(DicomTag.ScheduledProcedureStepSequence).Items[0].AddOrUpdate(DicomTag.ScheduledStationName, "2");
            ds2.GetSequence(DicomTag.ScheduledProcedureStepSequence).Items[0].GetSequence(
                DicomTag.ScheduledProtocolCodeSequence).Items[0].AddOrUpdate(DicomTag.ContextIdentifier, "2");

            Assert.Equal("1", ds.GetSingleValue <string>(DicomTag.PatientID));
            Assert.Equal(
                "1",
                ds.GetSequence(DicomTag.ScheduledProcedureStepSequence).First().GetString(DicomTag.ScheduledStationName));
            Assert.Equal(
                "1",
                ds.GetSequence(DicomTag.ScheduledProcedureStepSequence).First().GetSequence(
                    DicomTag.ScheduledProtocolCodeSequence).First().GetString(DicomTag.ContextIdentifier));
        }
Exemplo n.º 28
0
        public void Get_IntWithoutArgumentTagNonExisting_ShouldThrow()
        {
            var dataset = new DicomDataset();
            var e       = Record.Exception(() => dataset.GetSingleValue <int>(DicomTag.MetersetRate));

            Assert.IsType <DicomDataException>(e);
        }
Exemplo n.º 29
0
        public async Task GivenOneDifferentStudyInstanceUID_WhenStoringWithProvidedStudyInstanceUID_TheServerShouldReturnAccepted()
        {
            var studyInstanceUID1 = TestUidGenerator.Generate();
            var studyInstanceUID2 = TestUidGenerator.Generate();

            try
            {
                DicomFile dicomFile1 = Samples.CreateRandomDicomFile(studyInstanceUid: studyInstanceUID1);
                DicomFile dicomFile2 = Samples.CreateRandomDicomFile(studyInstanceUid: studyInstanceUID2);

                using DicomWebResponse <DicomDataset> response = await _instancesManager.StoreAsync(new[] { dicomFile1, dicomFile2 }, studyInstanceUid : studyInstanceUID1);

                Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);

                DicomDataset dataset = await response.GetValueAsync();

                Assert.NotNull(dataset);
                Assert.True(dataset.Count() == 3);

                Assert.EndsWith($"studies/{studyInstanceUID1}", dataset.GetSingleValue <string>(DicomTag.RetrieveURL));

                await ValidateReferencedSopSequenceAsync(
                    response,
                    ConvertToReferencedSopSequenceEntry(dicomFile1.Dataset));

                ValidationHelpers.ValidateFailedSopSequence(
                    dataset,
                    ConvertToFailedSopSequenceEntry(dicomFile2.Dataset, MismatchStudyInstanceUidFailureCode));
            }
            finally
            {
                await _client.DeleteStudyAsync(studyInstanceUID1);
            }
        }
        public void NestedSequencesBlankRemovalAllExceptSequence()
        {
            var ds = new DicomDataset(
                new DicomUniqueIdentifier(DicomTag.SOPInstanceUID, "1.2.3"),
                new DicomSequence(DicomTag.RTROIObservationsSequence,
                                  new DicomDataset(new DicomUniqueIdentifier(DicomTag.SOPInstanceUID, "1.2.3"))));

            var anon = GetAnonEngine(Mode.blank);
            var th   = new TestHandler(new Dictionary <DicomTag, AnonFunc>()
            {
                { DicomTag.RTROIObservationsSequence, (x, s, y) => { return(y); } }
            }, null);

            anon.RegisterHandler(th);

            var nds = anon.Anonymize(ds);

            // Assert no changes happened to the original object
            Assert.AreEqual("1.2.3", ds.GetSingleValue <string>(DicomTag.SOPInstanceUID));
            Assert.IsTrue(ds.Contains(DicomTag.RTROIObservationsSequence));
            Assert.AreEqual(1, ds.GetSequence(DicomTag.RTROIObservationsSequence).Items.Count);
            Assert.AreEqual("1.2.3", ds.GetSequence(DicomTag.RTROIObservationsSequence).Items[0].GetSingleValue <string>(DicomTag.SOPInstanceUID));

            Assert.IsFalse(nds.Contains(DicomTag.SOPInstanceUID));
            Assert.IsTrue(nds.Contains(DicomTag.RTROIObservationsSequence));
            Assert.AreEqual(0, nds.GetSequence(DicomTag.RTROIObservationsSequence).Items.Count);
        }