private static void SelectPriorsServers(ServerTreeComponent serverTreeComponent) { ServerTree serverTree = serverTreeComponent.ServerTree; var priorsServers = ServerDirectory.GetPriorsServers(false); CheckPriorsServers(serverTree, priorsServers); IServerTreeNode initialSelection = GetFirstPriorsServerOrGroup(serverTree.RootServerGroup); UncheckAllServers(serverTree); if (initialSelection == null) { if (serverTreeComponent.ShowLocalServerNode) { initialSelection = serverTreeComponent.ServerTree.LocalServer; } else { initialSelection = serverTreeComponent.ServerTree.RootServerGroup; } } serverTreeComponent.SetSelection(initialSelection); }
public static bool VerifyAssociation(IDicomServerContext context, AssociationParameters assocParms, out DicomRejectResult result, out DicomRejectReason reason) { string calledTitle = (assocParms.CalledAE ?? "").Trim(); string callingAE = (assocParms.CallingAE ?? "").Trim(); result = DicomRejectResult.Permanent; reason = DicomRejectReason.NoReasonGiven; var extendedConfiguration = LocalDicomServer.GetExtendedConfiguration(); if (!extendedConfiguration.AllowUnknownCaller && ServerDirectory.GetRemoteServersByAETitle(callingAE).Count == 0) { reason = DicomRejectReason.CallingAENotRecognized; } else if (calledTitle != context.AETitle) { reason = DicomRejectReason.CalledAENotRecognized; } else { return(true); } return(false); }
public void TestServiceNodeLocalServices() { Initialize1(); var local = ServerDirectory.GetLocalServer(); Assert.IsTrue(local.IsSupported <IStudyRootQuery>()); Assert.IsNotNull(local.GetService <IStudyRootQuery>()); Assert.IsTrue(local.IsSupported <IStudyStoreQuery>()); Assert.IsNotNull(local.GetService <IStudyStoreQuery>()); Initialize2(); Assert.IsFalse(local.IsSupported <IStudyRootQuery>()); try { var service = local.GetService <IStudyRootQuery>(); Assert.Fail(); } catch (NotSupportedException) { } Assert.IsFalse(local.IsSupported <IStudyStoreQuery>()); try { var service = local.GetService <IStudyStoreQuery>(); Assert.Fail(); } catch (NotSupportedException) { } }
public static List <IDicomServiceNode> ToDicomServiceNodes(this IServerTreeNode serverTreeNode) { Platform.CheckForNullReference(serverTreeNode, "serverTreeNode"); if (serverTreeNode.IsLocalServer) { return new List <IDicomServiceNode> { ServerDirectory.GetLocalServer() } } ; if (serverTreeNode.IsServer) { return new List <IDicomServiceNode> { ((IServerTreeDicomServer)serverTreeNode).ToDicomServiceNode() } } ; var group = (IServerTreeGroup)serverTreeNode; var childServers = new List <IDicomServiceNode>(); childServers.AddRange(group.ChildGroups.SelectMany(g => g.ToDicomServiceNodes())); childServers.AddRange(group.Servers.Cast <IServerTreeDicomServer>().Select(g => g.ToDicomServiceNode())); return(childServers); }
private static IImageViewer LaunchViewer(OpenStudiesRequest request, string primaryStudyInstanceUid) { try { CompleteOpenStudyInfo(request.StudiesToOpen); } catch (Exception ex) { if (request.ReportFaultToUser) { SynchronizationContext.Current.Post(ReportLoadFailures, ex); } throw; } ImageViewerComponent viewer; if (!request.LoadPriors.HasValue || request.LoadPriors.Value) { viewer = new ImageViewerComponent(LayoutManagerCreationParameters.Extended); } else { viewer = new ImageViewerComponent(LayoutManagerCreationParameters.Extended, PriorStudyFinder.Null); } var loadStudyArgs = (from info in request.StudiesToOpen let server = ServerDirectory.GetRemoteServersByAETitle(info.SourceAETitle).FirstOrDefault() ?? ServerDirectory.GetLocalServer() select new LoadStudyArgs(info.StudyInstanceUid, server)).ToList(); try { viewer.LoadStudies(loadStudyArgs); } catch (Exception e) { bool faultThrown = false; try { HandleLoadStudiesException(e, primaryStudyInstanceUid, viewer); } catch { faultThrown = true; viewer.Dispose(); throw; } finally { if (!faultThrown || request.ReportFaultToUser) { SynchronizationContext.Current.Post(ReportLoadFailures, e); } } } ImageViewerComponent.Launch(viewer, new LaunchImageViewerArgs(ViewerLaunchSettings.WindowBehaviour)); return(viewer); }
public IList <T> Query(T queryCriteria, out LocateFailureInfo[] failures) { if (queryCriteria == null) { const string message = "The argument cannot be null."; Platform.Log(LogLevel.Error, message); throw new FaultException(message); } var results = new List <T>(); var failureList = new List <LocateFailureInfo>(); try { foreach (var priorsServer in ServerDirectory.GetPriorsServers(true)) { try { IList <T> r = null; priorsServer.GetService <IStudyRootQuery>(service => r = _query(queryCriteria, service)); results.AddRange(r); } catch (Exception e) { QueryFailedFault fault = new QueryFailedFault(); fault.Description = String.Format("Failed to query server {0}.", priorsServer.Name); Platform.Log(LogLevel.Error, e, fault.Description); if (_suppressQueryFailureFaults) { failureList.Add(new LocateFailureInfo(fault, fault.Description) { ServerName = priorsServer.Name, ServerAE = priorsServer.AETitle }); } else { throw new FaultException <QueryFailedFault>(fault, fault.Description); } } } } catch (FaultException) { throw; } catch (Exception e) { QueryFailedFault fault = new QueryFailedFault(); fault.Description = String.Format("An unexpected error has occurred."); Platform.Log(LogLevel.Error, e, fault.Description); throw new FaultException <QueryFailedFault>(fault, fault.Description); } failures = failureList.ToArray(); return(results); }
private static DicomServiceNodeList GetPriorsServers() { try { var priorsServers = ServerDirectory.GetPriorsServers(false); return(new DicomServiceNodeList(priorsServers)); } catch (Exception e) { Platform.Log(LogLevel.Warn, e, "Error initializing priors servers from directory."); return(new DicomServiceNodeList()); } }
public StudyInfo(IImageSopProvider provider, NextSeriesNumberDelegate nextSeriesNumberDelegate) { _provider = provider; _nextSeriesNumberDelegate = nextSeriesNumberDelegate; _studyInstanceUid = provider.Sop.StudyInstanceUid; _originServer = ServerDirectory.GetRemoteServersByAETitle(provider.Sop[DicomTags.SourceApplicationEntityTitle].ToString()).FirstOrDefault(); _sourceServer = provider.Sop.DataSource.Server; KeyObjectSeriesUid = DicomUid.GenerateUid().UID; KeyObjectSeriesDateTime = Platform.Time; PresentationSeriesUid = DicomUid.GenerateUid().UID; PresentationSeriesDateTime = Platform.Time; }
public void TestGetPriorsServers() { Initialize1(); var priorsServers = ServerDirectory.GetPriorsServers(true); Assert.AreEqual(2, priorsServers.Count); Assert.AreEqual(1, priorsServers.Count(s => s.IsLocal)); priorsServers = ServerDirectory.GetPriorsServers(false); Assert.AreEqual(1, priorsServers.Count); Assert.AreEqual(0, priorsServers.Count(s => s.IsLocal)); }
/// <summary> /// Constructor. /// </summary> /// <param name="sourceAE">The AE title of the remote application sending the SOP Instances.</param> /// <param name="configuration">Storage configuration. </param> /// <param name="hostname">The IP Address the remote app is connecting with.</param> /// <param name="auditSource">The source of the request for auditing purposes </param> public DicomReceiveImportContext(string sourceAE, string hostname, StorageConfiguration configuration, EventSource auditSource) : base(sourceAE, configuration, auditSource) { // TODO (CR Jun 2012 - Med): This object is disposable and should be cleaned up. _monitor = WorkItemActivityMonitor.Create(false); _monitor.WorkItemsChanged += WorkItemsChanged; var serverList = ServerDirectory.GetRemoteServersByAETitle(sourceAE); if (serverList.Count == 1) _dicomServerNode = CollectionUtils.FirstElement(serverList); _hostname = hostname; }
/// <summary> /// Constructor. /// </summary> /// <param name="sourceAE">The AE title of the remote application sending the SOP Instances.</param> /// <param name="configuration">Storage configuration. </param> /// <param name="hostname">The IP Address the remote app is connecting with.</param> /// <param name="auditSource">The source of the request for auditing purposes </param> public DicomReceiveImportContext(string sourceAE, string hostname, StorageConfiguration configuration, EventSource auditSource) : base(sourceAE, configuration, auditSource) { _monitor = WorkItemActivityMonitor.Create(false); _monitor.WorkItemsChanged += WorkItemsChanged; var serverList = ServerDirectory.GetRemoteServersByAETitle(sourceAE); if (serverList.Count == 1) { _dicomServerNode = CollectionUtils.FirstElement(serverList); } _hostname = hostname; }
public void TestGetServersByName() { Initialize1(); var name1 = ServerDirectory.GetRemoteServerByName("Name1"); Assert.IsNotNull(name1); var name2 = ServerDirectory.GetRemoteServerByName("Name2"); Assert.IsNotNull(name2); Assert.IsNull(ServerDirectory.GetRemoteServerByName(null)); Assert.IsNull(ServerDirectory.GetRemoteServerByName(String.Empty)); Assert.IsNull(ServerDirectory.GetRemoteServerByName("abc")); }
public ImageEntry ToStoreEntry() { var entry = new ImageEntry { Image = new ImageIdentifier(this) { InstanceAvailability = "ONLINE", RetrieveAE = ServerDirectory.GetLocalServer(), SpecificCharacterSet = SpecificCharacterSet }, Data = new ImageEntryData { SourceAETitle = SourceAETitle } }; return(entry); }
public void TestGetServersByAE() { Initialize1(); var all = ServerDirectory.GetRemoteServers(); Assert.AreEqual(2, all.Count); var ae1 = ServerDirectory.GetRemoteServersByAETitle("AE1"); Assert.AreEqual(1, ae1.Count); var ae2 = ServerDirectory.GetRemoteServersByAETitle("AE2"); Assert.AreEqual(1, ae2.Count); Assert.AreEqual(0, ServerDirectory.GetRemoteServersByAETitle(null).Count); Assert.AreEqual(0, ServerDirectory.GetRemoteServersByAETitle(String.Empty).Count); Assert.AreEqual(0, ServerDirectory.GetRemoteServersByAETitle("abc").Count); }
internal SeriesEntry ToStoreEntry() { var entry = new SeriesEntry { Series = new SeriesIdentifier(this) { InstanceAvailability = "ONLINE", RetrieveAE = ServerDirectory.GetLocalServer(), SpecificCharacterSet = SpecificCharacterSet }, Data = new SeriesEntryData { ScheduledDeleteTime = GetScheduledDeleteTime(), SourceAETitlesInSeries = SourceAETitlesInSeries } }; return(entry); }
private void InternalVerifyServer() { if (this.NoServersSelected()) { //should never get here because the verify button should be disabled. this.Context.DesktopWindow.ShowMessageBox(SR.MessageNoServersSelected, MessageBoxActions.Ok); return; } try { var localServer = ServerDirectory.GetLocalServer(); var msgText = new StringBuilder(); msgText.AppendFormat(SR.MessageCEchoVerificationPrefix + "\r\n\r\n"); foreach (var server in this.Context.SelectedServers) { using (var scu = new VerificationScu()) { VerificationResult result = scu.Verify(localServer.AETitle, server.AETitle, server.ScpParameters.HostName, server.ScpParameters.Port); if (result == VerificationResult.Success) { msgText.AppendFormat(SR.MessageCEchoVerificationSingleServerResultSuccess + "\r\n", server.Name); } else { msgText.AppendFormat(SR.MessageCEchoVerificationSingleServerResultFail + "\r\n", server.Name); } // must wait for the SCU thread to release the connection properly before disposal, otherwise we might end up aborting the connection instead scu.Join(new TimeSpan(0, 0, 2)); } } msgText.AppendFormat("\r\n"); this.Context.DesktopWindow.ShowMessageBox(msgText.ToString(), MessageBoxActions.Ok); } catch (Exception e) { ExceptionHandler.Report(e, base.Context.DesktopWindow); } }
public StudyEntry ToStoreEntry() { var entry = new StudyEntry { Study = new StudyRootStudyIdentifier(this) { InstanceAvailability = "ONLINE", RetrieveAE = ServerDirectory.GetLocalServer(), SpecificCharacterSet = SpecificCharacterSet }, Data = new StudyEntryData { DeleteTime = DeleteTime, InstitutionNamesInStudy = DicomStringHelper.GetStringArray(InstitutionNamesInStudy), SourceAETitlesInStudy = DicomStringHelper.GetStringArray(SourceAETitlesInStudy), StationNamesInStudy = DicomStringHelper.GetStringArray(StationNamesInStudy), StoreTime = StoreTime } }; return(entry); }
public void TestServiceNodeRemoteServices() { Initialize1(); var remote = ServerDirectory.GetRemoteServerByName("Name1"); Assert.IsFalse(remote.IsSupported <IStudyStoreQuery>()); Assert.IsTrue(remote.IsSupported <IStudyRootQuery>()); Assert.IsNotNull(remote.GetService <IStudyRootQuery>()); remote = ServerDirectory.GetRemoteServerByName("Name2"); Assert.IsFalse(remote.IsSupported <IStudyStoreQuery>()); Assert.IsFalse(remote.IsSupported <IStudyRootQuery>()); try { var service = remote.GetService <IStudyRootQuery>(); Assert.Fail(); } catch (NotSupportedException) { } }
public void TestGetLocalServer() { Initialize1(); var local = ServerDirectory.GetLocalServer(); Assert.AreEqual(SR.LocalServerName, local.Name); Assert.AreEqual("AETITLE", local.AETitle); //default value from DicomServerSettings. Assert.AreEqual("localhost", local.ScpParameters.HostName); Assert.AreEqual(104, local.ScpParameters.Port); Assert.IsTrue(local.IsLocal); var contract = local.ToDataContract(); Assert.AreEqual(SR.LocalServerName, contract.Server.Name); Assert.AreEqual("AETITLE", contract.Server.AETitle); Assert.AreEqual("localhost", contract.Server.ScpParameters.HostName); Assert.AreEqual(104, contract.Server.ScpParameters.Port); DicomServer.DicomServer.UpdateConfiguration(new DicomServerConfiguration { AETitle = "Local2", HostName = "::1", Port = 104 }); local = ServerDirectory.GetLocalServer(); Assert.AreEqual(SR.LocalServerName, local.Name); Assert.AreEqual("Local2", local.AETitle); Assert.AreEqual("::1", local.ScpParameters.HostName); Assert.AreEqual(104, local.ScpParameters.Port); Assert.IsTrue(local.IsLocal); contract = local.ToDataContract(); Assert.AreEqual(SR.LocalServerName, contract.Server.Name); Assert.AreEqual("Local2", contract.Server.AETitle); Assert.AreEqual("::1", contract.Server.ScpParameters.HostName); Assert.AreEqual(104, contract.Server.ScpParameters.Port); }
/// <summary> /// Executes the save command. /// </summary> /// <returns>The save command.</returns> private async Task ExecuteSaveCommand() { var saved = false; if (IsBusy) { return; } if (ServerAddress.Trim() == null || ServerAddress.Trim().Length < 1) { Page.DisplayAlertMessage("", HACCPUtil.GetResourceString("EnterServerIPAddressorDomainName")); return; } var isDataExists = false; Page.EndEditing(); IsBusy = true; SaveCommand.ChangeCanExecute(); Page.ShowProgressIndicator(); var currentServerAddressStatus = IsServerAddressExist; try { var isConnected = await TestConnection(false); if (isConnected) { if (currentServerAddressStatus) { isDataExists = dataStore.CheckTemperaturesExists() || dataStore.CheckCheckListsExists(); } if (isDataExists == false) { HaccpAppSettings.SharedInstance.SiteSettings.ServerAddress = ServerAddress.Trim(); HaccpAppSettings.SharedInstance.SiteSettings.ServerPort = Port.Trim(); HaccpAppSettings.SharedInstance.SiteSettings.ServerDirectory = ServerDirectory.Trim(); dataStore.SaveSiteSettings(HaccpAppSettings.SharedInstance.SiteSettings); saved = true; } } } catch (Exception ex) { Debug.WriteLine("Ooops! Something went wrong while save connection. Exception: {0}", ex); } finally { IsBusy = false; SaveCommand.ChangeCanExecute(); Page.DismissPopup(); } if (saved) { await Page.ShowAlert("", HACCPUtil.GetResourceString("ServerSettingsupdatedsuccessfully")); if (currentServerAddressStatus) { await Page.PopPage(); } else { //if (HaccpAppSettings.SharedInstance.IsWindows) //{ // var style = Application.Current.Resources["WindowsListScrollHelpGridStyle"] as Style; // if (style != null) // { // style.Setters.RemoveAt(0); // style.Setters.Insert(0, new Setter {Property = VisualElement.HeightRequestProperty, Value = 90}); // } // var recordstyle = Application.Current.Resources["WindowsScrollHelpGridStyle"] as Style; // if (recordstyle != null) // { // recordstyle.Setters.RemoveAt(0); // recordstyle.Setters.Insert(0, // new Setter {Property = VisualElement.HeightRequestProperty, Value = 85}); // } // // related to scroll issue fix after changing language //} Page.LoadHomePage(); } } else if (isDataExists) { var siteSettings = new SiteSettings { ServerAddress = ServerAddress.Trim(), ServerPort = Port.Trim(), ServerDirectory = ServerDirectory.Trim() }; await Page.NavigateToWithSelectedObject(PageEnum.ServerSettingsConfirmation, true, siteSettings); } }
public override bool OnReceiveRequest(ClearCanvas.Dicom.Network.DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message) { //// Check for a Cancel message, and cancel the SCU. if (message.CommandField == DicomCommandField.CCancelRequest) { OnReceiveCancelRequest(message); return(true); } // TODO (CR Jun 2012): Log when there's more than 1. var remoteAE = ServerDirectory.GetRemoteServersByAETitle(message.MoveDestination).FirstOrDefault(); if (remoteAE == null) { server.SendCMoveResponse(presentationID, message.MessageId, new DicomMessage(), DicomStatuses.QueryRetrieveMoveDestinationUnknown); return(true); } String level = message.DataSet[DicomTags.QueryRetrieveLevel].GetString(0, string.Empty); try { if (level.Equals("STUDY")) { OnReceiveMoveStudiesRequest(server, presentationID, message, remoteAE); } else if (level.Equals("SERIES")) { OnReceiveMoveSeriesRequest(server, presentationID, message, remoteAE); } else if (level.Equals("IMAGE")) { OnReceiveMoveImageRequest(server, presentationID, message, remoteAE); } else { Platform.Log(LogLevel.Error, "Unexpected Study Root Move Query/Retrieve level: {0}", level); server.SendCMoveResponse(presentationID, message.MessageId, new DicomMessage(), DicomStatuses.QueryRetrieveIdentifierDoesNotMatchSOPClass); return(true); } } catch (Exception e) { Platform.Log(LogLevel.Error, e, "Unexpected exception when processing C-MOVE-RQ"); try { server.SendCMoveResponse(presentationID, message.MessageId, new DicomMessage(), DicomStatuses.QueryRetrieveUnableToProcess, e.Message); } catch (Exception ex) { Platform.Log(LogLevel.Error, ex, "Unable to send final C-MOVE-RSP message on association from {0} to {1}", association.CallingAE, association.CalledAE); } } return(true); }
/// <summary> /// Registers a number of <see cref="ISopDataSource"/>s with the <see cref="UnitTestStudyLoader"/>. /// </summary> /// <remarks> /// <para>Dispose the returned context to unregister the data sources.</para> /// <para>This method is thread safe.</para> /// </remarks> /// <param name="sopDataSources">The <see cref="ISopDataSource"/>s to be registered.</param> /// <returns>A context object that should be disposed in order to unregister the data sources.</returns> public static UnitTestStudyProviderContext RegisterStudies(IEnumerable <ISopDataSource> sopDataSources) { return(RegisterStudies(ServerDirectory.GetLocalServer(), sopDataSources)); }
public override void Process() { EnsureMaxUsedSpaceNotExceeded(); DicomServerConfiguration configuration = GetServerConfiguration(); var remoteAE = ServerDirectory.GetRemoteServerByName(Request.ServerName); if (remoteAE == null) { Proxy.Fail(string.Format("Unknown destination: {0}", Request.ServerName), WorkItemFailureType.Fatal); return; } if (RetrieveStudy != null) { _scu = new ImageViewerMoveScu(configuration.AETitle, remoteAE, RetrieveStudy.Patient, RetrieveStudy.Study); } else if (RetrieveSeries != null) { _scu = new ImageViewerMoveScu(configuration.AETitle, remoteAE, RetrieveSeries.Patient, RetrieveSeries.Study, RetrieveSeries.SeriesInstanceUids); } else { Proxy.Fail("Invalid request type.", WorkItemFailureType.Fatal); return; } Progress.ImagesToRetrieve = _scu.TotalSubOperations; Progress.FailureSubOperations = 0; Progress.WarningSubOperations = 0; Progress.SuccessSubOperations = 0; Progress.IsCancelable = false; Proxy.UpdateProgress(); _scu.ImageMoveCompleted += OnMoveImage; _scu.Retrieve(); Progress.ImagesToRetrieve = _scu.TotalSubOperations; Progress.SuccessSubOperations = _scu.SuccessSubOperations; Progress.FailureSubOperations = _scu.FailureSubOperations; Progress.WarningSubOperations = _scu.WarningSubOperations; Progress.StatusDetails = !string.IsNullOrEmpty(_scu.ErrorDescriptionDetails) ? _scu.ErrorDescriptionDetails : _scu.FailureDescription; if (_scu.Canceled) { if (_cancelDueToDiskSpace) { var study = RetrieveStudy.Study ?? RetrieveSeries.Study; Platform.Log(LogLevel.Info, "Dicom Retrieve for {0} from {1} was cancelled because disk space has been exceeded", study, remoteAE.AETitle); Progress.IsCancelable = true; throw new NotEnoughStorageException(); // item will be failed } else if (StopPending) { Progress.IsCancelable = true; Proxy.Postpone(); } else { Proxy.Cancel(); } } else if (_scu.FailureSubOperations > 0 || _scu.Failed) { Progress.IsCancelable = true; Proxy.Fail(!string.IsNullOrEmpty(_scu.ErrorDescriptionDetails) ? _scu.ErrorDescriptionDetails : _scu.FailureDescription, WorkItemFailureType.NonFatal); } else { Proxy.Complete(); } }
public override StudyItemList Query(QueryParameters queryParams, IApplicationEntity server) { Platform.CheckForNullReference(queryParams, "queryParams"); //.NET strings are unicode, therefore, so is all the query data. const string utf8 = "ISO_IR 192"; var collection = new DicomAttributeCollection { SpecificCharacterSet = utf8 }; collection[DicomTags.SpecificCharacterSet].SetStringValue(utf8); collection[DicomTags.QueryRetrieveLevel].SetStringValue("STUDY"); collection[DicomTags.PatientId].SetStringValue(queryParams["PatientId"]); collection[DicomTags.AccessionNumber].SetStringValue(queryParams["AccessionNumber"]); collection[DicomTags.PatientsName].SetStringValue(queryParams["PatientsName"]); collection[DicomTags.ReferringPhysiciansName].SetStringValue(queryParams["ReferringPhysiciansName"]); collection[DicomTags.StudyDate].SetStringValue(queryParams["StudyDate"]); collection[DicomTags.StudyTime].SetStringValue(""); collection[DicomTags.StudyDescription].SetStringValue(queryParams["StudyDescription"]); collection[DicomTags.PatientsBirthDate].SetStringValue(""); collection[DicomTags.ModalitiesInStudy].SetStringValue(queryParams["ModalitiesInStudy"]); collection[DicomTags.StudyInstanceUid].SetStringValue(queryParams["StudyInstanceUid"]); collection[DicomTags.NumberOfStudyRelatedInstances].SetStringValue(""); collection[DicomTags.InstanceAvailability].SetEmptyValue(); // must not be included in request collection[DicomTags.PatientSpeciesDescription].SetStringValue(GetString(queryParams, "PatientSpeciesDescription")); var codeValue = GetString(queryParams, "PatientSpeciesCodeSequenceCodeValue"); var codeMeaning = GetString(queryParams, "PatientSpeciesCodeSequenceCodeMeaning"); if (codeValue != null || codeMeaning != null) { var codeSequenceMacro = new CodeSequenceMacro { CodingSchemeDesignator = "", CodeValue = codeValue, CodeMeaning = codeMeaning }; collection[DicomTags.PatientSpeciesCodeSequence].AddSequenceItem(codeSequenceMacro.DicomSequenceItem); } collection[DicomTags.PatientBreedDescription].SetStringValue(GetString(queryParams, "PatientBreedDescription")); codeValue = GetString(queryParams, "PatientBreedCodeSequenceCodeValue"); codeMeaning = GetString(queryParams, "PatientBreedCodeSequenceCodeMeaning"); if (codeValue != null || codeMeaning != null) { var codeSequenceMacro = new CodeSequenceMacro { CodingSchemeDesignator = "", CodeValue = codeValue, CodeMeaning = codeMeaning }; collection[DicomTags.PatientBreedCodeSequence].AddSequenceItem(codeSequenceMacro.DicomSequenceItem); } collection[DicomTags.ResponsiblePerson].SetStringValue(GetString(queryParams, "ResponsiblePerson")); collection[DicomTags.ResponsiblePersonRole].SetStringValue(""); collection[DicomTags.ResponsibleOrganization].SetStringValue(GetString(queryParams, "ResponsibleOrganization")); var localServer = ServerDirectory.GetLocalServer(); var studyItemList = new StudyItemList(); using (var context = new DataAccessContext()) { foreach (DicomAttributeCollection result in context.GetStudyStoreQuery().Query(collection)) { var item = new StudyItem(result[DicomTags.StudyInstanceUid].ToString(), localServer); item.SpecificCharacterSet = result.SpecificCharacterSet; item.PatientId = result[DicomTags.PatientId].ToString(); item.PatientsName = new PersonName(result[DicomTags.PatientsName].ToString()); item.ReferringPhysiciansName = new PersonName(result[DicomTags.ReferringPhysiciansName].GetString(0, "")); item.PatientsBirthDate = result[DicomTags.PatientsBirthDate].ToString(); item.StudyDate = result[DicomTags.StudyDate].ToString(); item.StudyTime = result[DicomTags.StudyTime].ToString(); item.StudyDescription = result[DicomTags.StudyDescription].ToString(); item.ModalitiesInStudy = DicomStringHelper.GetStringArray(result[DicomTags.ModalitiesInStudy].ToString()); item.AccessionNumber = result[DicomTags.AccessionNumber].ToString(); item.NumberOfStudyRelatedInstances = result[DicomTags.NumberOfStudyRelatedInstances].GetInt32(0, 0); item.InstanceAvailability = result[DicomTags.InstanceAvailability].GetString(0, ""); if (String.IsNullOrEmpty(item.InstanceAvailability)) { item.InstanceAvailability = "ONLINE"; } item.PatientSpeciesDescription = result[DicomTags.PatientSpeciesDescription].GetString(0, ""); var patientSpeciesCodeSequence = result[DicomTags.PatientSpeciesCodeSequence]; if (!patientSpeciesCodeSequence.IsNull && patientSpeciesCodeSequence.Count > 0) { var codeSequenceMacro = new CodeSequenceMacro(((DicomSequenceItem[])result[DicomTags.PatientSpeciesCodeSequence].Values)[0]); item.PatientSpeciesCodeSequenceCodingSchemeDesignator = codeSequenceMacro.CodingSchemeDesignator; item.PatientSpeciesCodeSequenceCodeValue = codeSequenceMacro.CodeValue; item.PatientSpeciesCodeSequenceCodeMeaning = codeSequenceMacro.CodeMeaning; } item.PatientBreedDescription = result[DicomTags.PatientBreedDescription].GetString(0, ""); var patientBreedCodeSequence = result[DicomTags.PatientBreedCodeSequence]; if (!patientBreedCodeSequence.IsNull && patientBreedCodeSequence.Count > 0) { var codeSequenceMacro = new CodeSequenceMacro(((DicomSequenceItem[])result[DicomTags.PatientBreedCodeSequence].Values)[0]); item.PatientBreedCodeSequenceCodingSchemeDesignator = codeSequenceMacro.CodingSchemeDesignator; item.PatientBreedCodeSequenceCodeValue = codeSequenceMacro.CodeValue; item.PatientBreedCodeSequenceCodeMeaning = codeSequenceMacro.CodeMeaning; } item.ResponsiblePerson = new PersonName(result[DicomTags.ResponsiblePerson].GetString(0, "")); item.ResponsiblePersonRole = result[DicomTags.ResponsiblePersonRole].GetString(0, ""); item.ResponsibleOrganization = result[DicomTags.ResponsibleOrganization].GetString(0, ""); studyItemList.Add(item); } } AuditHelper.LogQueryIssued(null, null, EventSource.CurrentUser, EventResult.Success, SopClass.StudyRootQueryRetrieveInformationModelFindUid, collection); return(studyItemList); }
public override void Process() { DicomServerConfiguration configuration = GetServerConfiguration(); var remoteAE = ServerDirectory.GetRemoteServerByName(Request.DestinationServerName); if (remoteAE == null) { Proxy.Fail(string.Format("Unknown destination: {0}", Request.DestinationServerName), WorkItemFailureType.Fatal); return; } if (AutoRoute != null && Proxy.Item.Priority != WorkItemPriorityEnum.Stat) { DateTime now = Platform.Time; DateTime scheduledTime = AutoRoute.GetScheduledTime(now, 0); if (now != scheduledTime) { Proxy.Postpone(); Platform.Log(LogLevel.Info, "Rescheduling AutoRoute WorkItem {0} back into the scheduled time window: {1}", Proxy.Item.Oid, Proxy.Item.ProcessTime); return; } } _scu = new ImageViewerStorageScu(configuration.AETitle, remoteAE); LoadImagesToSend(); if (Request.CompressionType != CompressionType.None) { _scu.LoadPreferredSyntaxes(Request); } Progress.TotalImagesToSend = _scu.TotalSubOperations; Progress.FailureSubOperations = 0; Progress.WarningSubOperations = 0; Progress.SuccessSubOperations = 0; Progress.IsCancelable = true; Proxy.UpdateProgress(); _scu.ImageStoreCompleted += OnImageSent; _scu.DoSend(); if (_scu.Canceled) { if (StopPending) { Proxy.Postpone(); } else { Proxy.Cancel(); } } else if (_scu.Failed || _scu.FailureSubOperations > 0) { var settings = new DicomSendSettings(); TimeSpan delay = settings.RetryDelayUnits == RetryDelayTimeUnit.Seconds ? TimeSpan.FromSeconds(settings.RetryDelay) : TimeSpan.FromMinutes(settings.RetryDelay); Proxy.Fail(_scu.FailureDescription, WorkItemFailureType.NonFatal, AutoRoute != null ? AutoRoute.GetScheduledTime(Platform.Time, (int)delay.TotalSeconds) : Platform.Time.Add(delay), settings.RetryCount); } else { Proxy.Complete(); } }
private StudyXml RetrieveStudyXml(StudyLoaderArgs studyLoaderArgs) { var headerParams = new HeaderStreamingParameters { StudyInstanceUID = studyLoaderArgs.StudyInstanceUid, ServerAETitle = _serverAe.AETitle, ReferenceID = Guid.NewGuid().ToString(), IgnoreInUse = studyLoaderArgs.Options != null && studyLoaderArgs.Options.IgnoreInUse }; HeaderStreamingServiceClient client = null; try { string uri = String.Format(StreamingSettings.Default.FormatHeaderServiceUri, _serverAe.ScpParameters.HostName, _serverAe.StreamingParameters.HeaderServicePort); client = new HeaderStreamingServiceClient(new Uri(uri)); client.Open(); var studyXml = client.GetStudyXml(ServerDirectory.GetLocalServer().AETitle, headerParams); client.Close(); return(studyXml); } catch (FaultException <StudyIsInUseFault> e) { throw new InUseLoadStudyException(studyLoaderArgs.StudyInstanceUid, e); } catch (FaultException <StudyIsNearlineFault> e) { throw new NearlineLoadStudyException(studyLoaderArgs.StudyInstanceUid, e) { IsStudyBeingRestored = e.Detail.IsStudyBeingRestored }; } catch (FaultException <StudyNotFoundFault> e) { throw new NotFoundLoadStudyException(studyLoaderArgs.StudyInstanceUid, e); } catch (FaultException e) { //TODO: Some versions (pre-Team) of the ImageServer //throw a generic fault when a study is nearline, instead of the more specialized one. string message = e.Message.ToLower(); if (message.Contains("nearline")) { throw new NearlineLoadStudyException(studyLoaderArgs.StudyInstanceUid, e) { IsStudyBeingRestored = true } } ; //assume true in legacy case. throw new LoadStudyException(studyLoaderArgs.StudyInstanceUid, e); } catch (Exception e) { if (client != null) { client.Abort(); } throw new LoadStudyException(studyLoaderArgs.StudyInstanceUid, e); } }
protected override void AddValueToResult(TDatabaseObject item, DicomAttribute resultAttribute) { resultAttribute.SetString(0, ServerDirectory.GetLocalServer().AETitle); }
public override PriorStudyFinderResult FindPriorStudies() { _cancel = false; var results = new Dictionary <string, StudyItem>(); IPatientReconciliationStrategy reconciliationStrategy = new DefaultPatientReconciliationStrategy(); reconciliationStrategy.SetStudyTree(Viewer.StudyTree); var patientIds = new Dictionary <string, string>(); foreach (Patient patient in Viewer.StudyTree.Patients) { if (_cancel) { break; } IPatientData reconciled = reconciliationStrategy.ReconcileSearchCriteria(patient); patientIds[reconciled.PatientId] = reconciled.PatientId; } int failedCount = 0; int successCount = 0; foreach (var priorsServer in ServerDirectory.GetPriorsServers(true)) { if (_cancel) { break; } try { using (var bridge = new StudyRootQueryBridge(priorsServer.GetService <IStudyRootQuery>())) { foreach (string patientId in patientIds.Keys) { //#10790: don't search for priors if patient id is empty if (string.IsNullOrEmpty(patientId)) { continue; } var identifier = new StudyRootStudyIdentifier { PatientId = patientId }; IList <StudyRootStudyIdentifier> studies = bridge.StudyQuery(identifier); Platform.Log(LogLevel.Debug, "Found {0} prior studies on server '{1}'", studies.Count, priorsServer.Name); foreach (StudyRootStudyIdentifier study in studies) { if (_cancel) { break; } //Eliminate false positives right away. IPatientData reconciled = reconciliationStrategy.ReconcilePatientInformation(study); if (reconciled == null) { continue; } StudyItem studyItem = ConvertToStudyItem(study); if (studyItem == null || results.ContainsKey(studyItem.StudyInstanceUid)) { continue; } if (!results.ContainsKey(studyItem.StudyInstanceUid)) { results[studyItem.StudyInstanceUid] = studyItem; } } } } ++successCount; } catch (Exception e) { ++failedCount; Platform.Log(LogLevel.Error, e, "Failed to query server: {0}", priorsServer.Name); } } if (_cancel) { //Just pretend the query never happened. return(new PriorStudyFinderResult(new StudyItemList(), true)); } if (failedCount > 0) { PriorStudyLoaderExceptionPolicy.NotifyFailedQuery(); if (successCount == 0) { throw new Exception("The search for prior studies has failed."); } } else { //Even if success count is zero, we'll still consider it "successful". PriorStudyLoaderExceptionPolicy.NotifySuccessfulQuery(); } Platform.Log(LogLevel.Debug, "Found {0} prior studies in total.", results.Count); return(new PriorStudyFinderResult(new StudyItemList(results.Values), failedCount == 0)); }
public void Publish() { if (_sourceInformation.ClipboardItems.Count == 0) { return; } while (!WorkItemActivityMonitor.IsRunning) { // TODO CR (Sep 12): convert this to a desktop alert DialogBoxAction result = Application.ActiveDesktopWindow.ShowMessageBox( SR.MessageCannotPublishKeyImagesServersNotRunning, MessageBoxActions.OkCancel); if (result == DialogBoxAction.Cancel) { return; } } var anyFailed = false; try { CreateKeyObjectDocuments(); var publishers = new Dictionary <string, DicomPublishingHelper>(); // add each KO document to a publisher by study foreach (var koDocument in _keyObjectDocuments) { var publisher = GetValue(publishers, koDocument.DataSet[DicomTags.StudyInstanceUid].ToString()); publisher.Files.Add(koDocument); } // add each PR state to a publisher by study foreach (var presentationFrame in SourceFrames) { var sourceFrame = presentationFrame.Key; var publisher = GetValue(publishers, sourceFrame.StudyInstanceUid); if (presentationFrame.Value != null) { publisher.Files.Add(presentationFrame.Value.DicomFile); } var sopDataSource = sourceFrame.ParentImageSop.DataSource; publisher.OriginServer = ServerDirectory.GetRemoteServersByAETitle(sopDataSource[DicomTags.SourceApplicationEntityTitle].ToString()).FirstOrDefault(); publisher.SourceServer = sopDataSource.Server; } // publish all files now foreach (var publisher in publishers.Values) { if (!publisher.Publish()) { anyFailed = true; } } } catch (Exception e) { anyFailed = true; Platform.Log(LogLevel.Error, e, "An unexpected error occurred while trying to publish key images."); } // TODO CR (Sep 12): convert this to a desktop alert if (anyFailed) { Application.ActiveDesktopWindow.ShowMessageBox(SR.MessageKeyImagePublishingFailed, MessageBoxActions.Ok); } }
public void Publish() { if (_sourceInformation.ClipboardItems.Count == 0) { return; } var service = Platform.GetService <IPublishFiles>(); while (!service.CanPublish()) { // ActiveDesktopWindow may be null when the study is opened from Webstation // By the time viewer closes, there is no browser window to display the error if (Application.ActiveDesktopWindow == null) { // Log to file only and return immediately Platform.Log(LogLevel.Error, SR.MessageKeyImagePublishingFailed); return; } else { // TODO CR (Sep 12): convert this to a desktop alert DialogBoxAction result = Application.ActiveDesktopWindow.ShowMessageBox( SR.MessageCannotPublishKeyImagesServersNotRunning, MessageBoxActions.OkCancel); if (result == DialogBoxAction.Cancel) { return; } } } var anyFailed = false; try { CreateKeyObjectDocuments(); var publishers = new Dictionary <string, DicomPublishingHelper>(); // add each KO document to a publisher by study foreach (var koDocument in _keyObjectDocuments) { var publisher = GetValue(publishers, koDocument.DataSet[DicomTags.StudyInstanceUid].ToString()); publisher.Files.Add(koDocument); } // add each PR state to a publisher by study foreach (var presentationFrame in SourceFrames) { var sourceFrame = presentationFrame.Key; var publisher = GetValue(publishers, sourceFrame.StudyInstanceUid); if (presentationFrame.Value != null) { publisher.Files.Add(presentationFrame.Value.DicomFile); } var sopDataSource = sourceFrame.ParentImageSop.DataSource; publisher.OriginServer = ServerDirectory.GetRemoteServersByAETitle(sopDataSource[DicomTags.SourceApplicationEntityTitle].ToString()).FirstOrDefault(); publisher.SourceServer = sopDataSource.Server; } // publish all files now foreach (var publisher in publishers.Values) { if (!publisher.Publish()) { anyFailed = true; } } } catch (Exception e) { anyFailed = true; Platform.Log(LogLevel.Error, e, "An unexpected error occurred while trying to publish key images."); } // TODO CR (Sep 12): convert this to a desktop alert if (anyFailed) { // ActiveDesktopWindow may be null when the study is opened from Webstation // By the time viewer closes, there is no browser window to display the error, so log to file only. if (Application.ActiveDesktopWindow == null) { Platform.Log(LogLevel.Error, SR.MessageKeyImagePublishingFailed); } else { Application.ActiveDesktopWindow.ShowMessageBox(SR.MessageKeyImagePublishingFailed, MessageBoxActions.Ok); } } }