Esempio n. 1
0
        public IList <SupportedSop> GetStroageSupportedSopClasses()
        {
            var list = new List <SupportedSop>();

            var storageAbstractSyntaxList = new List <SopClass>();

            using (var ctx = new PacsContext())
            {
                storageAbstractSyntaxList.AddRange(
                    ctx.SupportedSopClasses.ToList().Select(
                        sopClass => SopClass.GetSopClass(sopClass.SopClassUid)));
            }

            foreach (var abstractSyntax in storageAbstractSyntaxList)
            {
                var supportedSop = new SupportedSop {
                    SopClass = abstractSyntax
                };
                supportedSop.AddSyntax(TransferSyntax.ExplicitVrLittleEndian);
                supportedSop.AddSyntax(TransferSyntax.ImplicitVrLittleEndian);
                list.Add(supportedSop);
            }

            return(list);
        }
Esempio n. 2
0
        private Instance InsertImage(PacsContext context, Instance instance, Series dbSeries, Study dbStudy,
                                     Patient dbPatient)
        {
            var dbInstance = context.Instances.FirstOrDefault(i => i.SopInstanceUid.Equals(instance.SopInstanceUid));

            if (dbInstance == null)
            {
                dbInstance = instance;
                dbInstance.SeriesForeignKey = dbSeries.Id;
                dbInstance.LastUpdateTime   = DateTime.Now;
                dbInstance.InsertTime       = DateTime.Now;
                context.Instances.Add(dbInstance);

                dbSeries.NumberOfRelatedImage      += 1;
                dbStudy.NumberOfRelatedImage       += 1;
                dbPatient.NumberOfRelatedInstances += 1;
            }

            dbInstance.LastUpdateTime = DateTime.Now;
            dbSeries.LastUpdateTime   = DateTime.Now;
            dbStudy.LastUpdateTime    = DateTime.Now;
            dbPatient.LastUpdateTime  = DateTime.Now;

            return(dbInstance);
        }
Esempio n. 3
0
        private void LoadPartitions()
        {
            bool changed = false;

            lock (_partitionsLock)
            {
                var templist = new Dictionary <string, ServerPartition>();

                using (var ctx = new PacsContext())
                {
                    var partitions = (from p in ctx.ServerPartitions where (true)select p).ToList();
                    foreach (var serverPartition in partitions)
                    {
                        if (IsChanged(serverPartition))
                        {
                            changed = true;
                        }

                        templist.Add(serverPartition.AeTitle, serverPartition);
                    }
                }

                _partitions = templist;

                if (changed && _changedListener != null)
                {
                    EventsHelper.Fire(_changedListener, this, new ServerPartitionChangedEventArgs(this));
                }
            }
        }
Esempio n. 4
0
        private Study InsertStudy(PacsContext context, Study study, Patient patient, out Patient dbPatient)
        {
            var dbStudy = context.Studies.FirstOrDefault(s => s.StudyUid.Equals(study.StudyUid));

            if (dbStudy == null)
            {
                // check is patient exist by patient id, patient name and so on.
                var tempResult = (context.Patients.Where(p => p.PatientId.Equals(patient.PatientId))).ToList();

                // TODO Patient strategy
                dbPatient = tempResult.FirstOrDefault();
                if (dbPatient == null)
                {
                    patient.LastUpdateTime = DateTime.Now;
                    patient.InsertTime     = DateTime.Now;
                    context.Patients.Add(patient);
                    dbPatient = patient;
                }

                // Insert Study info
                dbStudy = study;
                dbStudy.PatientForeignKey = dbPatient.Id;
                dbStudy.InsertTime        = DateTime.Now;
                context.Studies.Add(dbStudy);

                dbPatient.NumberOfRelatedStudies += 1;
            }
            else
            {
                dbPatient = dbStudy.Patient;
            }

            return(dbStudy);
        }
Esempio n. 5
0
        public override IList<SupportedSop> GetSupportedSopClasses()
        {
            if (_list == null)
            {
                _list = new List<SupportedSop>();

                var storageAbstractSyntaxList = new List<SopClass>();
                using (var ctx = new PacsContext())
                {
                    storageAbstractSyntaxList.AddRange(
                        ctx.SupportedSopClasses.ToList().Select(
                        sopClass => SopClass.GetSopClass(sopClass.SopClassUid)));
                }

                foreach (var abstractSyntax in storageAbstractSyntaxList)
                {
                    var supportedSop = new SupportedSop {SopClass = abstractSyntax};
                    supportedSop.AddSyntax(TransferSyntax.ExplicitVrLittleEndian);
                    supportedSop.AddSyntax(TransferSyntax.ImplicitVrLittleEndian);
                    _list.Add(supportedSop);
                }
            }

            return _list;
        }
Esempio n. 6
0
        // Instance Level
        // StudyInstanceUid, SeriesInstanceUid, SopInstanceUid, InstanceNumber, SopClassUid

        public List <StorageInstance> GetSopListForPatient(DicomMessage message)
        {
            var instances = new List <StorageInstance>();

            using (var ctx = new PacsContext())
            {
                var patientId = message.DataSet[DicomTags.PatientId].GetString(0, string.Empty);

                var patientPK = ctx.Patients.Where(p => p.PatientId == patientId).Select(p => p.Id).FirstOrDefault();

                var studyList = ctx.Studies.Where(s => s.PatientForeignKey == patientPK).ToList();

                foreach (var study in studyList)
                {
                    var seriesPkList = (from s in ctx.Series where study.Id == s.StudyForeignKey select s.Id).ToList();

                    var sopList =
                        (from s in ctx.Instances where seriesPkList.Contains(s.SeriesForeignKey) select s.Id).ToList();

                    var fileList = (from f in ctx.Files where sopList.Contains(f.InstanceFk) select f).ToList();

                    foreach (var file in fileList)
                    {
                        instances.Add(new StorageInstance(file.FilePath));
                    }
                }
            }

            return(instances);
        }
Esempio n. 7
0
        public List <StorageInstance> GetSopListForStudy(DicomMessage message)
        {
            var instances = new List <StorageInstance>();

            using (var ctx = new PacsContext())
            {
                var studyUidList = (string[])message.DataSet[DicomTags.StudyInstanceUid].Values;

                var studyList = (from s in ctx.Studies where studyUidList.Contains(s.StudyUid) select s).ToList();

                foreach (var study in studyList)
                {
                    var seriesPkList = (from s in ctx.Series where study.Id == s.StudyForeignKey select s.Id).ToList();

                    var sopList =
                        (from s in ctx.Instances where seriesPkList.Contains(s.SeriesForeignKey) select s.Id).ToList();

                    var fileList = (from f in ctx.Files where sopList.Contains(f.InstanceFk) select f).ToList();

                    foreach (var file in fileList)
                    {
                        instances.Add(new StorageInstance(file.FilePath));
                    }
                }
            }

            return(instances);
        }
Esempio n. 8
0
        private File InsertFile(PacsContext context, Instance instance, Series dbSeries, Study dbStudy,
                                Patient dbPatient)
        {
            var partition = context.ServerPartitions.First(p => p.AeTitle == Context.DestAE);

            string fsDir = partition.FileSystem.DirPath;

            var filepath = Path.Combine(fsDir, dbPatient.PatientId, dbStudy.StudyUid, dbSeries.SeriesUid,
                                        instance.SopInstanceUid);

            var dbFile = context.Files.FirstOrDefault(f => f.InstanceFk.Equals(instance.Id));

            if (dbFile == null)
            {
                dbFile = new File
                {
                    CreateTime = DateTime.Now
                };
                context.Files.Add(dbFile);
            }

            dbFile.InstanceFk   = instance.Id;
            dbFile.FilePath     = filepath;
            dbFile.FileSystemFk = partition.FileSystem.Id;

            return(dbFile);
        }
Esempio n. 9
0
        public List <StorageInstance> GetSopListForSeries(DicomMessage message)
        {
            var instances = new List <StorageInstance>();

            using (var ctx = new PacsContext())
            {
                //var studyInstanctUid = message.DataSet[DicomTags.StudyInstanceUid].GetString(0, string.Empty);
                var seriesUidList = (string[])message.DataSet[DicomTags.SeriesInstanceUid].Values;

                //int studyPk = ctx.Studies.Where(s => s.StudyUid == studyInstanctUid).Select(s => s.Id).FirstOrDefault();

                var seriesPkList = (from s in ctx.Series where seriesUidList.Contains(s.SeriesUid) select s.Id).ToList();

                var sopList =
                    (from s in ctx.Instances where seriesPkList.Contains(s.SeriesForeignKey) select s.Id).ToList();

                var fileList = (from f in ctx.Files where sopList.Contains(f.InstanceFk) select f).ToList();

                foreach (var file in fileList)
                {
                    instances.Add(new StorageInstance(file.FilePath));
                }
            }

            return(instances);
        }
Esempio n. 10
0
        public IDevice LookupDevice(IServerPartition partition, string aet)
        {
            Device device = null;

            using (var ctx = new PacsContext())
            {
                var part = (from p in ctx.ServerPartitions select p).FirstOrDefault();
                if (part != null)
                {
                    device = part.Devices.FirstOrDefault(d => d.AeTitle.Equals(aet));
                }
            }

            return(device);
        }
Esempio n. 11
0
        private Series InsertSeries(PacsContext context, Series series, Study dbStudy, Patient dbPatient)
        {
            var dbSeries = context.Series.FirstOrDefault(s => s.SeriesUid.Equals(series.SeriesUid));

            if (dbSeries == null)
            {
                dbSeries = series;
                dbSeries.StudyForeignKey = dbStudy.Id;
                dbSeries.InsertTime      = DateTime.Now;
                context.Series.Add(dbSeries);

                dbStudy.NumberOfRelatedSeries   += 1;
                dbPatient.NumberOfRelatedSeries += 1;
            }

            return(dbSeries);
        }
Esempio n. 12
0
        public List <StorageInstance> GetSopListForInstance(DicomMessage message)
        {
            var instances = new List <StorageInstance>();

            using (var ctx = new PacsContext())
            {
                var studyInstanceUid    = message.DataSet[DicomTags.StudyInstanceUid].GetString(0, "");
                var seriesInstanceUid   = message.DataSet[DicomTags.SeriesInstanceUid].GetString(0, "");
                var sopInstanceUidArray = (string[])message.DataSet[DicomTags.SopInstanceUid].Values;

                var sopPkArray =
                    (from s in ctx.Instances where sopInstanceUidArray.Contains(s.SopInstanceUid) select s.Id).ToList();

                var fileList =
                    (from f in ctx.Files where sopPkArray.Contains(f.InstanceFk) select f).ToList();

                foreach (var file in fileList)
                {
                    instances.Add(new StorageInstance(file.FilePath));
                }
            }

            return(instances);
        }
Esempio n. 13
0
        public IDevice LookupDevice(IServerPartition partition, AssociationParameters association, out bool isNew)
        {
            isNew = false;

            Device device = null;

            using (var ctx = new PacsContext())
            {
                var part = (from p in ctx.ServerPartitions select p).FirstOrDefault();
                if (part != null)
                {
                    device = part.Devices.FirstOrDefault(d => d.AeTitle.Equals(association.CallingAE));
                }

                if (device == null)
                {
                    if (!partition.AcceptAnyDevice)
                    {
                        return(null);
                    }

                    if (partition.AutoInsertDevice)
                    {
                        device = new Device()
                        {
                            AeTitle           = association.CallingAE,
                            Enabled           = true,
                            Description       = string.Format("AE: {0}", association.CallingAE),
                            Hostname          = association.RemoteEndPoint.Address.ToString(),
                            Port              = 104,
                            AllowQuery        = true,
                            AllowRetrieve     = true,
                            AllowStorage      = true,
                            ServerPartitionPK = part.Id,
                            LastAccessTime    = DateTime.Now
                        };

                        ctx.Devices.Add(device);
                        ctx.SaveChanges();

                        isNew = true;
                    }
                }

                if (device != null)
                {
                    if (device.Dhcp && !association.RemoteEndPoint.Address.ToString().Equals(device.Hostname))
                    {
                        device.Hostname = association.RemoteEndPoint.Address.ToString();

                        device.LastAccessTime = DateTime.Now;
                        ctx.SaveChanges();
                    }
                    else if (!isNew)
                    {
                        device.LastAccessTime = DateTime.Now;
                        ctx.SaveChanges();
                    }
                }
            }

            return(device);
        }
Esempio n. 14
0
        private void OnReceiveStudyLevelQuery(DicomServer server, byte presentationId, DicomMessage message)
        {
            var tagList = new List<DicomTag>();

            using (var pacsContext = new PacsContext())
            {
                var adapter = (IObjectContextAdapter)pacsContext;
                var query = new ObjectQuery<Study>("Studies", adapter.ObjectContext);

                DicomAttributeCollection data = message.DataSet;
                foreach (DicomAttribute attrib in message.DataSet)
                {
                    tagList.Add(attrib.Tag);

                    if (!attrib.IsNull)
                    {
                        switch (attrib.Tag.TagValue)
                        {
                            case DicomTags.StudyInstanceUid:
                                {
                                    var cond = QueryHelper.SetStringArrayCondition("StudyInstanceUid",
                                                                                   (string[])data[DicomTags.StudyInstanceUid].Values);
                                    if (!string.IsNullOrEmpty(cond))
                                    {
                                        query = query.Where(cond);
                                    }    
                                }
                                
                                break;
                            case DicomTags.PatientsName:
                                {
                                    var cond = QueryHelper.SetStringCondition("PatientName",
                                                                              data[DicomTags.PatientsName].GetString(0,
                                                                                                                     string
                                                                                                                         .Empty));
                                    if (!string.IsNullOrEmpty(cond))
                                    {
                                        query = query.Where(cond);
                                    }
                                    
                                    break;
                                }
                            case DicomTags.PatientId:
                                {
                                    var cond = QueryHelper.SetStringCondition("PatientId",
                                                                              data[DicomTags.PatientId].GetString(0,
                                                                                                                  string
                                                                                                                      .Empty));
                                    break;
                                }
                            case DicomTags.PatientsBirthDate:
                                {
                                    var cond = QueryHelper.SetRangeCondition("PatientBirthDate",
                                                                             data[DicomTags.PatientsBirthDate].GetString
                                                                                 (0, string.Empty));
                                    query = query.Where(cond);
                                    break;
                                }

                            case DicomTags.PatientsSex:
                                {
                                    var cond = QueryHelper.SetStringCondition("PatientSex",
                                                                              data[DicomTags.PatientsSex].GetString(0,
                                                                                                                    string
                                                                                                                        .Empty));
                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.StudyDate:
                                {
                                    var cond = QueryHelper.SetRangeCondition("StudyDate",
                                                                              data[DicomTags.StudyDate].GetString(0,
                                                                                                                  string
                                                                                                                      .Empty));
                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.StudyTime:
                                {
                                    var cond = QueryHelper.SetRangeCondition("StudyTime",
                                                                              data[DicomTags.StudyTime].GetString(0,
                                                                                                                  string
                                                                                                                      .Empty));
                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.AccessionNumber:
                                {
                                    var cond = QueryHelper.SetStringCondition("AccessionNumber",
                                                                              data[DicomTags.AccessionNumber].GetString(
                                                                                  0, string.Empty));
                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.StudyId:
                                {
                                    var cond = QueryHelper.SetStringCondition("StudyId",
                                        data[DicomTags.StudyId].GetString(0, string.Empty));

                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.StudyDescription:
                                {
                                    var cond = QueryHelper.SetStringCondition("StudyDescription",
                                        data[DicomTags.StudyDescription].GetString(0, string.Empty));
                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.ReferringPhysiciansName:
                                {
                                    var cond = QueryHelper.SetStringCondition("RefPhysician",
                                                                              data[DicomTags.ReferringPhysiciansName]
                                                                                  .GetString(0, string.Empty));
                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.ModalitiesInStudy:
                                break;
                            default:
                                break;
                        }
                    }
                }
                int resultCount = 0;
                try
                {
                    foreach (Study study in query)
                    {
                        if (_cancelReceived)
                        {
                            throw new DicomException("DICOM C-Cancel Received");
                        }

                        resultCount++;
                        if (DicomSetting.Default.MaxQueryResponses != -1 &&
                            DicomSetting.Default.MaxQueryResponses < resultCount)
                        {
                            SendBufferedResponses(server, presentationId, message);
                            throw new DicomException("Maximum Configured Query Responses Exceeded: " + resultCount);
                        }

                        var response = new DicomMessage();
                        PopulateStudy(response, tagList, study);
                        _responseQueue.Enqueue(response);

                        if (_responseQueue.Count >= DicomSetting.Default.BufferedQueryResponses)
                        {
                            SendBufferedResponses(server, presentationId, message);
                        }
                    }

                    SendBufferedResponses(server, presentationId, message);
                }
                catch (Exception e)
                {
                    if (_cancelReceived)
                    {
                        var errorResponse = new DicomMessage();
                        server.SendCFindResponse(presentationId, message.MessageId, errorResponse,
                                                 DicomStatuses.Cancel);
                    }

                    return;
                }
            }

            var finalResponse = new DicomMessage();
            server.SendCFindResponse(presentationId, message.MessageId, finalResponse, DicomStatuses.Success);
        }
Esempio n. 15
0
        private void OnReceiveSeriesLevelQuery(DicomServer server, byte presentationId, DicomMessage message)
        {
            var tagList = new List<DicomTag>();

            using (var pacsContext = new PacsContext())
            {
                var adapter = (IObjectContextAdapter)pacsContext;
                var query = new ObjectQuery<Series>("Series", adapter.ObjectContext);

                DicomAttributeCollection data = message.DataSet;
                foreach (DicomAttribute attrib in data)
                {
                    tagList.Add(attrib.Tag);
                    if (!attrib.IsNull)
                    {
                        switch (attrib.Tag.TagValue)
                        {
                            case DicomTags.StudyInstanceUid:
                                {
                                    var uids = data[DicomTags.StudyInstanceUid].GetString(0, string.Empty);
                                    IQueryable<int> studyQuery = from s in pacsContext.Studies
                                                                 where uids.Contains(s.StudyUid)
                                                                 select s.Id;
                                    var result = studyQuery.ToArray();
                                    if (result.Length == 0)
                                    {
                                        server.SendCFindResponse(presentationId, message.MessageId, new DicomMessage(),
                                                             DicomStatuses.Success);
                                        return;
                                    }

                                    query = query.Where(QueryHelper.SetIntArrayCondition("StudyForeignKey", result));
                                }
                                break;
                            case DicomTags.SeriesInstanceUid:
                                {
                                    var cond = QueryHelper.SetStringArrayCondition("SeriesUid",
                                                                                   (string[])
                                                                                   data[DicomTags.SeriesInstanceUid]
                                                                                       .Values);
                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.Modality:
                                {
                                    var cond = QueryHelper.SetStringCondition("Modality",
                                                                              data[DicomTags.Modality].GetString(0,
                                                                                                                 string
                                                                                                                     .Empty));
                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.SeriesNumber:
                                {
                                    var cond = QueryHelper.SetStringCondition("SeriesNumber",
                                                                              data[DicomTags.SeriesNumber].GetString(0,
                                                                                                                     string
                                                                                                                         .Empty));
                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.SeriesDescription:
                                {
                                    var cond = QueryHelper.SetStringCondition("SeriesDescription",
                                                                              data[DicomTags.StudyDescription].GetString
                                                                                  (0, string.Empty));
                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.PerformedProcedureStepStartDate:
                                {
                                    var cond = QueryHelper.SetRangeCondition("PerformedProcedureStepStartDate",
                                                                             data[
                                                                                 DicomTags
                                                                                     .PerformedProcedureStepStartDate]
                                                                                 .GetString(0, string.Empty));
                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.PerformedProcedureStepStartTime:
                                {
                                    var cond = QueryHelper.SetRangeCondition("PerformedProcedureStepStartTime",
                                                                             data[
                                                                                 DicomTags
                                                                                     .PerformedProcedureStepStartTime]
                                                                                 .GetString(0, string.Empty));
                                    query = query.Where(cond);
                                }
                                break;
                            case DicomTags.RequestAttributesSequence: // todo
                                break;
                            default:
                                break;
                        }
                    }
                }

                int resultCount = 0;
                try
                {
                    foreach (Series series in query)
                    {
                        if (_cancelReceived)
                        {
                            throw new DicomException("DICOM C-Cancel Received");
                        }

                        resultCount++;
                        if (DicomSetting.Default.MaxQueryResponses != -1 &&
                            DicomSetting.Default.MaxQueryResponses < resultCount)
                        {
                            SendBufferedResponses(server, presentationId, message);
                            throw new DicomException("Maximum Configured Query Responses Exceeded: " + resultCount);
                        }

                        var response = new DicomMessage();
                        PopulateSeries(message, response, tagList, series);
                        _responseQueue.Enqueue(response);

                        if (_responseQueue.Count >= DicomSetting.Default.BufferedQueryResponses)
                        {
                            SendBufferedResponses(server, presentationId, message);
                        }
                    }

                    SendBufferedResponses(server, presentationId, message);
                }
                catch (Exception e)
                {
                    if (_cancelReceived)
                    {
                        var errorResponse = new DicomMessage();
                        server.SendCFindResponse(presentationId, message.MessageId, errorResponse,
                                                 DicomStatuses.Cancel);
                    }
                }
            }

            var finalResponse = new DicomMessage();
            server.SendCFindResponse(presentationId, message.MessageId, finalResponse, DicomStatuses.Success);
        }
Esempio n. 16
0
        public void OnSeriesQuery(DicomMessage message, SelectCallback <ISeriesData> callback)
        {
            // Support query conditions :
            // StudyInstanceUid, SeriesInstanceUid, Modality, SeriesDescription
            // SeriesNumber

            var data = message.DataSet;

            using (var ctx = new PacsContext())
            {
                #region Build Query

                //Linq query is lazy query mechanism
                var results = from row in ctx.Series select row;
                foreach (var attrib in message.DataSet)
                {
                    if (!attrib.IsNull)
                    {
                        switch (attrib.Tag.TagValue)
                        {
                        case DicomTags.StudyInstanceUid:
                            var studyUid = data[DicomTags.StudyInstanceUid].GetString(0,
                                                                                      string.Empty);

                            results = from row in results
                                      where row.Study.StudyUid.Equals(studyUid)
                                      select row;

                            break;

                        case DicomTags.SeriesInstanceUid:
                            var uid = data[DicomTags.SeriesInstanceUid].GetString(0, string.Empty);
                            results = from row in results
                                      where row.SeriesUid.Equals(uid)
                                      select row;

                            break;

                        case DicomTags.Modality:
                            var modality = data[DicomTags.Modality].GetString(0, string.Empty);
                            results = from row in results
                                      where row.Modality.Equals(modality)
                                      select row;
                            break;

                        case DicomTags.SeriesDescription:
                            var description = data[DicomTags.SeriesDescription].GetString(0, string.Empty);
                            var replaced    = QueryHelper.ReplacsWildcard(description);

                            if (replaced == null)
                            {
                                results = from row in results
                                          where row.SeriesDescription.Equals(description)
                                          select row;
                            }
                            else
                            {
                                results = from row in results
                                          where row.SeriesDescription.Contains(description)
                                          select row;
                            }

                            break;

                        case DicomTags.SeriesNumber:
                            var number = data[DicomTags.SeriesNumber].GetUInt32(0, 0);
                            results = from row in results
                                      where row.SeriesNumber.Equals(number.ToString())
                                      select row;

                            break;
                        }
                    }
                }

                foreach (var source in results.ToList())
                {
                    callback(source);
                }

                #endregion
            }
        }
Esempio n. 17
0
        public void OnPatientQuery(DicomMessage message, SelectCallback <IPatientData> callback)
        {
            // filter condition:
            // PatientsName, PatientsId, PatientsSex, PatientsBirthDate, PatientsBirthTime

            var data = message.DataSet;

            using (var ctx = new PacsContext())
            {
                var results = from patient in ctx.Patients select patient;

                foreach (var attrib in data)
                {
                    if (!attrib.IsNull)
                    {
                        #region Build Query

                        switch (attrib.Tag.TagValue)
                        {
                        case DicomTags.PatientsName:
                        {
                            var patientName = data[DicomTags.PatientsName].GetString(0,
                                                                                     string.Empty);
                            if (patientName.Length == 0)
                            {
                                break;
                            }

                            var replaced = QueryHelper.ReplacsWildcard(patientName);
                            if (replaced == null)
                            {
                                results = from row in results
                                          where row.PatientName.Equals(patientName)
                                          select row;
                            }
                            else
                            {
                                results = from row in results
                                          where row.PatientName.Contains(replaced)
                                          select row;
                            }

                            break;
                        }

                        case DicomTags.PatientId:
                        {
                            var patientId = data[DicomTags.PatientId].GetString(0, string.Empty);
                            if (patientId.Length == 0)
                            {
                                break;
                            }

                            var replaced = QueryHelper.ReplacsWildcard(patientId);
                            if (replaced == null)
                            {
                                results = from row in results
                                          where row.PatientId.Equals(patientId)
                                          select row;
                            }
                            else
                            {
                                results = from row in results
                                          where row.PatientId.Contains(replaced)
                                          select row;
                            }

                            break;
                        }

                        case DicomTags.PatientsBirthDate:
                        {
                            var values = (string[])data[DicomTags.PatientsBirthDate].Values;
                            if (values == null || values.Length == 0)
                            {
                                break;
                            }

                            //results = from study in results
                            //    where values.Length == 1
                            //        ? study.PatientBirthDate.Equals(values[0])
                            //        : values.Contains(study.PatientBirthDate)
                            //    select study;
                            break;
                        }

                        default:
                            break;
                        }

                        #endregion
                    }
                }

                foreach (var source in results.ToList())
                {
                    callback(source);
                }
            }
        }
Esempio n. 18
0
        public void OnStudyQuery(DicomMessage message, SelectCallback <IStudyData> callback)
        {
            // Supported Query Condition includes:
            // PatientsName, PatientsId, PatientsSex, PatientsBirthDate, PatientsBirthTime
            // StudyInstanceUid, StudyId, StudyDescription, AccessionNumber, ModalitiesInStudy
            // ReferringPhysiciansName, StudyDate, StudyTime

            var data = message.DataSet;

            using (var ctx = new PacsContext())
            {
                #region Build Query

                //Linq query is lazy query mechanism
                var results = from study in ctx.Studies select study;
                foreach (var attrib in message.DataSet)
                {
                    if (!attrib.IsNull)
                    {
                        switch (attrib.Tag.TagValue)
                        {
                        case DicomTags.PatientsName:
                        {
                            var patientName = data[DicomTags.PatientsName].GetString(0,
                                                                                     string.Empty);
                            if (patientName.Length == 0)
                            {
                                break;
                            }

                            var replaced = QueryHelper.ReplacsWildcard(patientName);
                            if (replaced == null)
                            {
                                results = from study in results
                                          where study.PatientName.Equals(patientName)
                                          select study;
                            }
                            else
                            {
                                results = from study in results
                                          where study.PatientName.Contains(replaced)
                                          select study;
                            }

                            break;
                        }

                        case DicomTags.PatientId:
                        {
                            var patientId = data[DicomTags.PatientId].GetString(0, string.Empty);
                            if (patientId.Length == 0)
                            {
                                break;
                            }

                            var replaced = QueryHelper.ReplacsWildcard(patientId);
                            if (replaced == null)
                            {
                                results = from row in results
                                          where row.PatientId.Equals(patientId)
                                          select row;
                            }
                            else
                            {
                                results = from row in results
                                          where row.PatientId.Contains(replaced)
                                          select row;
                            }

                            break;
                        }

                        case DicomTags.PatientsSex:
                        {
                            var values = (string[])data[DicomTags.PatientsSex].Values;
                            if (values == null || values.Length == 0)
                            {
                                break;
                            }

                            results = from study in results
                                      where values.Length == 1
                                        ? study.PatientSex.Equals(values[0])
                                        : values.Contains(study.PatientSex)
                                      select study;
                            break;
                        }

                        case DicomTags.PatientsBirthDate:
                        {
                            var values = (string[])data[DicomTags.PatientsBirthDate].Values;
                            if (values == null || values.Length == 0)
                            {
                                break;
                            }

                            var dt = DateParser.Parse(values[0]);
                            if (dt == null)
                            {
                                break;
                            }

                            results = from study in results
                                      where values.Length == 1
                                        ? study.PatientBirthday.Equals(dt.Value)
                                        : values.Contains(DateParser.ToDicomString(study.PatientBirthday))
                                      select study;
                            break;
                        }

                        case DicomTags.StudyDate:
                        {
                            var v = data[DicomTags.StudyDate].GetString(0, string.Empty);
                            if (string.IsNullOrEmpty(v))
                            {
                                break;
                            }

                            DateTime?startDate;
                            DateTime?toDate;
                            bool     isRange;
                            DateRangeHelper.Parse(v, out startDate, out toDate, out isRange);

                            if (isRange)
                            {
                                results = from study in results
                                          where study.StudyDate >= startDate.Value &&
                                          study.StudyDate <= toDate.Value
                                          select study;
                            }
                            else
                            {
                                if (startDate != null)
                                {
                                    results = from study in results
                                              where study.StudyDate >= startDate.Value
                                              select study;
                                }
                                else
                                {
                                    results = from study in results
                                              where study.StudyDate <= toDate.Value
                                              select study;
                                }
                            }

                            break;
                        }
                        }
                    }
                }

                #endregion

                Logger.Warn(results.ToString());

                foreach (var source in results.ToList())
                {
                    callback(source);
                }
            }
        }
Esempio n. 19
0
        public override bool OnReceiveRequest(DicomServer server, ServerAssociationParameters association,
                                              byte presentationID, DicomMessage message)
        {
            bool finalResponseSent = false;
            string errorComment;

            try
            {
                // check for a Cancel Message, and cance the scu 
                if (message.CommandField == DicomCommandField.CCancelRequest)
                {
                    if (_theScu != null)
                    {
                        _theScu.Cancel();
                    }

                    return true;
                }

                string level = message.DataSet[DicomTags.QueryRetrieveLevel].GetString(0, string.Empty);

                string remoteAe = message.MoveDestination.Trim();

                // load remote device for move information 
                using (var ctx = new PacsContext())
                {
                    var device = (from d in ctx.Devices
                                  where d.ServerPartitionPK == Partition.Id && d.AeTitle == remoteAe
                                  select d).FirstOrDefault();

                    if (device == null)
                    {
                        errorComment = string.Format(
                            "Unknown move destination \"{0}\", failing C-MOVE-RQ from {1} to {2}",
                            remoteAe, association.CallingAE, association.CalledAE);
                        Platform.Log(LogLevel.Error, errorComment);
                        server.SendCMoveResponse(presentationID, message.MessageId, new DicomMessage(),
                                                 DicomStatuses.QueryRetrieveMoveDestinationUnknown, errorComment);
                        finalResponseSent = true;
                        return true;
                    }

                    // If the remote node is a DHCP node, use its IP address from the connection information, else
                    // use what is configured.  Always use the configured port. 
                    if (device.Dhcp)
                    {
                        device.Hostname = association.RemoteEndPoint.Address.ToString();
                    }

                    // now setup the storage scu component 
                    _theScu = new PacsStorageScu(Partition, device, association.CallingAE, message.MessageId);

                    bool bOnline;

                    if (level.Equals("PATIENT"))
                    {
                        bOnline = GetSopListForInstance(ctx, message, out errorComment);
                    }
                    else if (level.Equals("STUDY"))
                    {
                        bOnline = GetSopListForStudy(ctx, message, out errorComment);
                    }
                    else if (level.Equals("SERIES"))
                    {
                        bOnline = GetSopListForSeries(ctx, message, out errorComment);
                    }
                    else if (level.Equals("IMAGE"))
                    {
                        bOnline = GetSopListForInstance(ctx, message, out errorComment);
                    }
                    else
                    {
                        errorComment = string.Format("Unexpected Study Root Move Query/Retrieve level: {0}", level);
                        Platform.Log(LogLevel.Error, errorComment);

                        server.SendCMoveResponse(presentationID, message.MessageId, new DicomMessage(),
                                                 DicomStatuses.QueryRetrieveIdentifierDoesNotMatchSOPClass,
                                                 errorComment);
                        finalResponseSent = true;
                        return true;
                    }

                    // Could not find an online/readable location for the requested objects to move.
                    // Note that if the C-MOVE-RQ included a list of study instance uids, and some 
                    // were online and some offline, we don't fail now (ie, the check on the Count)
                    if (!bOnline || _theScu.StorageInstanceList.Count == 0)
                    {
                        Platform.Log(LogLevel.Error, "Unable to find online storage location for C-MOVE-RQ: {0}",
                                     errorComment);

                        server.SendCMoveResponse(presentationID, message.MessageId, new DicomMessage(),
                                                 DicomStatuses.QueryRetrieveUnableToPerformSuboperations,
                                                 string.IsNullOrEmpty(errorComment) ? string.Empty : errorComment);
                        finalResponseSent = true;
                        _theScu.Dispose();
                        _theScu = null;
                        return true;
                    }

                    _theScu.ImageStoreCompleted += delegate(Object sender, StorageInstance instance)
                        {
                            var scu = (StorageScu) sender;
                            var msg = new DicomMessage();
                            DicomStatus status;

                            if (instance.SendStatus.Status == DicomState.Failure)
                            {
                                errorComment =
                                    string.IsNullOrEmpty(instance.ExtendedFailureDescription)
                                        ? instance.SendStatus.ToString()
                                        : instance.ExtendedFailureDescription;
                            }

                            if (scu.RemainingSubOperations == 0)
                            {
                                foreach (StorageInstance sop in _theScu.StorageInstanceList)
                                {
                                    if ((sop.SendStatus.Status != DicomState.Success)
                                        && (sop.SendStatus.Status != DicomState.Warning))
                                        msg.DataSet[DicomTags.FailedSopInstanceUidList].AppendString(sop.SopInstanceUid);
                                }
                                if (scu.Status == ScuOperationStatus.Canceled)
                                    status = DicomStatuses.Cancel;
                                else if (scu.Status == ScuOperationStatus.ConnectFailed)
                                    status = DicomStatuses.QueryRetrieveMoveDestinationUnknown;
                                else if (scu.FailureSubOperations > 0)
                                    status = DicomStatuses.QueryRetrieveSubOpsOneOrMoreFailures;
                                else if (!bOnline)
                                    status = DicomStatuses.QueryRetrieveUnableToPerformSuboperations;
                                else
                                    status = DicomStatuses.Success;
                            }
                            else
                            {
                                status = DicomStatuses.Pending;

                                if ((scu.RemainingSubOperations%5) != 0)
                                    return;
                                // Only send a RSP every 5 to reduce network load
                            }
                            server.SendCMoveResponse(presentationID, message.MessageId,
                                                     msg, status,
                                                     (ushort) scu.SuccessSubOperations,
                                                     (ushort) scu.RemainingSubOperations,
                                                     (ushort) scu.FailureSubOperations,
                                                     (ushort) scu.WarningSubOperations,
                                                     status == DicomStatuses.QueryRetrieveSubOpsOneOrMoreFailures
                                                         ? errorComment
                                                         : string.Empty);


                            if (scu.RemainingSubOperations == 0)
                                finalResponseSent = true;
                        };

                    _theScu.BeginSend(
                        delegate(IAsyncResult ar)
                            {
                                if (_theScu != null)
                                {
                                    if (!finalResponseSent)
                                    {
                                        var msg = new DicomMessage();
                                        server.SendCMoveResponse(presentationID, message.MessageId,
                                                                 msg, DicomStatuses.QueryRetrieveSubOpsOneOrMoreFailures,
                                                                 (ushort) _theScu.SuccessSubOperations,
                                                                 0,
                                                                 (ushort)
                                                                 (_theScu.FailureSubOperations +
                                                                  _theScu.RemainingSubOperations),
                                                                 (ushort) _theScu.WarningSubOperations, errorComment);
                                        finalResponseSent = true;
                                    }

                                    _theScu.EndSend(ar);
                                    _theScu.Dispose();
                                    _theScu = null;
                                }
                            },
                        _theScu);

                    return true;
                }
            }
            catch (Exception e)
            {
                Platform.Log(LogLevel.Error, e, "Unexpected exception when processing C-MOVE-RQ");
                if (finalResponseSent == false)
                {
                    try
                    {
                        server.SendCMoveResponse(presentationID, message.MessageId, new DicomMessage(),
                                                 DicomStatuses.QueryRetrieveUnableToProcess, e.Message);
                        finalResponseSent = true;
                    }
                    catch (Exception x)
                    {
                        Platform.Log(LogLevel.Error, x,
                                     "Unable to send final C-MOVE-RSP message on association from {0} to {1}",
                                     association.CallingAE, association.CalledAE);
                        server.Abort();
                    }
                }
            }

            return false;
        }
Esempio n. 20
0
        private bool GetSopListForInstance(PacsContext ctx, DicomMessage message, out string errorComment)
        {
            errorComment = string.Empty;

            string studyInstanceUid = message.DataSet[DicomTags.StudyInstanceUid].GetString(0, "");
            string seriesInstanceUid = message.DataSet[DicomTags.SeriesInstanceUid].GetString(0, "");
            var sopInstanceUidArray = (string[])message.DataSet[DicomTags.SopInstanceUid].Values;

            var sopPkArray =
                (from s in ctx.Instances where sopInstanceUidArray.Contains(s.SopInstanceUid) select s.Id).ToList();

            var fileList =
                (from f in ctx.Files where sopPkArray.Contains(f.InstanceFk) select f).ToList();

            foreach (var file in fileList)
            {
                _theScu.AddStorageInstance(new StorageInstance(file.FilePath));
            }

            return true;
        }
Esempio n. 21
0
        private bool GetSopListForSeries(PacsContext ctx, DicomMessage message, out string errorComment)
        {
            errorComment = string.Empty;

            var studyInstanctUid = message.DataSet[DicomTags.StudyInstanceUid].GetString(0, string.Empty);
            var seriesUidList = (string[]) message.DataSet[DicomTags.SeriesInstanceUid].Values;

            int studyPk = ctx.Studies.Where(s => s.StudyUid == studyInstanctUid).Select(s => s.Id).FirstOrDefault();

            var seriesPkList = (from s in ctx.Series where seriesUidList.Contains(s.SeriesUid) select s.Id).ToList();

            var sopList = (from s in ctx.Instances where seriesPkList.Contains(s.SeriesForeignKey) select s.Id).ToList();

            var fileList = (from f in ctx.Files where sopList.Contains(f.InstanceFk) select f).ToList();

            foreach (var file in fileList)
            {
                _theScu.AddStorageInstance(new StorageInstance(file.FilePath));
            }

            return true;
        }
Esempio n. 22
0
        private void OnReceivePatientQuery(DicomServer server, byte presentationId, DicomMessage message)
        {
            var tagList = new List<DicomTag>();

            using (var pacsContext = new PacsContext())
            {
                var adapter = (IObjectContextAdapter)pacsContext;
                var query = new ObjectQuery<Patient>("Patients", adapter.ObjectContext);

                DicomAttributeCollection data = message.DataSet;

                foreach (DicomAttribute attribute in data)
                {
                    tagList.Add(attribute.Tag);
                    if (!attribute.IsNull)
                    {
                        switch (attribute.Tag.TagValue)
                        {
                            case DicomTags.PatientsName:
                                {
                                    var cond = QueryHelper.SetStringCondition("PatientName",
                                                                   data[DicomTags.PatientsName].GetString(0, string.Empty));
                                    query = query.Where(cond);
                                    break;
                                }

                            case DicomTags.PatientId:
                                {
                                    var cond = QueryHelper.SetStringCondition("PatientId",
                                                               data[DicomTags.PatientId].GetString(0, string.Empty));
                                    query = query.Where(cond);
                                    break;
                                }

                            case DicomTags.IssuerOfPatientId:
                                {
                                    var cond = QueryHelper.SetStringCondition("Issuer",
                                                                              data[DicomTags.IssuerOfPatientId]
                                                                                  .GetString(0, string.Empty));
                                }
                                break;
                            case DicomTags.PatientsSex:
                                break;
                            case DicomTags.PatientsBirthDate:
                                {
                                    var cond = QueryHelper.SetStringArrayCondition("PatientBirthDate",
                                                                                   (string[])
                                                                                   data[DicomTags.PatientsBirthDate]
                                                                                       .Values);
                                    query = query.Where(cond);
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }

                int resultCount = 0;
                try
                {
                    foreach (Patient patient in query)
                    {
                        if (_cancelReceived)
                        {
                            throw new DicomException("DICOM C-Cancel Received");
                        }

                        resultCount++;
                        if (DicomSetting.Default.MaxQueryResponses != -1 &&
                            DicomSetting.Default.MaxQueryResponses < resultCount)
                        {
                            SendBufferedResponses(server, presentationId, message);
                            throw new DicomException("Maximum Configured Query Responses Exceeded: " + resultCount);
                        }

                        var response = new DicomMessage();
                        PopulatePatient(response, tagList, patient);
                        _responseQueue.Enqueue(response);

                        if (_responseQueue.Count >= DicomSetting.Default.BufferedQueryResponses)
                        {
                            SendBufferedResponses(server, presentationId, message);
                        }
                    }

                    SendBufferedResponses(server, presentationId, message);
                }
                catch (Exception e)
                {
                    if (_cancelReceived)
                    {
                        var errorResponse = new DicomMessage();
                        server.SendCFindResponse(presentationId, message.MessageId, errorResponse,
                                                 DicomStatuses.Cancel);
                    }
                }
            }

            var finalResponse = new DicomMessage();
            server.SendCFindResponse(presentationId, message.MessageId, finalResponse, DicomStatuses.Success);
        }
Esempio n. 23
0
        private uWs.PACS.Model.File InsertFile(PacsContext context, Instance instance, Series dbSeries, Study dbStudy,
            Patient dbPatient)
        {
            var partition = context.ServerPartitions.First(p => p.Id == _context.Partition.Id);

            string fsDir = partition.FileSystem.DirPath;

            var filepath = Path.Combine(fsDir, dbPatient.PatientId, dbStudy.StudyUid, dbSeries.SeriesUid,
                                        instance.SopInstanceUid);

            var dbFile = context.Files.FirstOrDefault(f => f.InstanceFk.Equals(instance.Id));
            if (dbFile == null)
            {
                dbFile = new uWs.PACS.Model.File
                    {
                        CreateTime = DateTime.Now
                    };
                context.Files.Add(dbFile);
            }

            dbFile.InstanceFk = instance.Id;
            dbFile.FilePath = filepath;
            dbFile.FileSystemFk = partition.FileSystem.Id;

            return dbFile;
        }
Esempio n. 24
0
        private Series InsertSeries(PacsContext context, Series series, Study dbStudy, Patient dbPatient)
        {
            var dbSeries = context.Series.FirstOrDefault(s => s.SeriesUid.Equals(series.SeriesUid));
            if (dbSeries == null)
            {
                dbSeries = series;
                dbSeries.StudyForeignKey = dbStudy.Id;
                dbSeries.InsertTime = DateTime.Now;
                context.Series.Add(dbSeries);

                dbStudy.NumberOfRelatedSeries += 1;
                dbPatient.NumberOfRelatedSeries += 1;
            }

            return dbSeries;
        }
Esempio n. 25
0
        // what is the scenario about image level query 
        // TODO add support in Image Level Query 
        private void OnReceiveImageLevelQuery(DicomServer server, byte presentationId, DicomMessage message)
        {
            var tagList = new List<DicomTag>();

            using (var pacsContext = new PacsContext())
            {
                var adapter = (IObjectContextAdapter)pacsContext;
                var query = new ObjectQuery<Instance>("Instances", adapter.ObjectContext);

                DicomAttributeCollection data = message.DataSet;
                string studyInstanceUid = data[DicomTags.StudyInstanceUid].GetString(0, String.Empty);
                string seriesInstanceUid = data[DicomTags.SeriesInstanceUid].GetString(0, String.Empty);

                foreach (DicomAttribute attrib in data)
                {
                    if (attrib.Tag.TagValue.Equals(DicomTags.SpecificCharacterSet)
                        || attrib.Tag.TagValue.Equals(DicomTags.QueryRetrieveLevel))
                        continue;

                    tagList.Add(attrib.Tag);
                    if (!attrib.IsNull)
                    {
                        switch (attrib.Tag.TagValue)
                        {

                        }
                    }
                }

                int resultCount = 0;
                try
                {
                    foreach (Instance instance in query)
                    {
                        if (_cancelReceived)
                        {
                            throw new DicomException("DICOM C-Cancel Received");
                        }

                        resultCount++;
                        if (DicomSetting.Default.MaxQueryResponses != -1 &&
                            DicomSetting.Default.MaxQueryResponses < resultCount)
                        {
                            SendBufferedResponses(server, presentationId, message);
                            throw new DicomException("Maximum Configured Query Responses Exceeded: " + resultCount);
                        }

                        var response = new DicomMessage();
                        PopuldateInstance(message, response, tagList, instance);
                        _responseQueue.Enqueue(response);

                        if (_responseQueue.Count >= DicomSetting.Default.BufferedQueryResponses)
                        {
                            SendBufferedResponses(server, presentationId, message);
                        }
                    }

                    SendBufferedResponses(server, presentationId, message);
                }
                catch (Exception e)
                {
                    if (_cancelReceived)
                    {
                        var errorResponse = new DicomMessage();
                        server.SendCFindResponse(presentationId, message.MessageId, errorResponse,
                                                 DicomStatuses.Cancel);
                    }
                }
            }

            var finalResponse = new DicomMessage();
            server.SendCFindResponse(presentationId, message.MessageId, finalResponse, DicomStatuses.Success);
        }
Esempio n. 26
0
        public DicomProcessingResult Import(DicomMessage dicomMessage)
        {
            var result = new DicomProcessingResult()
            {
                Successful = true,
            };

            if (dicomMessage.DataSet == null)
            {
                result.Successful = false;
            }

            DateTime dt = new DateTime();

            var patient = new Patient
            {
                PatientId         = dicomMessage.DataSet[DicomTags.PatientId].GetString(0, string.Empty),
                PatientName       = dicomMessage.DataSet[DicomTags.PatientsName].GetString(0, string.Empty),
                PatientBirthDate  = dicomMessage.DataSet[DicomTags.PatientsBirthDate].GetDateTime(0, dt),
                IssuerOfPatientId = dicomMessage.DataSet[DicomTags.IssuerOfPatientId].GetString(0, string.Empty),
            };

            var study = new Study()
            {
                StudyId          = dicomMessage.DataSet[DicomTags.StudyId].GetString(0, string.Empty),
                StudyUid         = dicomMessage.DataSet[DicomTags.StudyInstanceUid].GetString(0, string.Empty),
                AccessionNumber  = dicomMessage.DataSet[DicomTags.AccessionNumber].GetString(0, string.Empty),
                StudyDate        = dicomMessage.DataSet[DicomTags.StudyDate].GetDateTime(0, dt),
                StudyTime        = dicomMessage.DataSet[DicomTags.StudyTime].GetDateTime(0, dt),
                RefPhysician     = dicomMessage.DataSet[DicomTags.ReferringPhysiciansName].GetString(0, string.Empty),
                StudyDescription = dicomMessage.DataSet[DicomTags.StudyDescription].GetString(0, string.Empty),

                PatientId       = patient.PatientId,
                PatientName     = patient.PatientName,
                PatientBirthday = patient.PatientBirthDate,
                PatientAge      = dicomMessage.DataSet[DicomTags.PatientsAge].GetString(0, string.Empty),
                PatientSize     = dicomMessage.DataSet[DicomTags.PatientsSize].GetString(0, string.Empty),
                PatientWeight   = dicomMessage.DataSet[DicomTags.PatientsWeight].GetString(0, string.Empty),
                PatientSex      = dicomMessage.DataSet[DicomTags.PatientsSex].GetString(0, string.Empty)
            };

            var series = new Series()
            {
                SeriesUid         = dicomMessage.DataSet[DicomTags.SeriesInstanceUid].GetString(0, string.Empty),
                SeriesNumber      = dicomMessage.DataSet[DicomTags.SeriesNumber].GetString(0, string.Empty),
                Modality          = dicomMessage.DataSet[DicomTags.Modality].GetString(0, string.Empty),
                BodyPart          = dicomMessage.DataSet[DicomTags.BodyPartExamined].GetString(0, string.Empty),
                Institution       = dicomMessage.DataSet[DicomTags.InstitutionName].GetString(0, string.Empty),
                StationName       = dicomMessage.DataSet[DicomTags.StationName].GetString(0, string.Empty),
                Department        = dicomMessage.DataSet[DicomTags.InstitutionalDepartmentName].GetString(0, string.Empty),
                PerfPhysician     = dicomMessage.DataSet[DicomTags.PerformingPhysiciansName].GetString(0, string.Empty),
                SeriesDate        = dicomMessage.DataSet[DicomTags.SeriesDate].GetDateTime(0, dt),
                SeriesTime        = dicomMessage.DataSet[DicomTags.SeriesTime].GetDateTime(0, dt),
                SeriesDescription = dicomMessage.DataSet[DicomTags.SeriesDescription].GetString(0, string.Empty),
                PerformedProcedureStepStartDate = dicomMessage.DataSet[DicomTags.PerformedProcedureStepStartDate].GetDateTime(0, dt),
                PerformedProcedureStepStartTime = dicomMessage.DataSet[DicomTags.PerformedProcedureStepStartTime].GetDateTime(0, dt),
            };

            var instance = new Instance()
            {
                SopInstanceUid = dicomMessage.DataSet[DicomTags.SopInstanceUid].GetString(0, string.Empty),
                SopClassUid    = dicomMessage.DataSet[DicomTags.SopClassUid].GetString(0, string.Empty),
                InstanceNumber = dicomMessage.DataSet[DicomTags.InstanceNumber].GetString(0, string.Empty),
                ContentDate    = dicomMessage.DataSet[DicomTags.ContentDate].GetDateTime(0, dt),
                ContentTime    = dicomMessage.DataSet[DicomTags.ContentTime].GetDateTime(0, dt)
            };

            if (string.IsNullOrEmpty(study.StudyUid) ||
                string.IsNullOrEmpty(series.SeriesUid) ||
                string.IsNullOrEmpty(instance.SopInstanceUid))
            {
                result.Successful = false;
            }

            // Get Patient Db Object
            using (var context = new PacsContext())
            {
                Patient dbPatient = null;

                var dbStudy = InsertStudy(context, study, patient, out dbPatient);

                // Patient and study is exist in db now
                var dbSeries = InsertSeries(context, series, dbStudy, dbPatient);

                // insert instance
                var dbInstance = InsertImage(context, instance, dbSeries, dbStudy, dbPatient);

                var dbFile = InsertFile(context, dbInstance, dbSeries, dbStudy, dbPatient);

                var dicomFile = new DicomFile(dicomMessage, dbFile.FilePath);

                if (!Directory.Exists(Path.GetDirectoryName(dbFile.FilePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(dbFile.FilePath));
                }

                dicomFile.Save();

                context.SaveChanges();

                result.DicomStatus = DicomStatuses.Success;
            }

            return(result);
        }
Esempio n. 27
0
        private Study InsertStudy(PacsContext context, Study study, Patient patient, out Patient dbPatient)
        {
            var dbStudy = context.Studies.FirstOrDefault(s => s.StudyUid.Equals(study.StudyUid));
            if (dbStudy == null)
            {
                // check is patient exist by patient id, patient name and so on. 
                var tempResult = (context.Patients.Where(p => p.PatientId.Equals(patient.PatientId))).ToList();

                // TODO Patient strategy 
                dbPatient = tempResult.FirstOrDefault();
                if (dbPatient == null)
                {
                    patient.LastUpdateTime = DateTime.Now;
                    patient.InsertTime = DateTime.Now;
                    context.Patients.Add(patient);
                    dbPatient = patient;
                }

                // Insert Study info 
                dbStudy = study;
                dbStudy.PatientForeignKey = dbPatient.Id;
                dbStudy.InsertTime = DateTime.Now;
                context.Studies.Add(dbStudy);

                dbPatient.NumberOfRelatedStudies += 1;
            }
            else
            {
                dbPatient = dbStudy.Patient;
            }

            return dbStudy;
        }
Esempio n. 28
0
        private bool GetSopListForPatient(PacsContext ctx, DicomMessage message, out string errorComment)
        {
            errorComment = string.Empty;

            var patientId = message.DataSet[DicomTags.PatientId].GetString(0, string.Empty);
            int patientPK = ctx.Patients.Where(p => p.PatientId == patientId).Select(p => p.Id).FirstOrDefault();

            var studyList = (ctx.Studies.Where(s => s.PatientForeignKey == patientPK)).ToList();

            foreach (var study in studyList)
            {
                var seriesPkList = (from s in ctx.Series where study.Id == s.StudyForeignKey select s.Id).ToList();

                var sopList = (from s in ctx.Instances where seriesPkList.Contains(s.SeriesForeignKey) select s.Id).ToList();

                var fileList = (from f in ctx.Files where sopList.Contains(f.InstanceFk) select f).ToList();

                foreach (var file in fileList)
                {
                    _theScu.AddStorageInstance(new StorageInstance(file.FilePath));
                }
            }

            return true;
        }
Esempio n. 29
0
        private Instance InsertImage(PacsContext context, Instance instance, Series dbSeries, Study dbStudy,
                                        Patient dbPatient)
        {
            var dbInstance = context.Instances.FirstOrDefault(i => i.SopInstanceUid.Equals(instance.SopInstanceUid));
            if (dbInstance == null)
            {
                dbInstance = instance;
                dbInstance.SeriesForeignKey = dbSeries.Id;
                dbInstance.LastUpdateTime = DateTime.Now;
                dbInstance.InsertTime = DateTime.Now;
                context.Instances.Add(dbInstance);

                dbSeries.NumberOfRelatedImage += 1;
                dbStudy.NumberOfRelatedImage += 1;
                dbPatient.NumberOfRelatedInstances += 1;
            }

            dbInstance.LastUpdateTime = DateTime.Now;
            dbSeries.LastUpdateTime = DateTime.Now;
            dbStudy.LastUpdateTime = DateTime.Now;
            dbPatient.LastUpdateTime = DateTime.Now;

            return dbInstance;
        }
Esempio n. 30
0
        private bool GetSopListForStudy(PacsContext ctx, DicomMessage message, out string errorComment)
        {
            errorComment = string.Empty;

            var studyUidList = (string[])message.DataSet[DicomTags.StudyInstanceUid].Values;

            var studyList = (from s in ctx.Studies where studyUidList.Contains(s.StudyUid) select s).ToList();

            foreach (var study in studyList)
            {
                var seriesPkList = (from s in ctx.Series where study.Id == s.StudyForeignKey select s.Id).ToList();

                var sopList = (from s in ctx.Instances where seriesPkList.Contains(s.SeriesForeignKey) select s.Id).ToList();

                var fileList = (from f in ctx.Files where sopList.Contains(f.InstanceFk) select f).ToList();

                foreach (var file in fileList)
                {
                    _theScu.AddStorageInstance(new StorageInstance(file.FilePath));
                }
            }

            return true;
        }
Esempio n. 31
0
        public bool Import(DicomMessage dicomMessage)
        {
            if (dicomMessage.DataSet == null)
            {
                throw new ArgumentException();
            }

            var patient = new Patient
            {
                PatientId = dicomMessage.DataSet[DicomTags.PatientId].GetString(0, string.Empty),
                PatientName = dicomMessage.DataSet[DicomTags.PatientsName].GetString(0, string.Empty),
                PatientBirthDate = dicomMessage.DataSet[DicomTags.PatientsBirthDate].GetString(0, string.Empty),
                Issuer = dicomMessage.DataSet[DicomTags.IssuerOfPatientId].GetString(0, string.Empty),
            };

            var study = new Study()
            {
                StudyId = dicomMessage.DataSet[DicomTags.StudyId].GetString(0, string.Empty),
                StudyUid = dicomMessage.DataSet[DicomTags.StudyInstanceUid].GetString(0, string.Empty),
                AccessionNumber = dicomMessage.DataSet[DicomTags.AccessionNumber].GetString(0, string.Empty),
                StudyDate = dicomMessage.DataSet[DicomTags.StudyDate].GetString(0, string.Empty),
                StudyTime = dicomMessage.DataSet[DicomTags.StudyTime].GetString(0, string.Empty),
                RefPhysician = dicomMessage.DataSet[DicomTags.ReferringPhysiciansName].GetString(0, string.Empty),
                StudyDescription = dicomMessage.DataSet[DicomTags.StudyDescription].GetString(0, string.Empty),

                PatientId = patient.PatientId,
                PatientName = patient.PatientName,
                PatientBirthday = patient.PatientBirthDate,
                PatientAge = dicomMessage.DataSet[DicomTags.PatientsAge].GetString(0, string.Empty),
                PatientSize = dicomMessage.DataSet[DicomTags.PatientsSize].GetString(0, string.Empty),
                PatientWeight = dicomMessage.DataSet[DicomTags.PatientsWeight].GetString(0, string.Empty),
                PatientSex = dicomMessage.DataSet[DicomTags.PatientsSex].GetString(0, string.Empty)
            };

            var series = new Series()
            {
                SeriesUid = dicomMessage.DataSet[DicomTags.SeriesInstanceUid].GetString(0, string.Empty),
                SeriesNumber = dicomMessage.DataSet[DicomTags.SeriesNumber].GetString(0, string.Empty),
                Modality = dicomMessage.DataSet[DicomTags.Modality].GetString(0, string.Empty),
                BodyPart = dicomMessage.DataSet[DicomTags.BodyPartExamined].GetString(0, string.Empty),
                Institution = dicomMessage.DataSet[DicomTags.InstitutionName].GetString(0, string.Empty),
                StationName = dicomMessage.DataSet[DicomTags.StationName].GetString(0, string.Empty),
                Department = dicomMessage.DataSet[DicomTags.InstitutionalDepartmentName].GetString(0, string.Empty),
                PerfPhysician = dicomMessage.DataSet[DicomTags.PerformingPhysiciansName].GetString(0, string.Empty),
                SeriesDate = dicomMessage.DataSet[DicomTags.SeriesDate].GetString(0, string.Empty),
                SeriesTime = dicomMessage.DataSet[DicomTags.SeriesTime].GetString(0, string.Empty),
                SeriesDescription = dicomMessage.DataSet[DicomTags.SeriesDescription].GetString(0, string.Empty),
                PerformedProcedureStepStartDate = dicomMessage.DataSet[DicomTags.PerformedProcedureStepStartDate].GetString(0, string.Empty),
                PerformedProcedureStepStartTime = dicomMessage.DataSet[DicomTags.PerformedProcedureStepStartTime].GetString(0, string.Empty),
            };

            var instance = new Instance()
            {
                SopInstanceUid = dicomMessage.DataSet[DicomTags.SopInstanceUid].GetString(0, string.Empty),
                SopClassUid = dicomMessage.DataSet[DicomTags.SopClassUid].GetString(0, string.Empty),
                InstanceNumber = dicomMessage.DataSet[DicomTags.InstanceNumber].GetString(0, string.Empty),
                ContentDate = dicomMessage.DataSet[DicomTags.ContentDate].GetString(0, string.Empty),
                ContentTime = dicomMessage.DataSet[DicomTags.ContentTime].GetString(0, string.Empty)
            };

            if (string.IsNullOrEmpty(study.StudyUid)
                || string.IsNullOrEmpty(series.SeriesUid)
                || string.IsNullOrEmpty(instance.SopInstanceUid))
            {
                throw new ArgumentException();
            }

            // Get Patient Db Object 
            using (var context = new PacsContext())
            {
                Patient dbPatient = null;

                var dbStudy = InsertStudy(context, study, patient, out dbPatient);

                // Patient and study is exist in db now
                var dbSeries = InsertSeries(context, series, dbStudy, dbPatient);

                // insert instance 
                var dbInstance = InsertImage(context, instance, dbSeries, dbStudy, dbPatient);

                var dbFile = InsertFile(context, dbInstance, dbSeries, dbStudy, dbPatient);

                var dicomFile = new DicomFile(dicomMessage, dbFile.FilePath);
                
                if (!Directory.Exists(Path.GetDirectoryName(dbFile.FilePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(dbFile.FilePath));
                }

                dicomFile.Save();

                context.SaveChanges();
            }

            return true;
        }
Esempio n. 32
0
        public static Device LookupDevice(ServerPartition partition, AssociationParameters association,
                                          out bool isNew)
        {
            isNew = false;

            Device device = null;

            using (var ctx = new PacsContext())
            {
                var part = (from p in ctx.ServerPartitions select p).FirstOrDefault();
                if (part != null)
                {
                    device = part.Devices.FirstOrDefault(d => d.AeTitle.Equals(association.CallingAE));
                }

                if (device == null)
                {
                    if (!partition.AcceptAnyDevice)
                    {
                        return null;
                    }

                    if (partition.AutoInsertDevice)
                    {
                        device = new Device
                        {
                            AeTitle = association.CallingAE,
                            Enabled = true,
                            Description = string.Format("AE: {0}", association.CallingAE),
                            //TODO
                            Port = 104,
                            AllowQuery = true,
                            AllowRetrieve = true,
                            AllowStorage = true,
                            ServerPartitionPK = part.Id,
                            LastAccessTime = DateTime.Now
                        };

                        ctx.Devices.Add(device);
                        ctx.SaveChanges();

                        isNew = true;
                    }
                }

                if (device != null)
                {
                    if (device.Dhcp && !association.RemoteEndPoint.Address.ToString().Equals(device.Hostname))
                    {
                        device.Hostname = association.RemoteEndPoint.Address.ToString();

                        device.LastAccessTime = DateTime.Now;
                        ctx.SaveChanges();
                    }
                    else if (!isNew)
                    {
                        device.LastAccessTime = DateTime.Now;
                        ctx.SaveChanges();
                    }
                }
            }

            return device;
        }