示例#1
0
        // This example builds a IDbCommand
        // for querying the MyPatient table
        // The generated WHERE clause contains PatientName and PatientSex
        public void MyExample()
        {
            MatchingParameterCollection matchingParamCollection = new MatchingParameterCollection();
            MatchingParameterList       matchingParamList       = new MatchingParameterList();

            MyPatient myPatient = new MyPatient();

            myPatient.PatientName = "Smith";
            myPatient.PatientSex  = "M";

            matchingParamList.Add(myPatient);
            matchingParamCollection.Add(matchingParamList);

            IDbCommand command = new SqlCommand();

            // This reads the storage catalog
            // Before you run this, make sure and add the following to your application configuration file

            //<configSections>
            //    <section name="xmlStorageCatalogSettings" type="Leadtools.Medical.Storage.DataAccessLayer.XmlStorageCatalogSettings, Leadtools.Medical.Storage.DataAccessLayer" />
            //</configSections>
            StorageCatalog myCatalog = new StorageCatalog();

            Collection <CatalogElement[]> catalogElements = CatalogDescriptor.GetElementsCollection(matchingParamCollection, myCatalog, true);

            PreparePatientsQueryCommand(command, catalogElements, ExtraQueryOptions.Typical);

            // The 'WHERE' clause of command.CommandText is the following:
            //    WHERE ( (  MyPatientTable.PatientName LIKE  'Smith' ) AND (  MyPatientTable.PatientSex LIKE  'M' ) )
            Console.WriteLine(command.CommandText);
        }
示例#2
0
        private CompositeInstanceDataSet GetReferencedCompositeInstancesAndFillInstanceProfiles
        (
            Dictionary <string, string> instanceSopProfileName
        )
        {
            MatchingParameterCollection matchingCollection;
            MatchingParameterList       matchingList;


            matchingCollection = new MatchingParameterCollection( );

            foreach (MediaCreationReferencedSop referencedSop in MediaObject.ReferencedSopSequence)
            {
                matchingList = new MatchingParameterList( );

                matchingCollection.Add(matchingList);

                ICatalogEntity instanceEntity = RegisteredEntities.GetInstanceEntity(referencedSop.SopInstance.ReferencedSopInstanceUid);
                matchingList.Add(instanceEntity);

                instanceSopProfileName.Add(referencedSop.SopInstance.ReferencedSopInstanceUid,
                                           referencedSop.RequestedMediaApplicationProfile);
            }

            return(StorageService.QueryCompositeInstances(matchingCollection).ToCompositeInstanceDataSet());
        }
示例#3
0
        public WorklistResult[] QueryWorklist(string userName, WorklistQueryOptions options)
        {
            List <WorklistResult>       results            = new List <WorklistResult>();
            MatchingParameterCollection matchingCollection = new MatchingParameterCollection();
            MatchingParameterList       matchingList       = new MatchingParameterList();
            MWLDataset dataset = null;


            matchingCollection.Add(matchingList);
            AddInsUtils.FillWorklistMatchingParameters(options, matchingList);
            dataset = _DataAccessAgent.QueryModalityWorklists(matchingCollection, new StringCollection());
            foreach (MWLDataset.ScheduledProcedureStepRow row in dataset.ScheduledProcedureStep.Rows)
            {
                WorklistResult result = new WorklistResult();

                result.ScheduledProcedureStep = new WorklistScheduledProcedureStep();
                result.Patient = new WorklistPatient();
                row.CopyTo(result.ScheduledProcedureStep);

                row.RequestedProcedureRowParent.ImagingServiceRequestRow.PatientRowParent.CopyTo(result.Patient);
                results.Add(result);

                result.ImagingServiceRequest = new ImagingServiceRequest();
                row.RequestedProcedureRowParent.ImagingServiceRequestRow.CopyTo(result.ImagingServiceRequest);

                result.RequestedProcedure = new WorklistRequestedProcedure();
                row.RequestedProcedureRowParent.CopyTo(result.RequestedProcedure);
            }

            return(results.ToArray());
        }
        MatchingParameterCollection GenerateMatchingParameterCollection(ViewGenerator.ViewDataRow metadataRow, out string rowKeyValue, out string rowKeyName, out string viewName)
        {
            DataRow originalRow = metadataRow.OriginalRow;
            MatchingParameterCollection matchingParamCollection = new MatchingParameterCollection();
            MatchingParameterList       matchingParamList       = new MatchingParameterList();

            matchingParamCollection.Add(matchingParamList);

            if (string.Compare(originalRow.Table.TableName, DataTableHelper.InstanceTableName) == 0)
            {
                string         sSopInstanceUid = RegisteredDataRows.InstanceInfo.GetElementValue(originalRow, DicomTag.SOPInstanceUID);
                ICatalogEntity imageInstance   = RegisteredEntities.GetInstanceEntity(sSopInstanceUid);

                rowKeyValue = sSopInstanceUid;
                rowKeyName  = "SOPInstanceUID";
                viewName    = "Images";

                matchingParamList.Add(imageInstance);
            }
            else if (string.Compare(originalRow.Table.TableName, DataTableHelper.SeriesTableName) == 0)
            {
                string         sSeriesInstanceUid = RegisteredDataRows.SeriesInfo.GetElementValue(originalRow, DicomTag.SeriesInstanceUID);
                ICatalogEntity seriesEntity       = RegisteredEntities.GetSeriesEntity(sSeriesInstanceUid);

                rowKeyValue = sSeriesInstanceUid;
                rowKeyName  = "SeriesInstanceUID";
                viewName    = "Series";

                matchingParamList.Add(seriesEntity);
            }
            else if (string.Compare(originalRow.Table.TableName, DataTableHelper.StudyTableName) == 0)
            {
                string         sStudyInstanceUid = RegisteredDataRows.StudyInfo.GetElementValue(originalRow, DicomTag.StudyInstanceUID);
                ICatalogEntity studyEntity       = RegisteredEntities.GetStudyEntity(sStudyInstanceUid);

                rowKeyValue = sStudyInstanceUid;
                rowKeyName  = "StudyInstanceUID";
                viewName    = "Studies";

                matchingParamList.Add(studyEntity);
            }
            else if (string.Compare(originalRow.Table.TableName, DataTableHelper.PatientTableName) == 0)
            {
                string         sPatientId    = RegisteredDataRows.PatientInfo.GetElementValue(originalRow, DicomTag.PatientID);
                ICatalogEntity patientEntity = RegisteredEntities.GetPatientEntity(sPatientId);

                rowKeyValue = sPatientId;
                rowKeyName  = "PatientId";
                viewName    = "Patients";

                matchingParamList.Add(patientEntity);
            }
            else
            {
                throw new ApplicationException("Row is not a valid DICOM format.");
            }

            return(matchingParamCollection);
        }
示例#5
0
        private ClientQueryDataSet.ImagesRow[] FillImages
        (
            ClientQueryDataSet.SeriesRow seriesRow,
            ClientQueryDataSet informationDS
        )
        {
            IStorageDataAccessAgent     storageDataAccess;
            MatchingParameterCollection matchingcollection;
            MatchingParameterList       matchingList;

            Leadtools.Medical.Storage.DataAccessLayer.MatchingParameters.Study  matchingStudy;
            Leadtools.Medical.Storage.DataAccessLayer.MatchingParameters.Series matchingSeries;
            List <ClientQueryDataSet.ImagesRow> imageRows;


            storageDataAccess = DataAccessServices.GetDataAccessService <IStorageDataAccessAgent> ( );

            if (null == storageDataAccess)
            {
                return(new ClientQueryDataSet.ImagesRow [] {});
            }

            matchingcollection = new MatchingParameterCollection( );
            matchingList       = new MatchingParameterList( );
            matchingStudy      = new Leadtools.Medical.Storage.DataAccessLayer.MatchingParameters.Study(seriesRow.StudyInstanceUID);
            matchingSeries     = new Leadtools.Medical.Storage.DataAccessLayer.MatchingParameters.Series(seriesRow.SeriesInstanceUID);

            matchingList.Add(matchingStudy);
            matchingList.Add(matchingSeries);
            matchingcollection.Add(matchingList);

            CompositeInstanceDataSet instances = storageDataAccess.QueryCompositeInstances(matchingcollection).ToCompositeInstanceDataSet();

            imageRows = new List <ClientQueryDataSet.ImagesRow> ( );

            foreach (CompositeInstanceDataSet.InstanceRow instance in instances.Instance)
            {
                ClientQueryDataSet.ImagesRow imageRow;


                imageRow = informationDS.Images.NewImagesRow( );

                imageRow.StudyInstanceUID  = seriesRow.StudyInstanceUID;
                imageRow.SeriesInstanceUID = seriesRow.SeriesInstanceUID;
                imageRow.SOPInstanceUID    = instance.SOPInstanceUID;
                imageRow.InstanceNumber    = instance.IsInstanceNumberNull( ) ? string.Empty : instance.InstanceNumber.ToString( );
                imageRow.SOPClassUID       = instance.IsSOPClassUIDNull( ) ? string.Empty : instance.SOPClassUID;

                informationDS.Images.AddImagesRow(imageRow);
                imageRows.Add(imageRow);

                __BurningImages.Add(imageRow);
            }

            return(imageRows.ToArray( ));
        }
示例#6
0
      private MatchingParameterCollection GetMatchingParameters(string sopInstanceUID)
      {
         MatchingParameterCollection matchingParamCollection = new MatchingParameterCollection();
         MatchingParameterList matchingParamList = new MatchingParameterList();
         // Instance instance = new Instance(sopInstanceUID);
         ICatalogEntity instance = RegisteredEntities.GetInstanceEntity(sopInstanceUID);

         matchingParamList.Add(instance);
         matchingParamCollection.Add(matchingParamList);
         return matchingParamCollection;
      }
 public ServerInformationControl()
 {
     InitializeComponent();
     _sqlDatabaseList = new Dictionary <string, string>();
     _mpc             = new MatchingParameterCollection();
     _mpc.Add(new MatchingParameterList());
     progressBar.Visible = false;
     _Sorter.Order       = System.Windows.Forms.SortOrder.Ascending;
     listViewModules.ListViewItemSorter = _Sorter;
     LoadModules();
 }
示例#8
0
        public static MWLDataset Find(this IWorklistDataAccessAgent accessAgent, params ICatalogEntity[] queries)
        {
            MatchingParameterCollection parameters = new MatchingParameterCollection();
            MatchingParameterList       matchList  = new MatchingParameterList();

            foreach (ICatalogEntity query in queries)
            {
                matchList.Add(query);
            }
            parameters.Add(matchList);
            return(accessAgent.FindPatientInformation(parameters));
        }
示例#9
0
        internal static string FindReferencedFile(
#if LEADTOOLS_V19_OR_LATER
            IExternalStoreDataAccessAgent externalStoreAgent,
#endif // #if LEADTOOLS_V19_OR_LATER
            string sopInstanceUID)
        {
            MatchingParameterCollection          mpc = new MatchingParameterCollection();
            MatchingParameterList                mpl = new MatchingParameterList();
            DataSet /*CompositeInstanceDataSet*/ instanceData;
            IStorageDataAccessAgent              agent = null;
            string referencedFile = string.Empty;

            if (DataAccessServices.IsDataAccessServiceRegistered <IStorageDataAccessAgent>())
            {
                agent = DataAccessServices.GetDataAccessService <IStorageDataAccessAgent>();
            }

            if (agent != null)
            {
                ICatalogEntity instanceEntity = RegisteredEntities.GetInstanceEntity(sopInstanceUID);
                mpl.Add(instanceEntity);
                mpc.Add(mpl);

                instanceData = agent.QueryCompositeInstances(mpc);
                if (instanceData.Tables[DataTableHelper.InstanceTableName].Rows.Count == 1)
                {
                    DataRow row = instanceData.Tables[DataTableHelper.InstanceTableName].Rows[0];
                    referencedFile = RegisteredDataRows.InstanceInfo.ReferencedFile(row);

#if (LEADTOOLS_V19_OR_LATER_MEDICAL_EXTERNAL_STORE) || (LEADTOOLS_V19_OR_LATER)
                    if (string.IsNullOrEmpty(referencedFile))
                    {
                        // If empty, it might be on the cloud
                        // Use DicomInstanceRetrieveExternalStoreCommand with cache set to true to copy it locally
                        if (externalStoreAgent == null)
                        {
                            if (DataAccessServices.IsDataAccessServiceRegistered <IExternalStoreDataAccessAgent>())
                            {
                                externalStoreAgent = DataAccessServices.GetDataAccessService <IExternalStoreDataAccessAgent>();
                            }
                        }

                        DicomInstanceRetrieveExternalStoreCommand c = new DicomInstanceRetrieveExternalStoreCommand(agent, externalStoreAgent, AddInsSession.ServiceDirectory, true);
                        DicomDataSet ds = c.GetDicomDataSet(row, out referencedFile);
                    }
#endif // (LEADTOOLS_V19_OR_LATER_MEDICAL_EXTERNAL_STORE) || (LEADTOOLS_V19_OR_LATER)
                }
            }
            return(referencedFile);
        }
示例#10
0
        private DataSet QueryCurrentPatient(string patientID)
        {
            MatchingParameterCollection matchingCollection;
            MatchingParameterList       matchingList;
            Patient patient;

            matchingCollection = new MatchingParameterCollection();
            matchingList       = new MatchingParameterList();
            patient            = new Patient(patientID);

            matchingList.Add(patient);
            matchingCollection.Add(matchingList);

            return(_DataAccessAgent.QueryCompositeInstances(matchingCollection));
        }
示例#11
0
        int Delete()
        {
            if (null == AuthorizedDataAccessAgent)
            {
                throw new ArgumentException();
            }

            int totalDeletedImagesCount = 0;

            MatchingParameterCollection matchingParamCollection;
            MatchingParameterList       matchingParamList;

            matchingParamCollection = new MatchingParameterCollection();
            matchingParamList       = new MatchingParameterList();

            matchingParamCollection.Add(matchingParamList);

            if (!string.IsNullOrEmpty(SOPInstanceUID))
            {
                Instance imageInstance = new Instance(SOPInstanceUID);

                matchingParamList.Add(imageInstance);
            }
            if (!string.IsNullOrEmpty(SeriesInstanceUID))
            {
                Series seriesEntity = new Series(SeriesInstanceUID);

                matchingParamList.Add(seriesEntity);
            }
            if (!string.IsNullOrEmpty(StudyInstanceUID))
            {
                Study studyEntity = new Study(StudyInstanceUID);

                matchingParamList.Add(studyEntity);
            }
            if (!string.IsNullOrEmpty(PatientID))
            {
                Patient patientEntity = new Patient(PatientID);

                matchingParamList.Add(patientEntity);
            }

            totalDeletedImagesCount = AuthorizedDataAccessAgent.DeleteInstance(matchingParamCollection, Owner, null);

            return(totalDeletedImagesCount);
        }
示例#12
0
        private DataSet QuerySeries(string[] instanceUIDs)
        {
            MatchingParameterCollection matchingCollection;
            MatchingParameterList       matchingList;

            matchingCollection = new MatchingParameterCollection();

            foreach (string instanceUID in instanceUIDs)
            {
                Series intance = new Series(instanceUID);

                matchingList = new MatchingParameterList();
                matchingList.Add(intance);
                matchingCollection.Add(matchingList);
            }

            return(_DataAccessAgent.QueryCompositeInstances(matchingCollection));
        }
示例#13
0
        private static string GetPatientName(MediaCreationManagement mediaObject)
        {
            string patientName;
            IStorageDataAccessAgent     dataAccess;
            MatchingParameterCollection matchingCollection;
            MatchingParameterList       matchingList;
            CompositeInstanceDataSet    compositeInstance;


            patientName        = string.Empty;
            dataAccess         = DataAccessServices.GetDataAccessService <IStorageDataAccessAgent> ( );
            matchingCollection = new MatchingParameterCollection( );
            matchingList       = new MatchingParameterList( );
            // Instance matchingInstance   = new Instance ( mediaObject.ReferencedSopSequence [ 0 ].SopInstance.ReferencedSopInstanceUid ) ;
            ICatalogEntity matchingInstance = RegisteredEntities.GetInstanceEntity(mediaObject.ReferencedSopSequence [0].SopInstance.ReferencedSopInstanceUid);

            if (null == dataAccess)
            {
                dataAccess = DataAccessFactory.GetInstance(new StorageDataAccessConfigurationView( )).CreateDataAccessAgent <IStorageDataAccessAgent> ( );
            }

            matchingCollection.Add(matchingList);
            matchingList.Add(matchingInstance);

            compositeInstance = dataAccess.QueryCompositeInstances(matchingCollection).ToCompositeInstanceDataSet();

            if (!string.IsNullOrEmpty(compositeInstance.Patient [0].FamilyName))
            {
                patientName += compositeInstance.Patient [0].FamilyName;
            }

            if (!string.IsNullOrEmpty(compositeInstance.Patient [0].GivenName))
            {
                if (!string.IsNullOrEmpty(patientName))
                {
                    patientName += ", ";
                }

                patientName += compositeInstance.Patient [0].GivenName;
            }

            return(patientName);
        }
示例#14
0
        private static DicomDataSet GetFirstReferencedInstanceDataSet
        (
            IStorageDataAccessAgent dataAccess,
            MediaCreationManagement mediaObject)
        {
            MatchingParameterCollection matchingCollection;
            MatchingParameterList       matchingList;
            CompositeInstanceDataSet    compositeInstance;


            matchingCollection = new MatchingParameterCollection( );
            matchingList       = new MatchingParameterList( );
            // Instance instance           = new Instance ( mediaObject.ReferencedSopSequence [ 0 ].SopInstance.ReferencedSopInstanceUid ) ;
            ICatalogEntity instance = RegisteredEntities.GetInstanceEntity(mediaObject.ReferencedSopSequence [0].SopInstance.ReferencedSopInstanceUid);


            matchingCollection.Add(matchingList);
            matchingList.Add(instance);

            compositeInstance = dataAccess.QueryCompositeInstances(matchingCollection).ToCompositeInstanceDataSet();

            if (compositeInstance.Instance.Count > 0)
            {
                DicomDataSet ds;


                ds = new DicomDataSet( );

                ds.Load(compositeInstance.Instance [0].ReferencedFile, DicomDataSetLoadFlags.None);

                return(ds);
            }
            else
            {
                return(null);
            }
        }
示例#15
0
        // This example is a test to build all queries
        public void MySampleQueries()
        {
            MatchingParameterCollection matchingParamCollection = new MatchingParameterCollection();
            MatchingParameterList       matchingParamList       = new MatchingParameterList();

            matchingParamCollection.Add(matchingParamList);

            StorageCatalog myCatalog = new StorageCatalog();
            Collection <CatalogElement[]> catalogElements = CatalogDescriptor.GetElementsCollection(matchingParamCollection, myCatalog, true);

            IDbCommand command = new SqlCommand();

            PreparePatientsQueryCommand(command, catalogElements, ExtraQueryOptions.Typical);
            PrepareStudiesQueryCommand(command, catalogElements, ExtraQueryOptions.Typical);
            PrepareSeriesQueryCommand(command, catalogElements, ExtraQueryOptions.Typical);
            PrepareInstanceQueryCommand(command, catalogElements, ExtraQueryOptions.Typical);

            PrepareDeletePatientsCommand(command, catalogElements, ExtraQueryOptions.Typical);
            PrepareDeleteStudiesCommand(command, catalogElements, ExtraQueryOptions.Typical);
            PrepareDeleteSeriesCommand(command, catalogElements, ExtraQueryOptions.Typical);
            PrepareDeleteInstanceCommand(command, catalogElements, ExtraQueryOptions.Typical);

            PrepareDeletePatientsNoChildStudiesCommand(command);
            PrepareDeleteStudiesNoChildSeriesCommand(command);
            PrepareDeleteSeriesNoChildInstancesCommand(command);

            DeletePatient(matchingParamCollection);
            DeleteStudy(matchingParamCollection);
            DeleteSeries(matchingParamCollection);
            DeleteInstance(matchingParamCollection);

            PrepareIsPatientExistsCommand(command, "1111");
            PrepareIsStudyExistsCommand(command, "2222");
            PrepareIsSeriesExistsCommand(command, "3333");
            PrepareIsInstanceExistsCommand(command, "4444");
        }
示例#16
0
        public void PrepareSearchDefault(MatchingParameterCollection matchingCollection)
        {
#if (LEADTOOLS_V19_OR_LATER)
            try
            {
                MatchingParameterList matchingList = new MatchingParameterList();
                HangingProtocolEntity hpe          = new HangingProtocolEntity();

                HangingProtocolDefinitonSequenceEntity hpdse = new HangingProtocolDefinitonSequenceEntity();

                matchingList.Add(hpe);
                matchingList.Add(hpdse);
                matchingCollection.Add(matchingList);

                DicomQueryHangingProtocolParams q = GetDicomQueryParams();

                hpe.Name        = q.Name;
                hpe.Description = q.Description;
                hpe.Level       = q.Level;
                hpe.Creator     = q.Creator;

                // Creation Date
                if (q.CreationDateFromChecked || q.CreationDateToChecked)
                {
                    DateRange studyDateRange = new DateRange();

                    if (q.CreationDateFromChecked)
                    {
                        studyDateRange.StartDate = q.CreationDateFrom;
                    }

                    if (q.CreationDateToChecked)
                    {
                        studyDateRange.EndDate = q.CreationDateTo;
                    }

                    hpe.CreationDateTime = studyDateRange;
                }

                hpe.NumberOfPriorsReferenced = q.Priors;

                // Hanging Protocol Definition
                if (!string.IsNullOrEmpty(q.Modalities))
                {
                    hpdse.Modality = q.Modalities.Replace(",", "\\");
                }

                hpdse.StudyDescription = q.StudyDescription;
                hpdse.Laterality       = q.Laterality;
                hpdse.BodyPartExamined = q.BodyPartExamined;
                hpdse.ProtocolName     = q.ProtocolName;


                // Anatomic Region Sequence
                if (!string.IsNullOrEmpty(q.AnatomicRegionCodeValue) || !string.IsNullOrEmpty(q.AnatomicRegionCodeMeaning))
                {
                    HangingProtocolAnatomicRegionSequenceEntity anatomicRegion = new HangingProtocolAnatomicRegionSequenceEntity();

                    matchingList.Add(anatomicRegion);

                    anatomicRegion.CodeValue   = q.AnatomicRegionCodeValue;
                    anatomicRegion.CodeMeaning = q.AnatomicRegionCodeMeaning;
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
#endif // #if (LEADTOOLS_V19_OR_LATER)
        }
示例#17
0
      public void RunThread(IForwardDataAccessAgent forwardAgent, IStorageDataAccessAgent storageAgent)
      {
         lock (cleanLock)
         {
            ForwardInstance[] instances = forwardAgent.GetCleanList();
            StorageAddInsConfiguration storageSettings = Module.StorageConfigManager.GetStorageAddInsSettings();
            string message = string.Format("[Forwarder] {0} {1} found to clean", instances.Length, instances.Length == 1 ? "dataset" : "datasets");
            DicomFileDeleter deleter = new DicomFileDeleter();
            MatchingParameterCollection mpc = new MatchingParameterCollection();

            deleter.DicomFileDeleted += new EventHandler<Leadtools.Medical.Winforms.EventBrokerArgs.DicomFileDeletedEventArgs>(deleter_DicomFileDeleted);
            deleter.DicomFileDeleteFailed += new EventHandler<Leadtools.Medical.Winforms.EventBrokerArgs.DicomFileDeletedEventArgs>(deleter_DicomFileDeleteFailed);
            if (storageSettings != null)
            {
               deleter.DeleteFilesOnDatabaseDelete = storageSettings.StoreAddIn.DeleteFiles;
               deleter.BackupFilesOnDatabaseDelete = storageSettings.StoreAddIn.BackupFilesOnDelete;
               deleter.BackupFilesOnDeleteFolder = storageSettings.StoreAddIn.DeleteBackupLocation;
            }

            Logger.Global.SystemMessage(LogType.Debug, message, _ServerAE);
            foreach (ForwardInstance instance in instances)
            {
#if LEADTOOLS_V18_OR_LATER
               if (_cancelClean)
               {
                  _cancelClean = false;
                  Logger.Global.SystemMessage(LogType.Information, string.Format("Cancelling Clean Process"), _ServerAE);
                  break;
               }
#endif // #if LEADTOOLS_V18_OR_LATER
               MatchingParameterList mpl = new MatchingParameterList();

               ICatalogEntity instanceEntity = RegisteredEntities.GetInstanceEntity(instance.SOPInstanceUID);
               mpl.Add(instanceEntity);
               mpc.Add(mpl);
               try
               {
                  DataSet ds = storageAgent.QueryCompositeInstances(mpc);

                  //
                  // Find the instance to delete
                  //
                  storageAgent.DeleteInstance(GetMatchingParameters(instance.SOPInstanceUID));
                  if (ds != null)
                  {                     
                     deleter.Delete(null, ds.Tables[DataTableHelper.InstanceTableName].Select());
                  }
               }
               catch (Exception e)
               {
                  message = string.Format("[Forwarder] Error ({0}) deleting instance: {1}", e.Message, instance.SOPInstanceUID);
                  Logger.Global.SystemMessage(LogType.Error, message, _ServerAE);
               }
               finally
               {
                  mpc.Clear();
               }
            }
            deleter.DicomFileDeleted -= deleter_DicomFileDeleted;
            deleter.DicomFileDeleteFailed -= deleter_DicomFileDeleteFailed;
         }
      }
        // To use a custom database schema with the Database Manager, you must define a custom MyPrepareSearch method
        // and assign it to the StorageDatabaseManager.PrepareSearch delegate. After doing this, the search fields in the Database Manager
        //will properly refine any database manager search.  The MyPrepareSearch() method gets the search fields specified in the database manager
        // by calling StorageDatabaseManager.GetDicomQueryParams().  This returns any query parameters specified.
        // The MyPrepareSearch() method then needs to create a MatchingParameterCollection that corresponds to the specified search.
        // Note that the database manager search fields correspond to items contained in the patient, study, and series tables only.
        // There are no search fields that correspond to the image table.
        // Therefore MyPrepareSearch() only needs to add MyPatient, MyStudy, and MySeries objects to the MatchingParameterList.
        // For more details, see the "Changing the LEAD Medical Storage Server to use a different database schema" tutorial.


        private void MyPrepareSearch(MatchingParameterCollection matchingCollection)
        {
            DicomQueryParams q = __DbManager.GetDicomQueryParams();

            try
            {
                MatchingParameterList matchingList = new MatchingParameterList();
                MyPatient             patient      = new MyPatient();
                MyStudy  study  = new MyStudy();
                MySeries series = new MySeries();

                matchingList.Add(patient);
                matchingList.Add(study);
                matchingList.Add(series);

                matchingCollection.Add(matchingList);
                study.StudyAccessionNumber    = q.AccessionNumber;
                patient.PatientIdentification = q.PatientId;

                if (!string.IsNullOrEmpty(q.PatientName.FamilyName))
                {
                    patient.PatientName = q.PatientName.FamilyName.TrimEnd('*') + "*";
                }

                if (!string.IsNullOrEmpty(q.PatientName.GivenName))
                {
                    patient.PatientName = q.PatientName.GivenName.TrimEnd('*') + "*";
                }

                if (!string.IsNullOrEmpty(q.Modalities))
                {
                    series.SeriesModality = q.Modalities.Replace(",", "\\");
                }
                ;

                if (!string.IsNullOrEmpty(q.SeriesDescription))
                {
                    series.SeriesSeriesDescription = q.SeriesDescription.TrimEnd('*') + "*";
                }

                if (!string.IsNullOrEmpty(q.ReferringPhysiciansName.FamilyName))
                {
                    study.StudyReferringPhysiciansName = q.ReferringPhysiciansName.FamilyName.TrimEnd('*') + "*";
                }
                ;

                if (!string.IsNullOrEmpty(q.ReferringPhysiciansName.GivenName))
                {
                    study.StudyReferringPhysiciansName = q.ReferringPhysiciansName.GivenName.TrimEnd('*') + "*";
                }
                ;

                if (q.StudyFromChecked || q.StudyToChecked)
                {
                    DateRange studyDateRange = new DateRange();

                    if (q.StudyFromChecked)
                    {
                        studyDateRange.StartDate = q.StudyFromDate;
                    }

                    if (q.StudyToChecked)
                    {
                        studyDateRange.EndDate = q.StudyToDate;
                    }

                    study.StudyStudyDate = studyDateRange;
                }

                if (q.StorageDateChecked)
                {
                    MyInstance      instance  = new MyInstance();
                    DateRange       dateRange = new DateRange();
                    DateRangeFilter StorageDateRangeFilter = q.StorageDateRange;
                    string          startDate = StorageDateRangeFilter.DateRangeFrom;
                    string          endDate   = StorageDateRangeFilter.DateRangeTo;

                    if (StorageDateRangeFilter.SelectedDateFilter == DateRangeFilter.RangeFilterType.DateRange)
                    {
                        if (!string.IsNullOrEmpty(startDate))
                        {
                            dateRange.StartDate = DateTime.Parse(startDate);
                        }

                        if (!string.IsNullOrEmpty(endDate))
                        {
                            dateRange.EndDate = DateTime.Parse(endDate);
                        }
                    }
                    else if (StorageDateRangeFilter.SelectedDateFilter == DateRangeFilter.RangeFilterType.Months)
                    {
                        DateTime lastMonthsDate = DateTime.Now.SubtractMonths(Convert.ToInt32(StorageDateRangeFilter.LastMonths));

                        dateRange.StartDate = lastMonthsDate;
                        dateRange.EndDate   = DateTime.Now;
                    }
                    else
                    {
                        TimeSpan subtractionDays = new TimeSpan(Convert.ToInt32(StorageDateRangeFilter.LastDays),
                                                                DateTime.Now.Hour,
                                                                DateTime.Now.Minute,
                                                                DateTime.Now.Second,
                                                                DateTime.Now.Millisecond);

                        dateRange.StartDate = DateTime.Now.Subtract(subtractionDays);
                        dateRange.EndDate   = DateTime.Now;
                    }

                    instance.ImageLastStoreDate = dateRange;
                    matchingList.Add(instance);
                }

                study.StudyStudyId = q.StudyId;
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                // do nothing ;
            }
        }
        protected override void OnDoWork(DoWorkEventArgs e)
        {
            int count = 0;
            int imagesToExportCount   = 0;
            InstanceCStoreCommand cmd = null;

            MatchingParameterCollection matchingParamCollection;
            MatchingParameterList       matchingParamList;

            if (this.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            ExportDicomWorkerArgs args = e.Argument as ExportDicomWorkerArgs;

            if (args == null)
            {
                throw new ArgumentException("Invalid ExportDicom argument");
            }

            if (args.CreateDicomDir)
            {
                DicomDirectory = new DicomDir(args.OutputFolder);
            }

            if (args.Anonymize)
            {
                Anonymizer.BeginBatch();
            }

            try
            {
                ViewGenerator.ViewDataRow[] exportRows = (args.Rows);

                imagesToExportCount = exportRows.Length;

                foreach (ViewGenerator.ViewDataRow exportRow in exportRows)
                {
                    try
                    {
                        string rowKeyValue;
                        string rowKeyName;
                        string viewName;

                        if (this.CancellationPending)
                        {
                            e.Cancel = true;

                            return;
                        }

                        DataRow originalRow = exportRow.OriginalRow;
                        matchingParamCollection = new MatchingParameterCollection( );
                        matchingParamList       = new MatchingParameterList( );

                        matchingParamCollection.Add(matchingParamList);

                        if (string.Compare(originalRow.Table.TableName, DataTableHelper.InstanceTableName) == 0)
                        {
                            string         sSopInstanceUid = RegisteredDataRows.InstanceInfo.GetElementValue(originalRow, DicomTag.SOPInstanceUID);
                            ICatalogEntity imageInstance   = RegisteredEntities.GetInstanceEntity(sSopInstanceUid);

                            rowKeyValue = sSopInstanceUid;
                            rowKeyName  = "SOPInstanceUID";
                            viewName    = "Images";

                            matchingParamList.Add(imageInstance);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.SeriesTableName) == 0)
                        {
                            string         sSeriesInstanceUid = RegisteredDataRows.SeriesInfo.GetElementValue(originalRow, DicomTag.SeriesInstanceUID);
                            ICatalogEntity seriesEntity       = RegisteredEntities.GetSeriesEntity(sSeriesInstanceUid);

                            rowKeyValue = sSeriesInstanceUid;
                            rowKeyName  = "SeriesInstanceUID";
                            viewName    = "Series";

                            matchingParamList.Add(seriesEntity);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.StudyTableName) == 0)
                        {
                            string         sStudyInstanceUid = RegisteredDataRows.StudyInfo.GetElementValue(originalRow, DicomTag.StudyInstanceUID);
                            ICatalogEntity studyEntity       = RegisteredEntities.GetStudyEntity(sStudyInstanceUid);

                            rowKeyValue = sStudyInstanceUid;
                            rowKeyName  = "StudyInstanceUID";
                            viewName    = "Studies";

                            matchingParamList.Add(studyEntity);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.PatientTableName) == 0)
                        {
                            string         sPatientId    = RegisteredDataRows.PatientInfo.GetElementValue(originalRow, DicomTag.PatientID);
                            ICatalogEntity patientEntity = RegisteredEntities.GetPatientEntity(sPatientId);

                            rowKeyValue = sPatientId;
                            rowKeyName  = "PatientId";
                            viewName    = "Patients";

                            matchingParamList.Add(patientEntity);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.HangingProtocolTableName) == 0)
                        {
                            string         sSopInstanceUid         = RegisteredDataRows.InstanceInfo.GetElementValue(originalRow, DicomTag.SOPInstanceUID);
                            ICatalogEntity hangingProtocolInstance = RegisteredEntities.GetHangingProtocolEntity(sSopInstanceUid);

                            rowKeyValue = sSopInstanceUid;
                            rowKeyName  = "SOPInstanceUID";
                            viewName    = "Hanging Protocol";

                            matchingParamList.Add(hangingProtocolInstance);
                        }
                        else
                        {
                            throw new ApplicationException("Deleted row is not a valid DICOM format.");
                        }

                        DataSet   exportDataSet = null;
                        DataRow[] rows          = null;

                        if (string.Compare(originalRow.Table.TableName, DataTableHelper.HangingProtocolTableName) == 0 && _dataAccessAgent3 != null)
                        {
                            exportDataSet = _dataAccessAgent3.QueryHangingProtocol(matchingParamCollection);
                            rows          = exportDataSet.Tables[DataTableHelper.HangingProtocolTableName].Select();
                        }
                        else
                        {
                            exportDataSet = _dataAccessAgent.QueryCompositeInstances(matchingParamCollection);
                            rows          = exportDataSet.Tables[DataTableHelper.InstanceTableName].Select();
                        }

                        foreach (DataRow row in rows)
                        {
                            DicomDataSet dicomDataSet = RegisteredDataRows.InstanceInfo.LoadDicomDataSet(row);

                            if (args.Anonymize)
                            {
                                Anonymizer.Anonymize(dicomDataSet);
                            }

                            AddDicomBackgroundWorker.StoreClientSessionProxy proxy = new AddDicomBackgroundWorker.StoreClientSessionProxy();
                            proxy.AffectedSOPInstance = dicomDataSet.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty);
                            proxy.AbstractClass       = dicomDataSet.GetValue <string>(DicomTag.SOPClassUID, string.Empty);


                            try
                            {
                                cmd = new InstanceCStoreCommand(proxy, dicomDataSet, _dataAccessAgent);

                                OnStoreCommandCreated(this, new StoreCommandEventArgs(cmd));

                                cmd.Configuration.DataSetStorageLocation = args.OutputFolder;
#if (LEADTOOLS_V19_OR_LATER)
                                cmd.Configuration.HangingProtocolLocation = args.OutputFolder;
#endif

                                string fileLocation = CStoreCommand.GetStorageFullPath(cmd.Configuration, dicomDataSet);
                                if (args.Overwrite || !File.Exists(fileLocation))
                                {
                                    // Only exporting, so do not validate SopInstance and do not add to database
                                    cmd.DoValidateSopInstance      = false;
                                    cmd.DoUpdateDatabase           = false;
                                    cmd.DoUseExternalStoreSettings = false;
                                    cmd.DataSetStored += cmd_DataSetStored;

                                    cmd.Execute();
                                }
                                else
                                {
                                    // File already exists -- it is not overwritten
                                    DataSetStoredEventArgs storedArgs = new DataSetStoredEventArgs(dicomDataSet, string.Empty, string.Empty, fileLocation);
                                    cmd_DataSetStored(this, storedArgs);
                                }
                            }
                            finally
                            {
                                if (cmd != null)
                                {
                                    cmd.DataSetStored -= cmd_DataSetStored;
                                }
                            }
                        }

                        count++;

                        ExportDicomWorkerProgressState state = new ExportDicomWorkerProgressState( );

                        state.Error               = null;
                        state.CurrentCount        = count;
                        state.ExportRow           = exportRow;
                        state.ExportedImagesCount = 1;
                        state.TotalCount          = imagesToExportCount;
                        state.RowKeyValue         = rowKeyValue;
                        state.RowKeyName          = rowKeyName;
                        state.ViewName            = viewName;

                        ReportProgress((count * 100) / exportRows.Length, state);
                    }
                    catch (Exception exception)
                    {
                        ExportDicomWorkerProgressState state = new ExportDicomWorkerProgressState( );

                        count++;

                        state.Error               = exception;
                        state.CurrentCount        = count;
                        state.ExportRow           = exportRow;
                        state.TotalCount          = imagesToExportCount;
                        state.ExportedImagesCount = 0;

                        ReportProgress((count * 100) / exportRows.Length, state);
                    }
                }
            }
            finally
            {
                e.Result = imagesToExportCount;
                if (DicomDirectory != null)
                {
                    DicomDirectory.Save();
                    DicomDirectory = null;
                }

                if (Anonymizer != null)
                {
                    Anonymizer.EndBatch();
                    Anonymizer = null;
                }
            }
        }
        protected override void OnDoWork(DoWorkEventArgs e)
        {
            int count;
            int totalDeletedImagesCount;

            ViewGenerator.ViewDataRow [] deleteRows;


            count = 0;
            totalDeletedImagesCount = 0;

            try
            {
                MatchingParameterCollection matchingParamCollection;
                MatchingParameterList       matchingParamList;


                if (this.CancellationPending)
                {
                    e.Cancel = true;

                    return;
                }

                if (!(e.Argument is ViewGenerator.ViewDataRow []))
                {
                    throw new ArgumentException("Invalid RemoveDicom argument");
                }

                deleteRows = (e.Argument as ViewGenerator.ViewDataRow []);

                foreach (ViewGenerator.ViewDataRow deletedRow in deleteRows)
                {
                    try
                    {
                        DataRow originalRow;
                        int     deletedImagesCount;
                        string  rowKeyValue;
                        string  rowKeyName;
                        string  viewName;


                        if (this.CancellationPending)
                        {
                            e.Cancel = true;

                            return;
                        }

                        originalRow             = deletedRow.OriginalRow;
                        matchingParamCollection = new MatchingParameterCollection( );
                        matchingParamList       = new MatchingParameterList( );

                        matchingParamCollection.Add(matchingParamList);

                        // if ( originalRow is CompositeInstanceDataSet.InstanceRow )
                        if (string.Compare(originalRow.Table.TableName, DataTableHelper.InstanceTableName) == 0)
                        {
                            // imageInstance = new Instance( ( ( CompositeInstanceDataSet.InstanceRow ) originalRow ).SOPInstanceUID ) ;
                            string         sSopInstanceUid = RegisteredDataRows.InstanceInfo.GetElementValue(originalRow, DicomTag.SOPInstanceUID);
                            ICatalogEntity imageInstance   = RegisteredEntities.GetInstanceEntity(sSopInstanceUid);


                            rowKeyValue = sSopInstanceUid;
                            rowKeyName  = "SOPInstanceUID";
                            viewName    = "Images";

                            matchingParamList.Add(imageInstance);
                        }
                        // else if ( originalRow is CompositeInstanceDataSet.SeriesRow )
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.SeriesTableName) == 0)
                        {
                            // ICatalogEntity seriesEntity ;


                            // seriesEntity = new Series ( ( ( CompositeInstanceDataSet.SeriesRow ) originalRow ).SeriesInstanceUID ) ;
                            string         sSeriesInstanceUid = RegisteredDataRows.SeriesInfo.GetElementValue(originalRow, DicomTag.SeriesInstanceUID);
                            ICatalogEntity seriesEntity       = RegisteredEntities.GetSeriesEntity(sSeriesInstanceUid);
                            // seriesEntity = new Series ( ( ( CompositeInstanceDataSet.SeriesRow ) originalRow ).SeriesInstanceUID ) ;


                            rowKeyValue = sSeriesInstanceUid;
                            rowKeyName  = "SeriesInstanceUID";
                            viewName    = "Series";

                            matchingParamList.Add(seriesEntity);
                        }
                        // else if ( originalRow is CompositeInstanceDataSet.StudyRow )
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.StudyTableName) == 0)
                        {
                            // Study studyEntity = new Study ( ( ( CompositeInstanceDataSet.StudyRow ) originalRow ).StudyInstanceUID ) ;
                            string         sStudyInstanceUid = RegisteredDataRows.StudyInfo.GetElementValue(originalRow, DicomTag.StudyInstanceUID);
                            ICatalogEntity studyEntity       = RegisteredEntities.GetStudyEntity(sStudyInstanceUid);

                            rowKeyValue = sStudyInstanceUid;
                            rowKeyName  = "StudyInstanceUID";
                            viewName    = "Studies";

                            matchingParamList.Add(studyEntity);
                        }
                        // else if ( originalRow is CompositeInstanceDataSet.PatientRow )
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.PatientTableName) == 0)
                        {
                            // Patient patientEntity = new Patient ( ( ( CompositeInstanceDataSet.PatientRow ) originalRow ).PatientID ) ;
                            string         sPatientId    = RegisteredDataRows.PatientInfo.GetElementValue(originalRow, DicomTag.PatientID);
                            ICatalogEntity patientEntity = RegisteredEntities.GetPatientEntity(sPatientId);

                            rowKeyValue = sPatientId;
                            rowKeyName  = "PatientId";
                            viewName    = "Patients";

                            matchingParamList.Add(patientEntity);
                        }
#if (LEADTOOLS_V19_OR_LATER)
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.HangingProtocolTableName) == 0)
                        {
                            string         sSopInstanceUid         = RegisteredDataRows.InstanceInfo.GetElementValue(originalRow, DicomTag.SOPInstanceUID);
                            ICatalogEntity hangingProtocolInstance = RegisteredEntities.GetHangingProtocolEntity(sSopInstanceUid);


                            rowKeyValue = sSopInstanceUid;
                            rowKeyName  = "SOPInstanceUID";
                            viewName    = "Hanging Protocol";

                            matchingParamList.Add(hangingProtocolInstance);
                        }
#endif
                        else
                        {
                            throw new ApplicationException("Deleted row is not a valid DICOM format.");
                        }

#if (LEADTOOLS_V19_OR_LATER)
                        if (string.Compare(originalRow.Table.TableName, DataTableHelper.HangingProtocolTableName) == 0 && _dataAccessAgent3 != null)
                        {
                            deletedImagesCount = _dataAccessAgent3.DeleteHangingProtocol(matchingParamCollection);
                        }
                        else
                        {
                            deletedImagesCount = _dataAccessAgent.DeleteInstance(matchingParamCollection);
                        }
#else
                        deletedImagesCount = _dataAccessAgent.DeleteInstance(matchingParamCollection);
#endif

                        count++;

                        RemoveDiconWorkerProgressState state;


                        state = new RemoveDiconWorkerProgressState( );

                        totalDeletedImagesCount += deletedImagesCount;

                        state.Error              = null;
                        state.CurrentCount       = count;
                        state.DeletedRow         = deletedRow;
                        state.RemovedImagesCount = deletedImagesCount;
                        state.TotalCount         = totalDeletedImagesCount;
                        state.RowKeyValue        = rowKeyValue;
                        state.RowKeyName         = rowKeyName;
                        state.ViewName           = viewName;

                        ReportProgress((count * 100) / deleteRows.Length, state);
                    }
                    catch (Exception exception)
                    {
                        RemoveDiconWorkerProgressState state;


                        state = new RemoveDiconWorkerProgressState( );

                        count++;

                        state.Error              = exception;
                        state.CurrentCount       = count;
                        state.DeletedRow         = deletedRow;
                        state.TotalCount         = totalDeletedImagesCount;
                        state.RemovedImagesCount = 0;

                        ReportProgress((count * 100) / deleteRows.Length, state);
                    }
                }
            }
            finally
            {
                e.Result = totalDeletedImagesCount;
            }
        }
示例#21
0
        public void Run(IExternalStoreDataAccessAgent externalStoreAgent, IStorageDataAccessAgent storageAgent, int expirationDays)
        {
            DicomUtilities.DebugString(DebugStringOptions.ShowCounter, "CleanProcess.Run");
            lock (cleanLock)
            {
                ExternalStoreInstance[] instances = externalStoreAgent.GetClearList(expirationDays);
                // StorageAddInsConfiguration storageSettings = Module.StorageConfigManager.GetStorageAddInsSettings();

                if (instances.Length > 0)
                {
                    string message = string.Format("{0} {1} found to clear", instances.Length, "local dataset(s)");
                    Logger.Global.SystemMessage(LogType.Information, message, _serviceName);

                    DicomFileDeleter            deleter = new DicomFileDeleter();
                    MatchingParameterCollection mpc     = new MatchingParameterCollection();

                    deleter.DicomFileDeleted      += new EventHandler <Leadtools.Medical.Winforms.EventBrokerArgs.DicomFileDeletedEventArgs>(deleter_DicomFileDeleted);
                    deleter.DicomFileDeleteFailed += new EventHandler <Leadtools.Medical.Winforms.EventBrokerArgs.DicomFileDeletedEventArgs>(deleter_DicomFileDeleteFailed);
                    if (_storageSettings != null)
                    {
                        deleter.DeleteFilesOnDatabaseDelete = _storageSettings.StoreAddIn.DeleteFiles;
                        deleter.BackupFilesOnDatabaseDelete = _storageSettings.StoreAddIn.BackupFilesOnDelete;
                        deleter.BackupFilesOnDeleteFolder   = _storageSettings.StoreAddIn.DeleteBackupLocation;

                        deleter.DeleteAnnotationsOnImageDelete      = false;
                        deleter.DeleteReferencedImagesOnImageDelete = false;
                    }

                    foreach (ExternalStoreInstance instance in instances)
                    {
                        MatchingParameterList mpl = new MatchingParameterList();

                        ICatalogEntity instanceEntity = RegisteredEntities.GetInstanceEntity(instance.SOPInstanceUID);
                        mpl.Add(instanceEntity);
                        mpc.Add(mpl);
                        try
                        {
                            DataSet ds = storageAgent.QueryCompositeInstances(mpc);

                            //
                            // Find the instance to delete
                            ////
                            deleter.Delete(null, ds.Tables[DataTableHelper.InstanceTableName].Select());

                            externalStoreAgent.SetReferencedFile(instance.SOPInstanceUID, string.Empty);
                        }
                        catch (Exception e)
                        {
                            message = string.Format("Error ({0}) deleting instance: {1}", e.Message, instance.SOPInstanceUID);
                            Logger.Global.SystemMessage(LogType.Error, message, _serviceName);
                        }
                        finally
                        {
                            mpc.Clear();
                        }
                    }
                    deleter.DicomFileDeleted      -= deleter_DicomFileDeleted;
                    deleter.DicomFileDeleteFailed -= deleter_DicomFileDeleteFailed;
                }
            }
        }
示例#22
0
        public void Execute( )
        {
            try
            {
                ILoggingDataAccessAgent2 loggingDataAccess;
                DicomEventLogDataSet     eventLogDS;

                if (!DataAccessServices.IsDataAccessServiceRegistered <ILoggingDataAccessAgent2> ( ))
                {
                    throw new InvalidOperationException("Logging Data Access is not registered.");
                }
                else
                {
                    loggingDataAccess = DataAccessServices.GetDataAccessService <ILoggingDataAccessAgent2> ( );
                }

                MatchingParameterCollection           matchingCollection = new MatchingParameterCollection( );
                MatchingParameterList                 matchingList       = new MatchingParameterList( );
                DICOMServerEventLogMatchingParameters eventLogMatching   = new DICOMServerEventLogMatchingParameters( );

                eventLogMatching.EventDateTime.EndDate = DateTime.Now.Subtract(new TimeSpan(0, 1, 0));

                matchingList.Add(eventLogMatching);
                matchingCollection.Add(matchingList);

                string directoryPath = Path.Combine(LoggingState.AutoSaveDirectory, DateTime.Now.ToShortDateString( ).Replace('/', '-'));
                string filePath;

                Directory.CreateDirectory(directoryPath);

                WriteLog("Begin Auto Save Log", LogType.Debug);

                int  batchSize  = 10000;
                long totalSaved = 0;

                eventLogDS = loggingDataAccess.QueryDicomEventLogDataset(matchingCollection, new OrderByParametersList( ), batchSize, true);

                if (eventLogDS.DICOMServerEventLog.Count > 0)
                {
                    string indexFile = Path.Combine(directoryPath, "index");

                    indexFile = Path.ChangeExtension(indexFile, ".xml");

                    using (FileStream indexfs = new FileStream(indexFile, FileMode.Create, FileAccess.Write))
                    {
                        XmlDocument document = new XmlDocument( );

                        XmlElement rootElement = document.CreateElement("logs");

                        document.AppendChild(rootElement);

                        while (eventLogDS.DICOMServerEventLog.Count != 0)
                        {
                            filePath = Path.Combine(directoryPath, eventLogDS.DICOMServerEventLog [0].EventID.ToString( ));

                            filePath = Path.ChangeExtension(filePath, "txt");

                            using (FileStream fleStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                            {
                                using (StreamWriter streamWriter = new StreamWriter(fleStream))
                                {
                                    EventLogWriter.WriteEventLog("", eventLogDS, streamWriter, new DICOMServerEventLogFormsFormatter( ), true, directoryPath);

                                    XmlElement   element            = document.CreateElement("logFile");
                                    XmlAttribute fileAttribute      = document.CreateAttribute("file");
                                    XmlAttribute dateStartAttribute = document.CreateAttribute("dateStart");
                                    XmlAttribute dateEndfAttribute  = document.CreateAttribute("dateEnd");

                                    fileAttribute.Value      = filePath;
                                    dateStartAttribute.Value = eventLogDS.DICOMServerEventLog [0].EventDateTime.ToString( );
                                    dateEndfAttribute.Value  = eventLogDS.DICOMServerEventLog [eventLogDS.DICOMServerEventLog.Count - 1].EventDateTime.ToString( );

                                    element.Attributes.Append(fileAttribute);
                                    element.Attributes.Append(dateStartAttribute);
                                    element.Attributes.Append(dateEndfAttribute);

                                    rootElement.AppendChild(element);

                                    totalSaved += eventLogDS.DICOMServerEventLog.Count;

                                    if (LoggingState.DeleteSavedLog)
                                    {
                                        //if failed to delete for any reason lets continue
                                        try
                                        {
                                            loggingDataAccess.DeleteDicomEventLog(matchingCollection, batchSize);
                                        }
                                        catch (Exception exception)
                                        {
                                            Logger.Global.Log(string.Empty, string.Empty, 0, string.Empty, string.Empty, 0, Leadtools.Dicom.DicomCommandType.Undefined, DateTime.Now, LogType.Error, MessageDirection.None,
                                                              "Auto Save Log failed to delete logs. " + exception.Message, null, null);
                                        }
                                    }
                                }
                            }

                            eventLogDS = loggingDataAccess.QueryDicomEventLogDataset(matchingCollection, new OrderByParametersList( ), batchSize, true);
                        }

                        document.Save(indexfs);
                    }

                    WriteLog("Exporting log to file: " + indexFile, LogType.Debug);
                }

                WriteLog("End Auto Save Log. " + totalSaved.ToString( ) + " log(s) saved.", LogType.Debug);
            }
            catch (Exception exception)
            {
                Logger.Global.Log(string.Empty, string.Empty, 0, string.Empty, string.Empty, 0, Leadtools.Dicom.DicomCommandType.Undefined, DateTime.Now, LogType.Error, MessageDirection.None,
                                  "Auto Save Log failed. " + exception.Message, null, null);
            }
        }
示例#23
0
        public void PrepareSearchDefault(MatchingParameterCollection matchingCollection)
        {
            try
            {
                // matchingCollection = new MatchingParameterCollection ( ) ;
                MatchingParameterList matchingList = new MatchingParameterList();
                Patient patient = new Patient();
                Study   study   = new Study();
                Series  series  = new Series();


                matchingList.Add(patient);
                matchingList.Add(study);
                matchingList.Add(series);

                matchingCollection.Add(matchingList);

                DicomQueryParams q = GetDicomQueryParams();
                study.AccessionNumber = q.AccessionNumber;// txtAccessionNumber.Text ;
                patient.PatientID     = q.PatientId;

                if (!string.IsNullOrEmpty(q.PatientName.FamilyName))
                {
                    patient.FamilyName = q.PatientName.FamilyName.TrimEnd('*') + "*";
                }

                if (!string.IsNullOrEmpty(q.PatientName.GivenName))
                {
                    patient.GivenName = q.PatientName.GivenName.TrimEnd('*') + "*";
                }

                if (!string.IsNullOrEmpty(q.Modalities))
                {
                    series.Modality = q.Modalities.Replace(",", "\\");
                }

                if (!string.IsNullOrEmpty(q.SeriesDescription))
                {
                    series.SeriesDescription = q.SeriesDescription.TrimEnd('*') + "*";
                }

                if (!string.IsNullOrEmpty(q.ReferringPhysiciansName.FamilyName))
                {
                    study.ReferDrFamilyName = q.ReferringPhysiciansName.FamilyName.TrimEnd('*') + "*";
                }
                ;

                if (!string.IsNullOrEmpty(q.ReferringPhysiciansName.GivenName))
                {
                    study.ReferDrGivenName = q.ReferringPhysiciansName.GivenName.TrimEnd('*') + "*";
                }
                ;

                if (q.StudyFromChecked || q.StudyToChecked)
                {
                    DateRange studyDateRange;


                    studyDateRange = new DateRange();

                    if (q.StudyFromChecked)
                    {
                        studyDateRange.StartDate = q.StudyFromDate;
                    }

                    if (q.StudyToChecked)
                    {
                        studyDateRange.EndDate = q.StudyToDate;
                    }

                    study.StudyDate = studyDateRange;
                }

                Instance instance = null;
                if (StorageDateCheckBox.Checked)
                {
                    DateRange dateRange;
                    string    startDate;
                    string    endDate;


                    instance  = new Instance();
                    dateRange = new DateRange();
                    startDate = StorageDateRangeFilter.DateRangeFrom;
                    endDate   = StorageDateRangeFilter.DateRangeTo;

                    if (StorageDateRangeFilter.SelectedDateFilter == DateRangeFilter.RangeFilterType.DateRange)
                    {
                        if (!string.IsNullOrEmpty(startDate))
                        {
                            dateRange.StartDate = DateTime.Parse(startDate);
                        }

                        if (!string.IsNullOrEmpty(endDate))
                        {
                            dateRange.EndDate = DateTime.Parse(endDate);
                        }
                    }
                    else if (StorageDateRangeFilter.SelectedDateFilter == DateRangeFilter.RangeFilterType.Months)
                    {
                        DateTime lastMonthsDate;


                        lastMonthsDate = SubtractMonths(DateTime.Now,
                                                        Convert.ToInt32(StorageDateRangeFilter.LastMonths));

                        dateRange.StartDate = lastMonthsDate;
                        dateRange.EndDate   = DateTime.Now;
                    }
                    else
                    {
                        TimeSpan subtractionDays;

                        subtractionDays = new TimeSpan(Convert.ToInt32(StorageDateRangeFilter.LastDays),
                                                       DateTime.Now.Hour,
                                                       DateTime.Now.Minute,
                                                       DateTime.Now.Second,
                                                       DateTime.Now.Millisecond);

                        dateRange.StartDate = DateTime.Now.Subtract(subtractionDays);
                        dateRange.EndDate   = DateTime.Now;
                    }

                    instance.ReceiveDate = dateRange;

                    matchingList.Add(instance);
                }

                if (!string.IsNullOrEmpty(q.RetrieveAeTitle) || !string.IsNullOrEmpty(q.StoreAeTitle))
                {
                    if (instance == null)
                    {
                        instance = new Instance();
                        matchingList.Add(instance);
                    }
                    instance.RetrieveAETitle = q.RetrieveAeTitle;
                    instance.StoreAETitle    = q.StoreAeTitle;
                }

                study.StudyID = q.StudyId;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
示例#24
0
        public void RunThread(IExternalStoreDataAccessAgent externalStoreAgent, IStorageDataAccessAgent storageAgent, DateRange range)
        {
            DicomUtilities.DebugString(DebugStringOptions.ShowCounter, "RestoreProcess.Run");

            lock (_restoreLock)
            {
                ExternalStoreInstance[] instances = externalStoreAgent.GetRestoreList(range);
                string message = string.Format("{0} {1} found to restore", instances.Length, "dataset(s)");
                MatchingParameterCollection mpc = new MatchingParameterCollection();

                Logger.Global.SystemMessage(LogType.Information, message, _serviceName);

                CStoreCommandConfiguration storeConfig = new CStoreCommandConfiguration();
                storeConfig.DicomFileExtension = _storageAddinsConfiguration.StoreAddIn.StoreFileExtension;
                FillStoreCommandDefaultSettings(storeConfig, _storageAddinsConfiguration);

                foreach (ExternalStoreInstance instance in instances)
                {
                    if (_cancelRestore)
                    {
                        _cancelRestore = false;
                        Logger.Global.SystemMessage(LogType.Information, "Cancelling Restore Process", _serviceName);
                        break;
                    }

                    MatchingParameterList mpl = new MatchingParameterList();

                    ICatalogEntity instanceEntity = RegisteredEntities.GetInstanceEntity(instance.SOPInstanceUID);
                    mpl.Add(instanceEntity);
                    mpc.Add(mpl);
                    try
                    {
                        DataSet ds = storageAgent.QueryCompositeInstances(mpc);

                        DataRow[] rows = ds.Tables[DataTableHelper.InstanceTableName].Select();
                        foreach (DataRow row in rows)
                        {
                            // Get the ICrud that the file was originally stored with
                            ICrud crud = DataAccessServiceLocator.Retrieve <ICrud>(instance.ExternalStoreGuid);
                            if (crud != null)
                            {
                                DicomDataSet dicomDataSet = null;
                                Exception    ex           = crud.RetrieveDicom(row, DicomDataSetLoadFlags.None, out dicomDataSet);
                                if (ex == null)
                                {
                                    string storageLocation   = CStoreCommand.GetStorageLocation(storeConfig, dicomDataSet);
                                    string dicomInstancePath = Path.Combine(storageLocation,
                                                                            instance.SOPInstanceUID) + "." + storeConfig.DicomFileExtension;

                                    ex = crud.RetrieveFile(row, dicomInstancePath);
                                    if (ex != null)
                                    {
                                        throw ex;
                                    }

                                    externalStoreAgent.SetReferencedFile(instance.SOPInstanceUID, dicomInstancePath);
                                    Logger.Global.SystemMessage(LogType.Information, string.Format("File Restored: {0} ", dicomInstancePath), _serviceName);
                                }
                            }
                            else
                            {
                                Logger.Global.SystemMessage(LogType.Information, string.Format("Error:  File Not Restored -- Store Token: {0}.  The Addin that for ExternalStoreGuid '{1}' cannot be found.", instance.StoreToken, instance.ExternalStoreGuid), _serviceName);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        message = string.Format("Error ({0}) restoring instance: {1}", e.Message, instance.SOPInstanceUID);
                        Logger.Global.SystemMessage(LogType.Error, message, _serviceName);
                    }
                    finally
                    {
                        mpc.Clear();
                    }
                }
            }
        }
示例#25
0
        // Returns a DataSet that reflects the existence of PatientID, StudyInstanceUID, SeriesInstanceUID, and SOPInstanceUID
        // * If the patient does not exist, returns an empty DataSet
        // * If patient exists but no study returns a DataSet where MyPatientTable has row with PatientID of DicomDataSet
        // * If patient exists, study exists but no series, returns a DataSet that has PatientID (MyPatientTable), and StudyInstanceUID (MyStudyTable)
        // * If patient, study, series exist but no Instance, returns a DataSet with PatientID, StudyInstanceUID, and SeriesInstanceUID
        // * If patinet, study series, instance exist, returns empty dataset
        private DataSet GetUpdateDataSet
        (
            DicomDataSet ds,
            bool updateExistentPatient,
            bool updateExistentStudy,
            bool updateExistentSeries,
            bool updateExistentInstances
        )
        {
            MatchingParameterCollection matchingEntitiesCollection = new MatchingParameterCollection();
            MatchingParameterList       matchingEntitiesList       = new MatchingParameterList();

            matchingEntitiesCollection.Add(matchingEntitiesList);

            MyInstance instance = new MyInstance();

            instance.SOPInstanceUID = ds.MyGetStringValue(DicomTag.SOPInstanceUID);

            bool instanceExists = IsCompositeInstancesExists(instance.SOPInstanceUID);

            if (instanceExists)
            {
                matchingEntitiesList.Add(instance);

                DeleteInstance(matchingEntitiesCollection);

                matchingEntitiesList.Remove(instance);

                instanceExists = false;
            }


            MyPatient patient = new MyPatient();

            patient.PatientIdentification = ds.MyGetStringValue(DicomTag.PatientID);

            if (null != patient.PatientIdentification)
            {
                matchingEntitiesList.Add(patient);
            }

            bool patientExist = IsPatientsExists(patient.PatientIdentification);

            if (updateExistentPatient && patientExist)
            {
                // case #1
                return(QueryCompositeInstances(matchingEntitiesCollection));
            }
            else if (!patientExist)
            {
                // case #2
                return(new MyDataSet());
            }
            else
            {
                // case #3
                // (!updateExistentPatient) && (patientExist)
                // int ? patientId = GetIntValue(patient.PatientIdentification);

                MyStudy study = new MyStudy();
                study.StudyStudyInstanceUID = ds.MyGetStringValue(DicomTag.StudyInstanceUID);

                if (null != study.StudyStudyInstanceUID)
                {
                    matchingEntitiesList.Add(study);
                }

                bool studyExists = IsStudyExists(study.StudyStudyInstanceUID);

                if (updateExistentStudy && studyExists)
                {
                    return(QueryCompositeInstances(matchingEntitiesCollection));
                }
                else if (!studyExists)
                {
                    if (matchingEntitiesList.Contains(study))
                    {
                        matchingEntitiesList.Remove(study);
                    }

                    return(QueryPatients(matchingEntitiesCollection));
                }
                else
                {
                    MySeries series = new MySeries();

                    series.SeriesSeriesInstanceUID = ds.MyGetStringValue(DicomTag.SeriesInstanceUID);

                    if (!string.IsNullOrEmpty(series.SeriesSeriesInstanceUID))
                    {
                        matchingEntitiesList.Add(series);
                    }

                    bool seriesExists = IsSeriesExists(series.SeriesSeriesInstanceUID);

                    if (updateExistentSeries && seriesExists)
                    {
                        return(QueryCompositeInstances(matchingEntitiesCollection));
                    }
                    else if (!seriesExists)
                    {
                        if (matchingEntitiesList.Contains(series))
                        {
                            matchingEntitiesList.Remove(series);
                        }

                        return(QueryStudies(matchingEntitiesCollection));
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(instance.SOPInstanceUID))
                        {
                            matchingEntitiesList.Add(instance);
                        }

                        if (updateExistentInstances && instanceExists)
                        {
                            return(QueryCompositeInstances(matchingEntitiesCollection));
                        }
                        else
                        {
                            MyDataSet.MyPatientTableRow patientRow;
                            MyDataSet.MyStudyTableRow   studyRow;
                            MyDataSet.MySeriesTableRow  seriesRow;

                            MyDataSet myDataSet = new MyDataSet();
                            myDataSet.EnforceConstraints = false;
                            myDataSet.MyPatientTable.BeginLoadData();
                            myDataSet.MyStudyTable.BeginLoadData();
                            myDataSet.MySeriesTable.BeginLoadData();
                            myDataSet.MyInstanceTable.BeginLoadData();

                            patientRow = myDataSet.MyPatientTable.AddMyPatientTableRow(patient.PatientIdentification,
                                                                                       string.Empty,
                                                                                       DateTime.MinValue,
                                                                                       string.Empty,
                                                                                       string.Empty);

                            //if (patientId != null)
                            //{
                            //   patientRow.PatientId = patientId.Value;
                            //}

                            //dicomDataSet.MyPatientTable.Rows[0]["PatientId"] = patientId;

                            studyRow = myDataSet.MyStudyTable.AddMyStudyTableRow(patientRow,
                                                                                 study.StudyStudyInstanceUID,
                                                                                 DateTime.MinValue,
                                                                                 string.Empty,
                                                                                 string.Empty,
                                                                                 string.Empty,
                                                                                 string.Empty);

                            seriesRow = myDataSet.MySeriesTable.AddMySeriesTableRow(
                                studyRow,
                                series.SeriesSeriesInstanceUID,
                                string.Empty,
                                0,
                                string.Empty,
                                DateTime.MinValue,
                                string.Empty);

                            //1. if updateInstance and instance exist not valid (will be in the above IF
                            //2. if updateInstance and instance NOT exist don't fill from Db
                            //3. if NOT updateInstance and instance exist then insert SOP Instance UID
                            //4. if NOT updateInstnace and NOT instance exist then don't fill from Db

                            //case 3 above
                            if (instanceExists)
                            {
                                myDataSet.MyInstanceTable.AddMyInstanceTableRow(seriesRow,
                                                                                instance.SOPInstanceUID,
                                                                                0,
                                                                                DateTime.MinValue,
                                                                                string.Empty,
                                                                                string.Empty,
                                                                                0,
                                                                                0,
                                                                                0);
                            }

                            myDataSet.AcceptChanges();

                            myDataSet.MyPatientTable.EndLoadData();
                            myDataSet.MyStudyTable.EndLoadData();
                            myDataSet.MySeriesTable.EndLoadData();
                            myDataSet.MyInstanceTable.EndLoadData();
                            myDataSet.EnforceConstraints = true;
                            return(myDataSet);
                        }
                    }
                }
            }
        }
示例#26
0
        private static CompositeInstanceDataSet.InstanceRow[] GetInstanceRows(int action, DicomDataSet request, out List <string> studyInstanceUids)
        {
            CompositeInstanceDataSet.InstanceRow[] rows = null;
            CompositeInstanceDataSet    ds  = null;
            MatchingParameterCollection mpc = new MatchingParameterCollection();
            MatchingParameterList       mpl = new MatchingParameterList();

            studyInstanceUids = new List <string>();

            if (request == null)
            {
                return(null);
            }

            if (Module.StorageAgent == null)
            {
                return(null);
            }

            switch (action)
            {
            case PatientUpdaterConstants.Action.MergePatient:
                MergePatient mergePatient = request.Get <MergePatient>();
                if (mergePatient.PatientToMerge != null && mergePatient.PatientToMerge.Count > 0)
                {
                    mpl.Add(new Patient()
                    {
                        PatientID = mergePatient.PatientToMerge[0].PatientId
                    });
                    mpc.Add(mpl);
                }
                break;

            case PatientUpdaterConstants.Action.DeletePatient:
                DeletePatient delPatient = request.Get <DeletePatient>();

                mpl.Add(new Patient()
                {
                    PatientID = delPatient.PatientId
                });
                foreach (StudyInstanceReference studyInstanceReference in delPatient.ReferencedStudySequence)
                {
                    mpl.Add(new Study()
                    {
                        StudyInstanceUID = studyInstanceReference.StudyInstanceUID
                    });
                }
                mpc.Add(mpl);
                break;

            case PatientUpdaterConstants.Action.DeleteSeries:
                DeleteSeries delSeries = request.Get <DeleteSeries>();

                mpl.Add(new Series()
                {
                    SeriesInstanceUID = delSeries.SeriesInstanceUID
                });
                mpc.Add(mpl);
                break;

            case PatientUpdaterConstants.Action.ChangePatient:
                ChangePatient changePatient = request.Get <ChangePatient>();
                mpl.Add(new Patient()
                {
                    PatientID = changePatient.OriginalPatientId
                });
                mpc.Add(mpl);
                break;

            default:
                return(null);
            }

            ds = Module.StorageAgent.QueryCompositeInstances(mpc).ToCompositeInstanceDataSet();

            CompositeInstanceDataSet.StudyRow[] studyRows = ds.Study.Rows.OfType <CompositeInstanceDataSet.StudyRow>().ToArray();
            foreach (CompositeInstanceDataSet.StudyRow studyRow in studyRows)
            {
                studyInstanceUids.Add(studyRow.StudyInstanceUID);
            }

            rows = ds.Instance.Rows.OfType <CompositeInstanceDataSet.InstanceRow>().ToArray();

            return(rows);
        }
示例#27
0
        private void SendCopy(AutoCopyItem item)
        {
            AeInfoExtended[] aes   = _aeManagementAgent.GetRelatedAeTitles(item.SourceAE, Module.AUTOCOPY_RELATION);
            StoreScu         store = new StoreScu();

            Module.InitializeDicomSecurity(false);
            StoreScu storeSecure = null;

            DicomOpenSslVersion dicomOpenSslVersion = DicomNet.GetOpenSslVersion();

            if (dicomOpenSslVersion.IsAvailable)
            {
                storeSecure = new StoreScu(Module._Server.TemporaryDirectory, DicomNetSecurityMode.Tls, Module._openSslOptions);
                Module.SetCiphers(storeSecure);
            }

            DicomScp scp = null;

            string[] sopInstances = item.Datasets.ToArray();

            if (aes == null || aes.Length == 0)
            {
                return;
            }

            string clientAe = Module.Options.UseCustomAE ? Module.Options.AutoCopyAE : item.ClientAE;

            AddEventHandlers(store, clientAe);
            AddEventHandlers(storeSecure, clientAe);

            foreach (AeInfoExtended ae in aes)
            {
#if LEADTOOLS_V20_OR_LATER
                // Update dbo.AeInfo.LastAccessDate to Date.Now
                ae.LastAccessDate = DateTime.Now;
                _aeManagementAgent.Update(ae.AETitle, ae);
#endif

                bool useTls = ae.ClientPortUsage == ClientPortUsageType.Secure || ((ae.ClientPortUsage == ClientPortUsageType.SameAsServer) && (Module._Server.Secure));
                useTls = (useTls && dicomOpenSslVersion.IsAvailable);

                foreach (string sopInstance in sopInstances)
                {
                    MatchingParameterCollection mpc = new MatchingParameterCollection();
                    MatchingParameterList       mpl = new MatchingParameterList();

                    ICatalogEntity instanceEntity = RegisteredEntities.GetInstanceEntity(sopInstance);
                    mpl.Add(instanceEntity);
                    mpc.Add(mpl);

                    DataSet instanceData = _StorageAgent.QueryCompositeInstances(mpc);
                    // if (instanceData.Instance.Rows.Count == 1)
                    if (instanceData.Tables[DataTableHelper.InstanceTableName].Rows.Count == 1)
                    {
                        // string file = instanceData.Instance[0].ReferencedFile;
                        DataRow instanceRow = instanceData.Tables[DataTableHelper.InstanceTableName].Rows[0];
                        string  file        = RegisteredDataRows.InstanceInfo.ReferencedFile(instanceRow);

                        scp = new DicomScp(IPAddress.Parse(ae.Address), ae.AETitle, ae.Port);
                        try
                        {
                            if (useTls)
                            {
                                storeSecure.Store(scp, file);
                            }
                            else
                            {
                                store.Store(scp, file);
                            }
                        }
                        catch (ClientAssociationException ce)
                        {
                            string message = string.Format("[Auto Copy] Failed to establish association with server: {0}.", ce.Reason);

                            LogEvent(LogType.Error, MessageDirection.None, message, DicomCommandType.Undefined, null, store, null);
                        }
                        catch (DicomException de)
                        {
                            string message = string.Format("[Auto Copy] Error: {0}.", de.Message);

                            LogEvent(LogType.Error, MessageDirection.Input, message, DicomCommandType.Undefined, null, store, null);
                        }
                        catch (Exception e)
                        {
                            string message = "[Auto Copy] " + e.Message;

                            Logger.Global.Log(string.Empty, string.Empty, -1, string.Empty, string.Empty, -1, DicomCommandType.Undefined,
                                              DateTime.Now, LogType.Error, MessageDirection.None, message, null, null);
                        }
                    }
                }
            }

            RemoveEventHandlers(store);
            RemoveEventHandlers(storeSecure);

            foreach (string sopInstance in sopInstances)
            {
                item.Datasets.Remove(sopInstance);
            }
        }
示例#28
0
        string GetPatientIdFromStorage()
        {
            try
            {
                if (null == DataAccessAgent)
                {
                    return("");
                }

                MatchingParameterCollection matchingParamCollection;
                MatchingParameterList       matchingParamList;

                matchingParamCollection = new MatchingParameterCollection();
                matchingParamList       = new MatchingParameterList();
                matchingParamCollection.Add(matchingParamList);

                {
                    ReverseDicomDatasetAdapter dataSetReader = new ReverseDicomDatasetAdapter()
                    {
                        query = DataSet
                    };

                    string PatientID         = dataSetReader.PatientID;
                    string StudyInstanceUID  = dataSetReader.StudyInstanceUID;
                    string SeriesInstanceUID = dataSetReader.SeriesInstanceUID;
                    string SOPInstanceUID    = dataSetReader.SOPInstanceUID;

                    if (!string.IsNullOrEmpty(SOPInstanceUID))
                    {
                        Instance imageInstance = new Instance(SOPInstanceUID);

                        matchingParamList.Add(imageInstance);
                    }
                    if (!string.IsNullOrEmpty(SeriesInstanceUID))
                    {
                        Leadtools.Medical.Storage.DataAccessLayer.MatchingParameters.Series seriesEntity = new Leadtools.Medical.Storage.DataAccessLayer.MatchingParameters.Series(SeriesInstanceUID);

                        matchingParamList.Add(seriesEntity);
                    }
                    if (!string.IsNullOrEmpty(StudyInstanceUID))
                    {
                        Leadtools.Medical.Storage.DataAccessLayer.MatchingParameters.Study studyEntity = new Leadtools.Medical.Storage.DataAccessLayer.MatchingParameters.Study(StudyInstanceUID);

                        matchingParamList.Add(studyEntity);
                    }
                    if (!string.IsNullOrEmpty(PatientID))
                    {
                        Leadtools.Medical.Storage.DataAccessLayer.MatchingParameters.Patient patientEntity = new Leadtools.Medical.Storage.DataAccessLayer.MatchingParameters.Patient(PatientID);

                        matchingParamList.Add(patientEntity);
                    }
                }

                DataSet result = DataAccessAgent.QueryPatients(matchingParamCollection);
                if (null != result)
                {
                    if (result.Tables[DataTableHelper.PatientTableName].Rows.Count > 0)
                    {
                        // return result.Patient[0].PatientID;
                        IPatientInfo patientInfo = RegisteredDataRows.PatientInfo;
                        DataRow      patientRow  = result.Tables[DataTableHelper.PatientTableName].Rows[0];
                        string       sPatientId  = patientInfo.GetElementValue(patientRow, DicomTag.PatientID);

                        return((string)result.Tables[DataTableHelper.PatientTableName].Rows[0]["PatientId"]);
                    }
                }

                return("");
            }
            catch (System.Exception)
            {
                System.Diagnostics.Debug.Assert(false);
                return("");
            }
        }