public bool SaveStreamData(DicomMessage message, byte[] data, int offset, int count)
		{
			var importer = new SopInstanceImporter(_importContext);
			var sopInstanceUid = message.DataSet[DicomTags.SopInstanceUid].GetString(0, string.Empty);
			
			if (_fileStream == null)
			{
				if (!importer.GetStreamedFileStorageFolder(message, out _sourceFolder, out _filesystemStreamingFolder))
				{
					Platform.Log(LogLevel.Warn, "Unable to create a folder to save SOP Instance, rejecting: {0}", sopInstanceUid);
					return false;
				}

				_sourceFilename = Path.Combine(_sourceFolder, Guid.NewGuid().ToString() + ServerPlatform.DicomFileExtension);

				try
				{
					_fileStream = FileStreamOpener.OpenForSoleUpdate(_sourceFilename, FileMode.Create);
				}
				catch (Exception x)
				{
					Platform.Log(LogLevel.Warn, x, "Unable to open file for saving filestream: {0}", _sourceFilename);
					return false;
				}
			}

			_fileStream.Write(data, offset, count);

			return true;
		}
        public ImportSopResponse ImportSop(ImportSopRequest request)
        {
            try
            {
                var theFile = new DicomFile(string.Format("{0}{1}", request.SopInstanceUid, ServerPlatform.DicomFileExtension));

                using (var stream = new LargeMemoryStream(request.SopInstance))
                {
                    theFile.Load(stream);
                }

                var partition = ServerPartitionMonitor.Instance.GetPartition(request.CalledAETitle);

                string aeTitle = theFile.SourceApplicationEntityTitle;

                if (_importerContext == null)
                    _importerContext = new SopInstanceImporterContext(
                        String.Format("{0}_{1}", aeTitle, DateTime.Now.ToString("yyyyMMddhhmmss")),
                        partition.AeTitle, partition);

                var utility = new SopInstanceImporter(_importerContext);


                var importResult = utility.Import(theFile);
                if (!importResult.Successful)
                    Platform.Log(LogLevel.Error, "Failure importing file file from Web Service: {0}, SOP Instance UID: {1}", importResult.ErrorMessage, request.SopInstanceUid);
                else
                    Platform.Log(LogLevel.Info, "Processed import for SOP through Web Service: {0}.", request.SopInstanceUid);

                var result = new ImportSopResponse
                    {
                        DicomStatusCode = importResult.DicomStatus.Code,
                        FailureMessage = importResult.ErrorMessage,
                        Successful = importResult.Successful
                    };

                return result;
            }
            catch (Exception ex)
            {
                var message = string.Format("Failed to import files: {0}, SOP Instance UID: {1}", ex.Message, request.SopInstanceUid);
                Platform.Log(LogLevel.Error, message);
                throw new FaultException(message);
            }
        }
        private AutoReconcilerResult ProcessImageAsIs(DicomFile file, StudyHistory lastHistory)
        {
            StudyStorage         destinationStudy = StudyStorage.Load(lastHistory.DestStudyStorageKey);
            StudyStorageLocation destStudy;
            AutoReconcilerResult preProcessingResult = new AutoReconcilerResult(StudyReconcileAction.ProcessAsIs);

            //Load the destination.  An exception will be thrown if any issues are encountered.
            FilesystemMonitor.Instance.GetWritableStudyStorageLocation(destinationStudy.ServerPartitionKey,
                                                                       destinationStudy.StudyInstanceUid, StudyRestore.True,
                                                                       StudyCache.True, out destStudy);

            bool belongsToAnotherStudy = !destStudy.Equals(StorageLocation);

            EnsureStudyCanBeUpdated(destStudy);

            if (belongsToAnotherStudy)
            {
                preProcessingResult.Changes = new List <UpdateItem>
                {
                    new UpdateItem(DicomTags.StudyInstanceUid, file.DataSet[DicomTags.StudyInstanceUid].ToString(), destStudy.StudyInstanceUid)
                };

                file.DataSet[DicomTags.StudyInstanceUid].SetStringValue(destStudy.StudyInstanceUid);
                SopInstanceImporterContext importContext = new SopInstanceImporterContext(
                    _contextID,
                    file.SourceApplicationEntityTitle, destStudy.ServerPartition);
                SopInstanceImporter   importer = new SopInstanceImporter(importContext);
                DicomProcessingResult result   = importer.Import(file);

                if (!result.Successful)
                {
                    throw new ApplicationException("Unable to import image to destination study");
                }
            }
            return(preProcessingResult);
        }
		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;
		}
        private void InitializeImporter()
        {
            if (_importer==null)
            {
                SopInstanceImporterContext context = new SopInstanceImporterContext(
                                String.Format("{0}_{1}", _parms.PartitionAE, _startTimeStamp.ToString("yyyyMMddhhmmss")),
                                _parms.PartitionAE, _parms.PartitionAE);

                _importer = new SopInstanceImporter(context);
            }
           
        }
Example #6
0
        private AutoReconcilerResult MergeImage(StudyReconcileAction action, DicomFile file, StudyHistory lastHistory)
        {
            string originalSeriesUid = file.DataSet[DicomTags.SeriesInstanceUid].ToString();
            string originalSopUid = file.DataSet[DicomTags.SopInstanceUid].ToString();
            
            AutoReconcilerResult preProcessingResult = null;
        	StudyStorageLocation destStudy;
            UidMapper uidMapper = null;
        	if (lastHistory.DestStudyStorageKey != null)
            {
                StudyStorage destinationStudy = StudyStorage.Load(lastHistory.DestStudyStorageKey);

				//Load the destination.  An exception will be thrown if any issues are encountered.
				FilesystemMonitor.Instance.GetWritableStudyStorageLocation(destinationStudy.ServerPartitionKey,
																		   destinationStudy.StudyInstanceUid, 
																		   StudyRestore.True, StudyCache.True, 
																		   out destStudy);

                EnsureStudyCanBeUpdated(destStudy);

                bool belongsToAnotherStudy = !destStudy.Equals(StorageLocation);

                ImageUpdateCommandBuilder commandBuilder = new ImageUpdateCommandBuilder();
                IList<BaseImageLevelUpdateCommand> commands = commandBuilder.BuildCommands<StudyMatchingMap>(destStudy);
                if (belongsToAnotherStudy)
                {
                    Platform.Log(LogLevel.Info, "AUTO-RECONCILE: Move SOP {0} to Study {1}, A#: {2}, Patient {3}", originalSopUid, destStudy.StudyInstanceUid, destStudy.Study.AccessionNumber, destStudy.Study.PatientsName);

                    // Load the Uid Map, either from cache or from disk
                    if (!_uidMapCache.TryGetValue(destStudy.Key, out uidMapper))
                    {
                        UidMapXml mapXml = new UidMapXml();
                        mapXml.Load(destStudy);
                        uidMapper = new UidMapper(mapXml);

                        _uidMapCache.Add(destStudy.Key, uidMapper);
                    }

                    try
                    {
                        commands.Add(GetUidMappingCommand(StorageLocation, destStudy, uidMapper, originalSopUid, originalSeriesUid));
                    }
                    catch (InstanceAlreadyExistsException ex)
                    {
                        Platform.Log(LogLevel.Info, "An instance already exists with the SOP Instance Uid {0}", ex.SopInstanceUid);
                        preProcessingResult = new AutoReconcilerResult(StudyReconcileAction.Discard) { DiscardImage = true };

                        return preProcessingResult;
                    }
                }


                preProcessingResult = new AutoReconcilerResult(action) { Changes = GetUpdateList(file, commands) };

                UpdateImage(file, commands);

                // First, must update the map
                if (uidMapper != null && uidMapper.Dirty)
                {
                    UpdateUidMap(destStudy, uidMapper);
                }

                if (belongsToAnotherStudy)
                {
                    SopInstanceImporterContext importContext = new SopInstanceImporterContext(_contextID, file.SourceApplicationEntityTitle, destStudy.ServerPartition);
                    SopInstanceImporter importer = new SopInstanceImporter(importContext);
                    DicomProcessingResult result = importer.Import(file);

                    if (!result.Successful)
                    {
                        throw new ApplicationException(result.ErrorMessage);
                    }
                }


            }
            return preProcessingResult;
        }
Example #7
0
        private AutoReconcilerResult ProcessImageAsIs(DicomFile file, StudyHistory lastHistory)
        {
            StudyStorage destinationStudy = StudyStorage.Load(lastHistory.DestStudyStorageKey);
        	StudyStorageLocation destStudy;
            AutoReconcilerResult preProcessingResult = new AutoReconcilerResult(StudyReconcileAction.ProcessAsIs);

			//Load the destination.  An exception will be thrown if any issues are encountered.
        	FilesystemMonitor.Instance.GetWritableStudyStorageLocation(destinationStudy.ServerPartitionKey,
        	                                                           destinationStudy.StudyInstanceUid, StudyRestore.True,
        	                                                           StudyCache.True, out destStudy);

            bool belongsToAnotherStudy = !destStudy.Equals(StorageLocation);

            EnsureStudyCanBeUpdated(destStudy);

            if (belongsToAnotherStudy)
            {
                preProcessingResult.Changes = new List<UpdateItem>
                                                  {
                                                      new UpdateItem(DicomTags.StudyInstanceUid, file.DataSet[DicomTags.StudyInstanceUid].ToString(), destStudy.StudyInstanceUid)
                                                  };

                file.DataSet[DicomTags.StudyInstanceUid].SetStringValue(destStudy.StudyInstanceUid);
                SopInstanceImporterContext importContext = new SopInstanceImporterContext(
                    _contextID,
                    file.SourceApplicationEntityTitle, destStudy.ServerPartition);
                SopInstanceImporter importer = new SopInstanceImporter(importContext);
                DicomProcessingResult result = importer.Import(file);

                if (!result.Successful)
                {
                    throw new ApplicationException("Unable to import image to destination study");
                }
            }
            return preProcessingResult;
        }
Example #8
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
            }
        }
        private AutoReconcilerResult MergeImage(StudyReconcileAction action, DicomFile file, StudyHistory lastHistory)
        {
            string originalSeriesUid = file.DataSet[DicomTags.SeriesInstanceUid].ToString();
            string originalSopUid    = file.DataSet[DicomTags.SopInstanceUid].ToString();

            AutoReconcilerResult preProcessingResult = null;
            StudyStorageLocation destStudy;
            UidMapper            uidMapper = null;

            if (lastHistory.DestStudyStorageKey != null)
            {
                StudyStorage destinationStudy = StudyStorage.Load(lastHistory.DestStudyStorageKey);

                //Load the destination.  An exception will be thrown if any issues are encountered.
                FilesystemMonitor.Instance.GetWritableStudyStorageLocation(destinationStudy.ServerPartitionKey,
                                                                           destinationStudy.StudyInstanceUid,
                                                                           StudyRestore.True, StudyCache.True,
                                                                           out destStudy);

                EnsureStudyCanBeUpdated(destStudy);

                bool belongsToAnotherStudy = !destStudy.Equals(StorageLocation);

                ImageUpdateCommandBuilder           commandBuilder = new ImageUpdateCommandBuilder();
                IList <BaseImageLevelUpdateCommand> commands       = commandBuilder.BuildCommands <StudyMatchingMap>(destStudy);
                if (belongsToAnotherStudy)
                {
                    Platform.Log(LogLevel.Info, "AUTO-RECONCILE: Move SOP {0} to Study {1}, A#: {2}, Patient {3}", originalSopUid, destStudy.StudyInstanceUid, destStudy.Study.AccessionNumber, destStudy.Study.PatientsName);

                    // Load the Uid Map, either from cache or from disk
                    if (!_uidMapCache.TryGetValue(destStudy.Key, out uidMapper))
                    {
                        UidMapXml mapXml = new UidMapXml();
                        mapXml.Load(destStudy);
                        uidMapper = new UidMapper(mapXml);

                        _uidMapCache.Add(destStudy.Key, uidMapper);
                    }

                    try
                    {
                        commands.Add(GetUidMappingCommand(StorageLocation, destStudy, uidMapper, originalSopUid, originalSeriesUid));
                    }
                    catch (InstanceAlreadyExistsException ex)
                    {
                        Platform.Log(LogLevel.Info, "An instance already exists with the SOP Instance Uid {0}", ex.SopInstanceUid);
                        preProcessingResult = new AutoReconcilerResult(StudyReconcileAction.Discard)
                        {
                            DiscardImage = true
                        };

                        return(preProcessingResult);
                    }
                }


                preProcessingResult = new AutoReconcilerResult(action)
                {
                    Changes = GetUpdateList(file, commands)
                };

                UpdateImage(file, commands);

                // First, must update the map
                if (uidMapper != null && uidMapper.Dirty)
                {
                    UpdateUidMap(destStudy, uidMapper);
                }

                if (belongsToAnotherStudy)
                {
                    SopInstanceImporterContext importContext = new SopInstanceImporterContext(_contextID, file.SourceApplicationEntityTitle, destStudy.ServerPartition);
                    SopInstanceImporter        importer      = new SopInstanceImporter(importContext);
                    DicomProcessingResult      result        = importer.Import(file);

                    if (!result.Successful)
                    {
                        throw new ApplicationException(result.ErrorMessage);
                    }
                }
            }
            return(preProcessingResult);
        }