Example #1
0
        public void OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
        {
            if (_type == TestTypes.SendMR)
            {
                var testSet = new DicomAttributeCollection();

                _test.SetupMR(testSet);

                bool same = testSet.Equals(message.DataSet);


                string studyId = message.DataSet[DicomTags.StudyId].GetString(0, "");
                Assert.AreEqual(studyId, "1933");


                DicomUid sopInstanceUid;
                bool     ok = message.DataSet[DicomTags.SopInstanceUid].TryGetUid(0, out sopInstanceUid);
                if (!ok)
                {
                    server.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified);
                    return;
                }

                server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID, DicomStatuses.Success);
            }
            else if (_type == TestTypes.Receive)
            {
                DicomUid sopInstanceUid;
                bool     ok = message.DataSet[DicomTags.SopInstanceUid].TryGetUid(0, out sopInstanceUid);
                if (!ok)
                {
                    server.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.InvalidPDUParameter);
                    return;
                }

                MessagesReceived.Add(message);

                server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID, DicomStatuses.Success);
            }
            else
            {
                Platform.Log(LogLevel.Error, "Unexpected test type mode");
                server.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.InvalidPDUParameter);
            }
        }
        public bool CompleteStream(DicomServer server, ServerAssociationParameters assoc, byte presentationId, DicomMessage message)
        {
            DicomProcessingResult result;

            try
            {
                if (_fileStream != null)
                {
                    _fileStream.Flush(true);
                    _fileStream.Close();
                    _fileStream.Dispose();
                    _fileStream = null;
                }

                ISopInstanceImporter importer = IoC.Get <ISopInstanceImporter>();
                importer.Context = _importContext;

                result = importer.ImportFile(message, _sourceFilename);

                if (result.Successful)
                {
                    if (!String.IsNullOrEmpty(result.AccessionNumber))
                    {
                        Platform.Log(LogLevel.Info, "Received SOP Instance {0} from {1} to {2} (A#:{3} StudyUid:{4})",
                                     result.SopInstanceUid, assoc.CallingAE, assoc.CalledAE, result.AccessionNumber,
                                     result.StudyInstanceUid);
                    }
                    else
                    {
                        Platform.Log(LogLevel.Info, "Received SOP Instance {0} from {1} to {2} (StudyUid:{3})",
                                     result.SopInstanceUid, assoc.CallingAE, assoc.CalledAE,
                                     result.StudyInstanceUid);
                    }
                }
            }
            catch (Exception e)
            {
                result = new DicomProcessingResult {
                    DicomStatus = DicomStatuses.ProcessingFailure, ErrorMessage = e.Message
                };
            }

            if (!result.Successful)
            {
                Platform.Log(LogLevel.Warn, "Failure importing sop: {0}", result.ErrorMessage);
            }

            CleanupDirectory();

            server.SendCStoreResponse(presentationId, message.MessageId, message.AffectedSopInstanceUid, result.DicomStatus);
            return(true);
        }
Example #3
0
        public override bool OnReceiveRequest(DicomServer server, ServerAssociationParameters association,
                                              byte presentationId, DicomMessage message)
        {
            try
            {
                SopInstanceImporterContext context = new SopInstanceImporterContext(
                    String.Format("{0}_{1}", association.CallingAE, association.TimeStamp.ToString("yyyyMMddhhmmss")),
                    association.CallingAE, Partition.AeTitle);

                DicomProcessingResult result   = new DicomProcessingResult();
                ISopInstanceImporter  importer = IoC.Get <ISopInstanceImporter>();
                if (importer != null)
                {
                    importer.Context = context;
                    result           = importer.Import(message);
                }

                if (result.Successful)
                {
                    if (!String.IsNullOrEmpty(result.AccessionNumber))
                    {
                        Log.Logger.Info("Received SOP Instance {0} from {1} to {2} (A#:{3} StudyUid:{4})",
                                        result.SopInstanceUid, association.CallingAE, association.CalledAE, result.AccessionNumber,
                                        result.StudyInstanceUid);
                    }
                    else
                    {
                        Log.Logger.Info("Received SOP Instance {0} from {1} to {2} (StudyUid:{3})",
                                        result.SopInstanceUid, association.CallingAE, association.CalledAE,
                                        result.StudyInstanceUid);
                    }
                }
                else
                {
                    Log.Logger.Warn("Failure importing sop: {0}", result.ErrorMessage);
                }

                server.SendCStoreResponse(presentationId, message.MessageId,
                                          message.AffectedSopInstanceUid, result.DicomStatus);
                return(true);
            }
            catch (DicomDataException ex)
            {
                Log.Logger.Error(ex, "Error when import {0}", message.AffectedSopInstanceUid);
                return(false);  // caller will abort the association
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex, "Error when import {0}", message.AffectedSopInstanceUid);
                return(false);  // caller will abort the association
            }
        }
Example #4
0
        public override bool OnReceiveRequest(DicomServer server, ServerAssociationParameters association, byte presentationId, DicomMessage message)
        {
            try
            {
                var context = new SopInstanceImporterContext(
                    String.Format("{0}_{1}", association.CallingAE, association.TimeStamp.ToString("yyyyMMddhhmmss")),
                    association.CallingAE, association.CalledAE);

                if (Device != null && Device.DeviceTypeEnum.Equals(DeviceTypeEnum.PrimaryPacs))
                {
                    context.DuplicateProcessing = DuplicateProcessingEnum.OverwriteSopAndUpdateDatabase;
                }

                var importer = new SopInstanceImporter(context);
                DicomProcessingResult result = importer.Import(message);

                if (result.Successful)
                {
                    if (!String.IsNullOrEmpty(result.AccessionNumber))
                    {
                        Platform.Log(LogLevel.Info, "Received SOP Instance {0} from {1} to {2} (A#:{3} StudyUid:{4})",
                                     result.SopInstanceUid, association.CallingAE, association.CalledAE, result.AccessionNumber,
                                     result.StudyInstanceUid);
                    }
                    else
                    {
                        Platform.Log(LogLevel.Info, "Received SOP Instance {0} from {1} to {2} (StudyUid:{3})",
                                     result.SopInstanceUid, association.CallingAE, association.CalledAE,
                                     result.StudyInstanceUid);
                    }
                }
                else
                {
                    Platform.Log(LogLevel.Warn, "Failure importing sop: {0}", result.ErrorMessage);
                }

                server.SendCStoreResponse(presentationId, message.MessageId, message.AffectedSopInstanceUid, result.DicomStatus);
                return(true);
            }
            catch (DicomDataException ex)
            {
                Platform.Log(LogLevel.Error, ex);
                return(false);  // caller will abort the association
            }
            catch (Exception ex)
            {
                Platform.Log(LogLevel.Error, ex);
                return(false);  // caller will abort the association
            }
        }
Example #5
0
        public override bool OnReceiveRequest(DicomServer server,
                                              ServerAssociationParameters association,
                                              byte presentationID, DicomMessage message)
        {
            try
            {
                server.SendCStoreResponse(presentationID, message.MessageId,
                                          message.AffectedSopInstanceUid, DicomStatuses.Success);
            }
            catch (DicomDataException ex)
            {
                LogAdapter.Logger.TraceException(ex);
                return(false); // caller will abort the association
            }
            catch (Exception ex)
            {
                LogAdapter.Logger.TraceException(ex);
                return(false); // caller will abort the association
            }

            return(true);
        }
Example #6
0
        void IDicomServerHandler.OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
        {
            if (message.CommandField == DicomCommandField.CEchoRequest)
            {
                server.SendCEchoResponse(presentationID, message.MessageId, DicomStatuses.Success);
                return;
            }

            String   studyInstanceUid  = null;
            String   seriesInstanceUid = null;
            DicomUid sopInstanceUid;
            String   patientName = null;

            bool ok = message.DataSet[DicomTags.SopInstanceUid].TryGetUid(0, out sopInstanceUid);

            if (ok)
            {
                ok = message.DataSet[DicomTags.SeriesInstanceUid].TryGetString(0, out seriesInstanceUid);
            }
            if (ok)
            {
                ok = message.DataSet[DicomTags.StudyInstanceUid].TryGetString(0, out studyInstanceUid);
            }
            if (ok)
            {
                ok = message.DataSet[DicomTags.PatientsName].TryGetString(0, out patientName);
            }

            if (!ok)
            {
                Platform.Log(LogLevel.Error, "Unable to retrieve UIDs from request message, sending failure status.");

                server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID,
                                          DicomStatuses.ProcessingFailure);
                return;
            }
            TransferSyntax syntax = association.GetPresentationContext(presentationID).AcceptedTransferSyntax;

            if (List)
            {
                Platform.Log(LogLevel.Info, message.Dump());
            }

            if (Bitbucket)
            {
                Platform.Log(LogLevel.Info, "Received SOP Instance: {0} for patient {1} in syntax {2}", sopInstanceUid,
                             patientName, syntax.Name);

                server.SendCStoreResponse(presentationID, message.MessageId,
                                          sopInstanceUid.UID,
                                          DicomStatuses.Success);
                return;
            }

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

            var path = new StringBuilder();

            path.AppendFormat("{0}{1}{2}{3}{4}", StorageLocation, Path.DirectorySeparatorChar,
                              studyInstanceUid, Path.DirectorySeparatorChar, seriesInstanceUid);

            Directory.CreateDirectory(path.ToString());

            path.AppendFormat("{0}{1}.dcm", Path.DirectorySeparatorChar, sopInstanceUid.UID);

            var dicomFile = new DicomFile(message, path.ToString())
            {
                TransferSyntaxUid            = syntax.UidString,
                MediaStorageSopInstanceUid   = sopInstanceUid.UID,
                ImplementationClassUid       = DicomImplementation.ClassUID.UID,
                ImplementationVersionName    = DicomImplementation.Version,
                SourceApplicationEntityTitle = association.CallingAE,
                MediaStorageSopClassUid      = message.SopClass.Uid
            };


            dicomFile.Save(DicomWriteOptions.None);

            Platform.Log(LogLevel.Info, "Received SOP Instance: {0} for patient {1} in syntax {2}", sopInstanceUid,
                         patientName, syntax.Name);

            server.SendCStoreResponse(presentationID, message.MessageId,
                                      sopInstanceUid.UID,
                                      DicomStatuses.Success);
        }
Example #7
0
    /// <summary>
    /// Process C-Echo and C-Store request.
    /// </summary>
    /// <param name="server"></param>
    /// <param name="association"></param>
    /// <param name="presentationID"></param>
    /// <param name="message"></param>
    void IDicomServerHandler.OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
    {
        if (message.CommandField == DicomCommandField.CEchoRequest)
        {
            server.SendCEchoResponse(presentationID, message.MessageId, DicomStatuses.Success);
            return;
        }
        else if (message.CommandField != DicomCommandField.CStoreRequest)
        {
            server.SendCEchoResponse(presentationID, message.MessageId, DicomStatuses.UnrecognizedOperation);
            return;
        }
        else if (message.CommandField == DicomCommandField.CStoreRequest)
        {
            Platform.Log(LogLevel.Info, message.DataSet.DumpString);

            ClearCanvas.Common.Platform.Log(LogLevel.Info, "C-Store request for {0}.", message.MessageId);
            String   studyInstanceUid  = null;
            String   seriesInstanceUid = null;
            DicomUid sopInstanceUid;
            String   patientName = null;

            bool ok = message.DataSet[DicomTags.SopInstanceUid].TryGetUid(0, out sopInstanceUid);
            if (ok)
            {
                ok = message.DataSet[DicomTags.SeriesInstanceUid].TryGetString(0, out seriesInstanceUid);
            }
            if (ok)
            {
                ok = message.DataSet[DicomTags.StudyInstanceUid].TryGetString(0, out studyInstanceUid);
            }
            if (ok)
            {
                ok = message.DataSet[DicomTags.PatientsName].TryGetString(0, out patientName);
            }

            //if (!ok)
            //{

            //    server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID, DicomStatuses.ProcessingFailure);
            //    return;
            //}

            try
            {
                // You can save the file by using this
                _storePath = ADCM.GetStoreString();
                if (string.IsNullOrEmpty(_storePath))
                {
                    throw new Exception("No store path provided");
                }
                string studyfolder = Path.Combine(_storePath, studyInstanceUid);
                studyfolder = Path.Combine(studyfolder, seriesInstanceUid);

                if (!Directory.Exists(studyfolder))
                {
                    Directory.CreateDirectory(studyfolder);
                }
                string    filename = Path.Combine(studyfolder, message.DataSet[DicomTags.SopInstanceUid].ToString() + ".dcm");
                DicomFile file     = new DicomFile(message, filename);
                file.Save(filename, DicomWriteOptions.Default);
                ClearCanvas.Common.Platform.Log(ClearCanvas.Common.LogLevel.Info, "Sending C-Store success response.");
                server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID, DicomStatuses.Success);
            }
            catch (Exception ex)
            {
                ClearCanvas.Common.Platform.Log(LogLevel.Error, ex, "Unable to store request {0}.", message.MessageId);

                server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid != null ? sopInstanceUid.UID : string.Empty, DicomStatuses.ProcessingFailure);
            }
        }
    }
Example #8
0
        void IDicomServerHandler.OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
        {
            if (message.CommandField == DicomCommandField.CEchoRequest)
            {
                server.SendCEchoResponse(presentationID, message.MessageId, DicomStatuses.Success);
                return;
            }

            String   studyInstanceUid  = null;
            String   seriesInstanceUid = null;
            DicomUid sopInstanceUid;

            bool ok = message.DataSet[DicomTags.SopInstanceUid].TryGetUid(0, out sopInstanceUid);

            if (ok)
            {
                ok = message.DataSet[DicomTags.SeriesInstanceUid].TryGetString(0, out seriesInstanceUid);
            }
            if (ok)
            {
                ok = message.DataSet[DicomTags.StudyInstanceUid].TryGetString(0, out studyInstanceUid);
            }

            if (!ok)
            {
                Logger.LogError("Unable to retrieve UIDs from request message, sending failure status.");

                server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID,
                                          DicomStatuses.ProcessingFailure);
                return;
            }

            if (!Directory.Exists(StorageScp.StorageLocation))
            {
                Directory.CreateDirectory(StorageScp.StorageLocation);
            }

            StringBuilder path = new StringBuilder();

            path.AppendFormat("{0}{1}{2}{3}{4}", StorageScp.StorageLocation, Path.DirectorySeparatorChar,
                              studyInstanceUid, Path.DirectorySeparatorChar, seriesInstanceUid);

            Directory.CreateDirectory(path.ToString());

            path.AppendFormat("{0}{1}.dcm", Path.DirectorySeparatorChar, sopInstanceUid.UID);

            DicomFile dicomFile = new DicomFile(message, path.ToString());

            dicomFile.TransferSyntaxUid            = TransferSyntax.ExplicitVrLittleEndianUid;
            dicomFile.MediaStorageSopInstanceUid   = sopInstanceUid.UID;
            dicomFile.ImplementationClassUid       = DicomImplementation.ClassUID.UID;
            dicomFile.ImplementationVersionName    = DicomImplementation.Version;
            dicomFile.SourceApplicationEntityTitle = association.CallingAE;
            dicomFile.MediaStorageSopClassUid      = message.SopClass.Uid;

            dicomFile.Save(DicomWriteOptions.None);

            String patientName = dicomFile.DataSet[DicomTags.PatientsName].GetString(0, "");

            Logger.LogInfo("Received SOP Instance: {0} for patient {1}", sopInstanceUid, patientName);

            server.SendCStoreResponse(presentationID, message.MessageId,
                                      sopInstanceUid.UID,
                                      DicomStatuses.Success);
        }
        /// <summary>
        /// Handle an incoming request
        /// </summary>
        /// <param name="server"></param>
        /// <param name="association"></param>
        /// <param name="presentationID"></param>
        /// <param name="message"></param>
        void IDicomServerHandler.OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
        {
            log.Info("Message received ... ");

            try
            {
                log.Info(
                    string.Format("Request recieved with command field {0} from ae {1}",
                                  message.CommandField,
                                  message.CommandSet[DicomTags.SourceApplicationEntityTitle].ToString()));

                if (message.CommandField == DicomCommandField.CEchoRequest)
                {
                    server.SendCEchoResponse(presentationID, message.MessageId, DicomStatuses.Success);
                    return;
                }

                String   studyInstanceUid  = null;
                String   seriesInstanceUid = null;
                DicomUid sopInstanceUid    = null;
                DicomUid sopClassUid       = null;
                String   patientName       = null;

                bool ok = message.DataSet[DicomTags.SopInstanceUid].TryGetUid(0, out sopInstanceUid);
                if (ok)
                {
                    ok = message.DataSet[DicomTags.SeriesInstanceUid].TryGetString(0, out seriesInstanceUid);
                }
                if (ok)
                {
                    ok = message.DataSet[DicomTags.StudyInstanceUid].TryGetString(0, out studyInstanceUid);
                }
                if (ok)
                {
                    ok = message.DataSet[DicomTags.PatientsName].TryGetString(0, out patientName);
                }
                if (ok)
                {
                    ok = message.DataSet[DicomTags.SopClassUid].TryGetUid(0, out sopClassUid);
                }

                if (!ok)
                {
                    log.Info("Unable to retrieve UIDs from request message, sending failure status.");

                    server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID,
                                              DicomStatuses.ProcessingFailure);
                    return;
                }

                TransferSyntax syntax = association.GetPresentationContext(presentationID).AcceptedTransferSyntax;

                if (!CacheManager.StorageSpaceAvailable(message, Configuration.Root, Configuration.MaxDiskPercentage))
                {
                    log.Error("Insufficient space to store.");

                    server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID,
                                              DicomStatuses.StorageStorageOutOfResources);
                    return;
                }

                log.Info("Adding to cache");
                CacheManager.AddToCache(
                    Configuration,
                    association,
                    message,
                    syntax,
                    studyInstanceUid,
                    seriesInstanceUid,
                    sopInstanceUid.UID,
                    patientName);

                log.Info(string.Format("Received SOP Instance: {0} for patient {1} in syntax {2}", sopInstanceUid,
                                       patientName, syntax.Name));

                server.SendCStoreResponse(presentationID, message.MessageId,
                                          sopInstanceUid.UID,
                                          DicomStatuses.Success);
            }
            catch (Exception ex)
            {
                server.SendCStoreResponse(presentationID, message.MessageId, message.AffectedSopInstanceUid,
                                          DicomStatuses.ProcessingFailure);
                log.Error("Exception thrown " + ex.ToString());
            }
        }
Example #10
0
        public override bool OnReceiveRequest(DicomServer server, ServerAssociationParameters association, byte presentationId, DicomMessage message)
        {
            Platform.Log(LogLevel.Info, "Received request,the message is {0}!!!", message.CommandField);
            //The following part is added for some devices won't contain the SpecificCharacterSet DicomTag.
            //The may introduce troubles when decoding the characters.
            //If there's SpecificCharacterSet DicomTag in the image, do nothing
            //If there's no SpecificCharacterSet DicomTag in the image, the configured DefaultSCS for the device will be added.
            //If there's no SpecificCharacterSet DicomTag in the image and no configured DefaultSCS, ISO_IR 100 will be used.
            if (string.IsNullOrEmpty(message.DataSet.SpecificCharacterSet))
            {
                if (string.IsNullOrEmpty(Device.DefaultSCS))
                {
                    sDefaultSCS = "ISO_IR 100";
                }
                else
                {
                    sDefaultSCS = Device.DefaultSCS;
                }

                message.DataSet[DicomTags.SpecificCharacterSet].SetStringValue(sDefaultSCS);
                message.DataSet.SpecificCharacterSet = sDefaultSCS;
            }
            try
            {
                var context = new SopInstanceImporterContext(
                    String.Format("{0}_{1}", association.CallingAE, association.TimeStamp.ToString("yyyyMMddhhmmss")),
                    association.CallingAE, association.CalledAE);

                if (Device != null && Device.DeviceTypeEnum.Equals(DeviceTypeEnum.PrimaryPacs))
                {
                    context.DuplicateProcessing = DuplicateProcessingEnum.OverwriteSopAndUpdateDatabase;
                }
                var importer = new SopInstanceImporter(context);


                DicomProcessingResult result = importer.Import(message);



                if (result.Successful)
                {
                    if (!String.IsNullOrEmpty(result.AccessionNumber))
                    {
                        ///if the accession number is fresh, write the accession number to RIS DB. This is for Dalian Yiwei

                        if (strAcsNbr != result.AccessionNumber)
                        {
                            strAcsNbr = result.AccessionNumber;
                            /// Platform.Log(LogLevel.Info, "The AccessionNumber of this received SOP Instance is:{0}", result.AccessionNumber);
                            //                               RIS4PACS.RISInterface ri = new RIS4PACS.RISInterface();
                            //                               ri.SetImageArrive(result.AccessionNumber);
                            try
                            {
                                Thread thread = new Thread(new ParameterizedThreadStart(UpdateRIS));
                                thread.Start((object)strAcsNbr);

                                //                                RIS4PACS.RISInterface ri = new RIS4PACS.RISInterface();
                                //                                ri.SetImageArrive(result.AccessionNumber);
                            }
                            catch
                            {
                                Platform.Log(LogLevel.Info, "RIS4PACS database update failure.");
                            }
                        }

                        Platform.Log(LogLevel.Info, "Received SOP Instance {0} from {1} to {2} (A#:{3} StudyUid:{4} )",
                                     result.SopInstanceUid, association.CallingAE, association.CalledAE, result.AccessionNumber,
                                     result.StudyInstanceUid);
                    }
                    else
                    {
                        Platform.Log(LogLevel.Info, "Received SOP Instance {0} from {1} to {2} (StudyUid:{3})",
                                     result.SopInstanceUid, association.CallingAE, association.CalledAE,
                                     result.StudyInstanceUid);
                    }
                }
                else
                {
                    Platform.Log(LogLevel.Warn, "Failure importing sop: {0}", result.ErrorMessage);
                }

                server.SendCStoreResponse(presentationId, message.MessageId, message.AffectedSopInstanceUid, result.DicomStatus);
                return(true);
            }
            catch (DicomDataException ex)
            {
                Platform.Log(LogLevel.Error, ex);
                return(false);  // caller will abort the association
            }
            catch (Exception ex)
            {
                Platform.Log(LogLevel.Error, ex);
                return(false);  // caller will abort the association
            }
        }
Example #11
0
        void IDicomServerHandler.OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
        {
            //C-ECHO
            if (message.CommandField == DicomCommandField.CEchoRequest)
            {
                server.SendCEchoResponse(presentationID, message.MessageId, DicomStatuses.Success);
                return;
            }
            //C-Storage
            else if (message.CommandField == DicomCommandField.CStoreRequest)
            {
                String   studyInstanceUid  = null;
                String   seriesInstanceUid = null;
                DicomUid sopInstanceUid;

                bool ok = message.DataSet[DicomTags.SopInstanceUid].TryGetUid(0, out sopInstanceUid);
                if (ok)
                {
                    ok = message.DataSet[DicomTags.SeriesInstanceUid].TryGetString(0, out seriesInstanceUid);
                }
                if (ok)
                {
                    ok = message.DataSet[DicomTags.StudyInstanceUid].TryGetString(0, out studyInstanceUid);
                }

                if (!ok)
                {
                    Logger.LogError("Unable to retrieve UIDs from request message, sending failure status.");

                    server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID,
                                              DicomStatuses.ProcessingFailure);
                    return;
                }

                if (!Directory.Exists(StorageScp.StorageLocation))
                {
                    Directory.CreateDirectory(StorageScp.StorageLocation);
                }

                StringBuilder path = new StringBuilder();
                path.AppendFormat("{0}{1}{2}{3}{4}", StorageScp.StorageLocation, Path.DirectorySeparatorChar,
                                  studyInstanceUid, Path.DirectorySeparatorChar, seriesInstanceUid);

                Directory.CreateDirectory(path.ToString());

                path.AppendFormat("{0}{1}.dcm", Path.DirectorySeparatorChar, sopInstanceUid.UID);

                DicomFile dicomFile = new DicomFile(message, path.ToString());

                dicomFile.TransferSyntaxUid            = TransferSyntax.ExplicitVrLittleEndianUid;
                dicomFile.MediaStorageSopInstanceUid   = sopInstanceUid.UID;
                dicomFile.ImplementationClassUid       = DicomImplementation.ClassUID.UID;
                dicomFile.ImplementationVersionName    = DicomImplementation.Version;
                dicomFile.SourceApplicationEntityTitle = association.CallingAE;
                dicomFile.MediaStorageSopClassUid      = message.SopClass.Uid;

                dicomFile.Save(DicomWriteOptions.None);
                #region Database Insert
                String PatientsName = dicomFile.DataSet[DicomTags.PatientsName].GetString(0, "");
                String PatientId    = dicomFile.DataSet[DicomTags.PatientId].GetString(0, "");
                String StudyId      = dicomFile.DataSet[DicomTags.StudyId].GetString(0, "");
                String StudyTime    = dicomFile.DataSet[DicomTags.StudyTime].GetString(0, "");
                String SopClassUid  = dicomFile.DataSet[DicomTags.SopClassUid].GetString(0, "");

                SqlParameter[] sqlParameters = new SqlParameter[] {
                    new SqlParameter("@SopInstanceUid", SqlDbType.VarChar),
                    new SqlParameter("@SqlClassUid", SqlDbType.VarChar),
                    new SqlParameter("@Path", SqlDbType.VarChar),
                    new SqlParameter("@PatientId", SqlDbType.VarChar),
                    new SqlParameter("@PatientsName", SqlDbType.VarChar),
                    new SqlParameter("@StudyId", SqlDbType.VarChar),
                    new SqlParameter("@StudyTime", SqlDbType.VarChar),
                    new SqlParameter("@StudyInstanceUid", SqlDbType.VarChar),
                    new SqlParameter("@SeriesInstanceUid", SqlDbType.VarChar),
                    new SqlParameter("@ImageId", SqlDbType.VarChar)
                };
                sqlParameters[0].Value = sopInstanceUid.ToString();
                sqlParameters[1].Value = SopClassUid;
                sqlParameters[2].Value = path.ToString();
                sqlParameters[3].Value = PatientId;
                sqlParameters[4].Value = PatientsName;
                sqlParameters[5].Value = StudyId;
                sqlParameters[6].Value = StudyTime;
                sqlParameters[7].Value = dicomFile.DataSet[DicomTags.StudyInstanceUid].GetString(0, "");
                sqlParameters[8].Value = dicomFile.DataSet[DicomTags.SeriesInstanceUid].GetString(0, "");
                sqlParameters[9].Value = dicomFile.DataSet[DicomTags.ImageId].GetString(0, "");
                String sql = @"INSERT INTO DICOMLIB VALUES(@SopInstanceUid,@SqlClassUid,@Path,@PatientId,@PatientsName,@StudyId,@StudyTime,@StudyInstanceUid,@SeriesInstanceUid,@ImageId)";
                SqlHelper.ExecuteNonQuery(SqlHelper.GetConnSting(), CommandType.Text, sql, sqlParameters);
                #endregion
                Logger.LogInfo("Received SOP Instance: {0} for patient {1}", sopInstanceUid, PatientsName);
                server.SendCStoreResponse(presentationID, message.MessageId,
                                          sopInstanceUid.UID,
                                          DicomStatuses.Success);
            }
            //C-Find
            else if (message.CommandField == DicomCommandField.CFindRequest)
            {
                //TODO:读取数据库
                //foreach(构造N+1个Message,SendCFindResponse());
                #region 找出筛选条件
                String[] Patameters = new string[4];
                Patameters[0] = message.DataSet[DicomTags.PatientId].ToString();
                Patameters[1] = message.DataSet[DicomTags.PatientsName].ToString();
                Patameters[2] = message.DataSet[DicomTags.StudyId].ToString();
                Patameters[3] = message.DataSet[DicomTags.StudyTime].ToString();
                String level = message.DataSet[DicomTags.QueryRetrieveLevel].ToString();
                String OnlyFliter = ""; Int32 i = 0;
                while (i < 4)
                {
                    if (Patameters[i] != "")
                    {
                        OnlyFliter = Patameters[i]; break;
                    }
                    i++;
                }
                SqlParameter sqlParameter = null;
                String       sql          = "";
                if (OnlyFliter == "")
                {
                    sql = @"SELECT * FROM DICOMLIB";
                }
                else
                {
                    switch (i)
                    {
                    case 0:
                        sqlParameter       = new SqlParameter("@PatientId", SqlDbType.VarChar);
                        sqlParameter.Value = OnlyFliter; sql = @"SELECT * FROM DICOMLIB WHERE PatientId=@PatientId"; break;

                    case 1:
                        sqlParameter       = new SqlParameter("@PatientsName", SqlDbType.VarChar);
                        sqlParameter.Value = OnlyFliter; sql = @"SELECT * FROM DICOMLIB WHERE PatientsName=@PatientsName"; break;

                    case 2:
                        sqlParameter       = new SqlParameter("@StudyId", SqlDbType.VarChar);
                        sqlParameter.Value = OnlyFliter; sql = @"SELECT * FROM DICOMLIB WHERE StudyId=@StudyId"; break;

                    case 3:
                        sqlParameter       = new SqlParameter("@StudyTime", SqlDbType.VarChar);
                        sqlParameter.Value = OnlyFliter; sql = @"SELECT * FROM DICOMLIB WHERE StudyTime=@StudyTime"; break;
                    }
                }

                #endregion
                DataSet      ds          = SqlHelper.ExecuteDataset(SqlHelper.GetConnSting(), CommandType.Text, sql, sqlParameter);
                int          rows        = ds.Tables[0].Rows.Count;
                DicomMessage tempMessage = message;
                for (int mi = 0; mi < rows; mi++)
                {
                    tempMessage.DataSet[DicomTags.PatientsName].SetString(0, ds.Tables[0].Rows[mi]["PatientsName"].ToString());
                    tempMessage.DataSet[DicomTags.PatientId].SetString(0, ds.Tables[0].Rows[mi]["PatientId"].ToString());
                    tempMessage.DataSet[DicomTags.StudyId].SetString(0, ds.Tables[0].Rows[mi]["StudyId"].ToString());
                    tempMessage.DataSet[DicomTags.StudyTime].SetString(0, ds.Tables[0].Rows[mi]["StudyTime"].ToString());
                    tempMessage.DataSet[DicomTags.SopInstanceUid].SetString(0, ds.Tables[0].Rows[mi]["SopInstanceUid"].ToString());
                    tempMessage.DataSet[DicomTags.SopClassUid].SetString(0, ds.Tables[0].Rows[mi]["SqlClassUid"].ToString());
                    tempMessage.DataSet[DicomTags.StudyInstanceUid].SetString(0, ds.Tables[0].Rows[mi]["StudyInstanceUid"].ToString());
                    tempMessage.DataSet[DicomTags.SeriesInstanceUid].SetString(0, ds.Tables[0].Rows[mi]["SeriesInstanceUid"].ToString());
                    tempMessage.DataSet[DicomTags.ImageId].SetString(0, ds.Tables[0].Rows[mi]["ImageId"].ToString());
                    server.SendCFindResponse(presentationID, tempMessage.MessageId, tempMessage, DicomStatuses.Pending);
                }
                server.SendCFindResponse(presentationID, tempMessage.MessageId, tempMessage, DicomStatuses.Success);
            }
            else if (message.CommandField == DicomCommandField.CMoveRequest)
            {
                //检索数据库,找到文件
                //发送
                #region 查询数据库

                String sql = "";

                String       QueryRetrieveLevel = message.DataSet[DicomTags.QueryRetrieveLevel].ToString();
                SqlParameter sqlParameter       = null;
                if (QueryRetrieveLevel == "PATIENT")
                {
                    sqlParameter       = new SqlParameter("@PatientId", SqlDbType.VarChar);
                    sqlParameter.Value = message.DataSet[DicomTags.PatientId].ToString();
                    sql = "SELECT Path FROM DICOMLIB WHERE PatientId = @PatientId";
                }
                else if (QueryRetrieveLevel == "STUDY")
                {
                    sqlParameter       = new SqlParameter("@StudyInstanceUid", SqlDbType.VarChar);
                    sqlParameter.Value = message.DataSet[DicomTags.StudyInstanceUid].ToString();
                    sql = "SELECT Path FROM DICOMLIB WHERE StudyInstanceUid = @StudyInstanceUid";
                }
                else if (QueryRetrieveLevel == "SERIES")
                {
                    sqlParameter       = new SqlParameter("@SeriesInstanceUid", SqlDbType.VarChar);
                    sqlParameter.Value = message.DataSet[DicomTags.SeriesInstanceUid].ToString();
                    sql = "SELECT Path FROM DICOMLIB WHERE SeriesInstanceUid = @SeriesInstanceUid";
                }
                else if (QueryRetrieveLevel == "IMAG")
                {
                    sqlParameter       = new SqlParameter("@ImageId", SqlDbType.VarChar);
                    sqlParameter.Value = message.DataSet[DicomTags.ImageId].ToString();
                    sql = "SELECT Path FROM DICOMLIB WHERE ImageId = @ImageId";
                }
                DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.GetConnSting(), CommandType.Text, sql, sqlParameter);

                #endregion
                DicomFile dicomFile       = new DicomFile(message, message.DataSet[DicomTags.ImageId].ToString());
                String    MoveDestination = message.MoveDestination.ToString();

                StorageScu _storagescu = new StorageScu();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        String path = ds.Tables[0].Rows[i]["Path"].ToString();
                        _storagescu.AddFileToSend(path);
                    }
                    if (MoveDestination == Samples.Properties.Settings.Default.AETs)
                    {
                        _storagescu.Send(Samples.Properties.Settings.Default.ScpAETitle, Properties.Settings.Default.AETs, Properties.Settings.Default.RemoteHost, Properties.Settings.Default.RemotePort);
                    }
                }
                else
                {
                    Logger.LogInfo("NoFiles");
                }
            }
        }