Ejemplo n.º 1
0
        public void OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
        {
        	if (_type == TestTypes.SendMR)
        	{
        		DicomAttributeCollection 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;
				}

				server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID, DicomStatuses.Success);
			}
        	else
        	{
				Platform.Log(LogLevel.Error,"Unexpected test type mode");
				server.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.InvalidPDUParameter);
				return;        		
        	}
    }
		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;
				}

				var importer = new SopInstanceImporter(_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;
		}
Ejemplo n.º 3
0
        //private static void WriteLog(string s)
        //{
        //    File.AppendAllText("C:\\_store.txt", string.Format("{0}\n",s));
        //}

        /// <summary>
        /// Hàm xử lý khi nhận xong dữ liệu Dicom
        /// </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)
        {
            //wc.Stop();
            //WriteLog(wc.ElapsedMilliseconds.ToString());

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

            String studyInstanceUid = null;
            String seriesInstanceUid = null;
            DicomUid sopInstanceUid;
            //String patientName = null;
            String sex = null;
            sex = message.DataSet[DicomTags.PatientsSex].GetString(0, "O");

            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)
            {
                VBLogger.LogError("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;

            server.SendCStoreResponse(presentationId, message.MessageId,
                                      sopInstanceUid.UID,
                                      DicomStatuses.Success);
            string pathImage = "";
            var path = new StringBuilder();
            path.AppendFormat("{0}{1}{2}{3}{4}", StorageLocation, Path.DirectorySeparatorChar,
                              studyInstanceUid, Path.DirectorySeparatorChar, seriesInstanceUid);

            try
            {
                // Save File
                if (!Directory.Exists(StorageLocation))
                    Directory.CreateDirectory(StorageLocation);
                if (!Directory.Exists(path.ToString()))
                    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);

                //WriteLog(string.Format("Save File OK!: {0}", wc.ElapsedMilliseconds));

                var pd = new DicomUncompressedPixelData(message.DataSet);
                pathImage = path.ToString();
                byte[] thePixels = pd.GetFrame(0);
                var pixData = new UInt16[thePixels.Length/2];
                int h = dicomFile.DataSet[DicomTags.Rows].GetUInt16(0, 0);
                int w = dicomFile.DataSet[DicomTags.Columns].GetUInt16(0, 0);
                UInt16 max = 0, min = UInt16.MaxValue;
                //min = pd.ge
                unsafe
                {
                    fixed (byte* pixPointer = thePixels)
                    {
                        var pP = (UInt16*) pixPointer;
                        for (int i = 0; i < w*h; ++i)
                        {
                            pixData[i] = *pP;
                            if (min > pixData[i]) min = pixData[i];
                            if (max < pixData[i]) max = pixData[i];
                            pP++;
                        }
                    }
                }
                int indexOf = pathImage.LastIndexOf(".dcm");
                pathImage = pathImage.Substring(0, indexOf);
                pathImage = string.Concat(pathImage, "_thumb.jpg");
                string photometricInterpretation;
                message.DataSet[DicomTags.PhotometricInterpretation].TryGetString(0, out photometricInterpretation);
                Bitmap bmp = CreateBitmap(pixData, min, max, w, h, photometricInterpretation);
                bmp.Save(pathImage, ImageFormat.Jpeg);
                bmp.Dispose();
            }
            catch (Exception ex)
            {
                // File.WriteAllText(@"C:\log.txt", ex.ToString());
            }
            //WriteLog(string.Format(" Create Thumbnail OK: {0}", wc.ElapsedMilliseconds));

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

            //Xóa các ký tự thừa trong Patient Name
            patientName = patientName.Replace('^', ' ');

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


            //Insert Install To DB
            //InsertInstanceToImageServer(association, message.DataSet);

            // FeedBack to Rislink
            string patientId = message.DataSet[DicomTags.PatientId].GetString(0, "");
            string bodyPart = message.DataSet[DicomTags.BodyPartExamined].GetString(0, "");
            string viewPosition = message.DataSet[DicomTags.ViewPosition].GetString(0, "");
            string accessionNumber = message.DataSet[DicomTags.AccessionNumber].GetString(0, "").Trim();
            accessionNumber = accessionNumber == "" ? patientId : accessionNumber;
            //var t = message.DataSet[DicomTags.SourceSerialNumber].GetString(0, "").Trim();
            string requestingAe = association.CallingAE;
            if (viewPosition.Trim() == "")
                viewPosition = message.DataSet[DicomTags.PatientOrientation].GetString(0, "");
            //WriteLog(string.Format("Finish time: {0}",wc.ElapsedMilliseconds));
            var updateOk = SpMergeData(bodyPart, patientId, patientName, path.ToString(), sex, studyInstanceUid, seriesInstanceUid,
                        sopInstanceUid.ToString(), viewPosition, accessionNumber, requestingAe);
            Console.WriteLine(updateOk.ToString(CultureInfo.InvariantCulture));
        }
Ejemplo n.º 4
0
        public override bool OnReceiveRequest(ClearCanvas.Dicom.Network.DicomServer server,
                                              ServerAssociationParameters association, byte presentationID, DicomMessage message)
        {
            string   studyInstanceUid;
            string   seriesInstanceUid;
            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)
            {
                Platform.Log(LogLevel.Error, "Unable to retrieve UIDs from request message, sending failure status.");

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

                return(true);
            }

            if (_importContext == null)
            {
                _importContext = new DicomReceiveImportContext(association.CallingAE, GetRemoteHostName(association), StudyStore.GetConfiguration(), EventSource.CurrentProcess);

                // Publish new WorkItems as they're added to the context
                lock (_importContext.StudyWorkItemsSyncLock)
                {
                    _importContext.StudyWorkItems.ItemAdded += delegate(object sender, DictionaryEventArgs <string, WorkItem> args)
                    {
                        Platform.GetService(
                            (IWorkItemActivityMonitorService service) =>
                            service.Publish(new WorkItemPublishRequest
                        {
                            Item =
                                WorkItemDataHelper
                                .FromWorkItem(
                                    args.Item)
                        }));


                        var auditedInstances = new AuditedInstances();
                        var request          =
                            args.Item.Request as DicomReceiveRequest;
                        if (request != null)
                        {
                            auditedInstances.AddInstance(request.Patient.PatientId, request.Patient.PatientsName,
                                                         request.Study.StudyInstanceUid);
                        }

                        AuditHelper.LogReceivedInstances(
                            association.CallingAE, GetRemoteHostName(association),
                            auditedInstances, EventSource.CurrentProcess,
                            EventResult.Success, EventReceiptAction.ActionUnknown);
                    }
                    ;

                    _importContext.StudyWorkItems.ItemChanged += (sender, args) => Platform.GetService(
                        (IWorkItemActivityMonitorService service) =>
                        service.Publish(new WorkItemPublishRequest {
                        Item = WorkItemDataHelper.FromWorkItem(args.Item)
                    }));
                }
            }

            var importer = new ImportFilesUtility(_importContext);

            var result = importer.Import(message, BadFileBehaviourEnum.Ignore, FileImportBehaviourEnum.Save);

            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);
                }
                server.SendCStoreResponse(presentationID, message.MessageId, message.AffectedSopInstanceUid, result.DicomStatus);
            }
            else
            {
                if (result.DicomStatus == DicomStatuses.ProcessingFailure)
                {
                    Platform.Log(LogLevel.Error, "Failure importing sop: {0}", result.ErrorMessage);
                }

                //OnReceiveError(message, result.ErrorMessage, association.CallingAE);
                server.SendCStoreResponse(presentationID, message.MessageId, message.AffectedSopInstanceUid,
                                          result.DicomStatus, result.ErrorMessage);
            }

            return(true);
        }
Ejemplo n.º 5
0
        public override bool OnReceiveRequest(ClearCanvas.Dicom.Network.DicomServer server,
                                              ServerAssociationParameters association, byte presentationID, DicomMessage message)
        {
            string   studyInstanceUid;
            string   seriesInstanceUid;
            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)
            {
                Platform.Log(LogLevel.Error, "Unable to retrieve UIDs from request message, sending failure status.");

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

                return(true);
            }

            if (_importContext == null)
            {
                LoadImportContext(association);
            }

            var importer = new ImportFilesUtility(_importContext);

            var result = importer.Import(message, BadFileBehaviourEnum.Ignore, FileImportBehaviourEnum.Save);

            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);
                }
                server.SendCStoreResponse(presentationID, message.MessageId, message.AffectedSopInstanceUid, result.DicomStatus);
            }
            else
            {
                if (result.DicomStatus == DicomStatuses.ProcessingFailure)
                {
                    Platform.Log(LogLevel.Error, "Failure importing sop: {0}", result.ErrorMessage);
                }

                //OnReceiveError(message, result.ErrorMessage, association.CallingAE);
                server.SendCStoreResponse(presentationID, message.MessageId, message.AffectedSopInstanceUid,
                                          result.DicomStatus, result.ErrorMessage);
            }

            return(true);
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 7
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, association.CalledAE);

                SopInstanceImporter 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
            }
        }
Ejemplo n.º 8
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);
            }

        }
    }
Ejemplo n.º 9
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);
        }