bool LoadDicomFile(string filename) { //if (_cancel) // return false; using (DicomDataSet ds = new DicomDataSet()) { ListViewItem item = null; DicomElement element; string strTransferSyntax = ""; bool succeeded = true; try { this.Cursor = Cursors.WaitCursor; ds.Load(filename, DicomDataSetLoadFlags.None); item = listViewImages.Items.Add(ds.GetValue <string>(DicomTag.PatientName, string.Empty)); item.SubItems.Add(ds.GetValue <string>(DicomTag.PatientID, string.Empty)); item.SubItems.Add(ds.GetValue <string>(DicomTag.StudyID, string.Empty)); item.SubItems.Add(ds.GetValue <string>(DicomTag.Modality, string.Empty)); strTransferSyntax = "Implicit VR - Little Endian"; element = ds.FindFirstElement(null, DicomTag.TransferSyntaxUID, false); if (element != null && ds.GetElementValueCount(element) > 0) { string uidString; DicomUid uid; uidString = ds.GetValue <string>(element, string.Empty); uid = DicomUidTable.Instance.Find(uidString); if (uid != null) { strTransferSyntax = uid.Name; } } } catch (DicomException de) { LogText("Dicom error: " + de.Code.ToString(), filename); succeeded = false; } if (succeeded) { // Mark item read if we have a basic directory if (ds.InformationClass == DicomClassType.BasicDirectory) { item.Font = new Font(listViewImages.Font, FontStyle.Bold); } item.SubItems.Add(strTransferSyntax); item.SubItems.Add(filename); item.Checked = true; } this.Cursor = Cursors.Default; return(succeeded); } }
public List <SeriesImage> GetInstanceImages(string[] instanceUIDs) { DataSet instances; List <SeriesImage> seriesImages = new List <SeriesImage>(); instances = QueryInstances(instanceUIDs); foreach (DataRow row in instances.Tables[DataTableHelper.InstanceTableName].Rows) { string referencedFile = row.Field <string>("ReferencedFile"); using (DicomDataSet dicomDs = new DicomDataSet()) { RasterImage image; dicomDs.Load(referencedFile, DicomDataSetLoadFlags.None); image = GetImage(dicomDs); if (image != null) { string seriesIntanceUID = dicomDs.GetValue <string>(DicomTag.SeriesInstanceUID, string.Empty); string sopInstanceUID = dicomDs.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty); SeriesImage si = new SeriesImage(seriesIntanceUID, sopInstanceUID, image); seriesImages.Add(si); } } } return(seriesImages); }
public List <SeriesImage> GetAllPatientImages(string patientID) { List <SeriesImage> seriesImages; DataSet instances; seriesImages = new List <SeriesImage>(); instances = QueryCurrentPatient(patientID); foreach (DataRow row in instances.Tables[DataTableHelper.InstanceTableName].Rows) { RasterImage image; string referencedFile = row.Field <string>("ReferencedFile"); using (var dicomDs = new DicomDataSet()) { dicomDs.Load(referencedFile, DicomDataSetLoadFlags.None); double xDpi = 0; double yDpi = 0; AddInsUtils.GetDpi(dicomDs, out xDpi, out yDpi); image = GetImage(dicomDs); if (image != null) { string seriesIntanceUID = dicomDs.GetValue <string>(DicomTag.SeriesInstanceUID, string.Empty); string sopInstanceUID = dicomDs.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty); SeriesImage si = new SeriesImage(seriesIntanceUID, sopInstanceUID, image, xDpi, yDpi); seriesImages.Add(si); } } } return(seriesImages); }
private void AddCommitItem(DicomDataSet ds, long tag, StorageCommit.StorageCommit commit) { DicomElement rppss = null; DicomElement element; rppss = ds.FindFirstElement(null, tag, true); // If SameStudy goes to false, it is false for the entire commit if (commit.SameStudy) { commit.SameStudy = rppss != null; } commit.TransactionUID = ds.GetValue <string>(DicomTag.TransactionUID, string.Empty); element = ds.GetChildElement(rppss, false); while (element != null) { DicomElement child = ds.GetChildElement(element, true); if (child != null) { StorageCommitItem item = new StorageCommitItem(); item.SOPClassUID = ds.GetValue <string>(child, true, DicomTag.ReferencedSOPClassUID, string.Empty); item.SOPInstanceUID = ds.GetValue <string>(child, true, DicomTag.ReferencedSOPInstanceUID, string.Empty); commit.Items.Add(item); } element = ds.GetNextElement(element, true, true); } }
public static void InsertDefaultImages(string prefix, int max, int padding, Configuration configuration) { MedicalWorkstationConfigurationDemo.UI.MainForm.StoreClientSessionProxy proxy = null; InstanceCStoreCommand cmd = null; IStorageDataAccessAgent agent = DataAccessFactory.GetInstance(new StorageDataAccessConfigurationView(configuration, DicomDemoSettingsManager.ProductNameStorageServer, null)).CreateDataAccessAgent <IStorageDataAccessAgent>(); string formatString = BuildDefaultImageFormatString(padding); for (int i = 1; i < max + 1; i++) { using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format(formatString, prefix, i))) { using (DicomDataSet ds = new DicomDataSet()) { ds.Load(stream, DicomDataSetLoadFlags.None); proxy = new MedicalWorkstationConfigurationDemo.UI.MainForm.StoreClientSessionProxy(); cmd = new InstanceCStoreCommand(proxy, ds, agent); proxy.AffectedSOPInstance = ds.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty); proxy.AbstractClass = ds.GetValue <string>(DicomTag.SOPClassUID, string.Empty); ds.InsertElementAndSetValue(DicomTag.MediaStorageSOPInstanceUID, proxy.AffectedSOPInstance); cmd.Execute(); ImageCountUpdate(); } } } }
public static void InsertDefaultImages(string prefix, int max, Configuration configuration) { MedicalWorkstationConfigurationDemo.UI.MainForm.StoreClientSessionProxy proxy = null; InstanceCStoreCommand cmd = null; IStorageDataAccessAgent agent = DataAccessFactory.GetInstance(new StorageDataAccessConfigurationView(configuration, DicomDemoSettingsManager.ProductNameStorageServer, null)).CreateDataAccessAgent <IStorageDataAccessAgent>(); string formatString = Path.Combine(DemosGlobal.ImagesFolder, prefix); for (int i = 1; i < max + 1; i++) { using (DicomDataSet ds = new DicomDataSet()) { string fileName = string.Format(formatString, i); if (File.Exists(fileName)) { ds.Load(fileName, DicomDataSetLoadFlags.None); proxy = new MedicalWorkstationConfigurationDemo.UI.MainForm.StoreClientSessionProxy(); cmd = new InstanceCStoreCommand(proxy, ds, agent); proxy.AffectedSOPInstance = ds.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty); proxy.AbstractClass = ds.GetValue <string>(DicomTag.SOPClassUID, string.Empty); ds.InsertElementAndSetValue(DicomTag.MediaStorageSOPInstanceUID, proxy.AffectedSOPInstance); cmd.Execute(); ImageCountUpdate(); } } } }
public MoveRequestInformation(DicomDataSet request) { Request = request; QueryLevel = request.GetValue <string> (DicomTag.QueryRetrieveLevel, string.Empty); PatientId = request.GetValue <string> (DicomTag.PatientID, string.Empty); StudyInstanceUID = new List <string> ( ); SeriesInstanceUID = new List <string> ( ); SopInstanceUID = new List <string> ( ); string studyInstanceUID = request.GetValue <string> (DicomTag.StudyInstanceUID, string.Empty); if (!string.IsNullOrEmpty(studyInstanceUID)) { StudyInstanceUID.AddRange(studyInstanceUID.Split('\\')); } string seriesInstanceUID = request.GetValue <string> (DicomTag.SeriesInstanceUID, string.Empty); if (!string.IsNullOrEmpty(seriesInstanceUID)) { SeriesInstanceUID.AddRange(seriesInstanceUID.Split('\\')); } string sopInstanceUID = request.GetValue <string> (DicomTag.SOPInstanceUID, string.Empty); if (!string.IsNullOrEmpty(sopInstanceUID)) { SopInstanceUID.AddRange(sopInstanceUID.Split('\\')); } }
public static DicomCommandStatusType GetAttributeStatus(string level, string affectedClass, DicomDataSet ds) { if (level.Length == 0) { return(DicomCommandStatusType.InvalidArgumentValue); } if (affectedClass == DicomUidType.PatientRootQueryFind && level != "PATIENT") { if (!ExtensionMethods.HasTag(ds, DicomTag.PatientID)) { return(DicomCommandStatusType.MissingAttribute); } if (ds.GetValue <string>(DicomTag.PatientID, string.Empty).Length == 0) { return(DicomCommandStatusType.MissingAttribute); } } if (level == "STUDY" || level == "SERIES" || level == "IMAGE") { if (!ExtensionMethods.HasTag(ds, DicomTag.StudyInstanceUID)) { return(DicomCommandStatusType.MissingAttribute); } if (level == "SERIES" || level == "IMAGE") { if (ds.GetValue <string>(DicomTag.StudyInstanceUID, string.Empty).Length == 0) { return(DicomCommandStatusType.MissingAttribute); } } } if (level == "SERIES" || level == "IMAGE") { if (!ExtensionMethods.HasTag(ds, DicomTag.SeriesInstanceUID)) { return(DicomCommandStatusType.MissingAttribute); } } if (level == "IMAGE") { if (!ExtensionMethods.HasTag(ds, DicomTag.SOPInstanceUID)) { return(DicomCommandStatusType.MissingAttribute); } } return(DicomCommandStatusType.Success); }
public static bool SendMessageQueueImplementation(DicomDataSet ds, string command, string sopInstanceUid, string path) { if (ds != null) { if (ds.IsHangingProtocolDataSet()) { // Filter out the hanging protocol datasets because there is no cache for these return(true); } } bool messageQueueSuccess = true; { try { int width = 0; int height = 0; if (ds != null) { width = ds.GetValue <int>(DicomTag.Columns, 0); height = ds.GetValue <int>(DicomTag.Rows, 0); if (string.IsNullOrEmpty(sopInstanceUid)) { sopInstanceUid = ds.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty); } } MessagingQueue.Send("storageserver", "19", command, new MessagingDicomFile() { FileName = path, Width = width, Height = height, SopInstanceUID = sopInstanceUid }); } catch (Exception ex) { Logger.Global.Log(string.Empty, string.Empty, 0, string.Empty, string.Empty, 0, DicomCommandType.Undefined, DateTime.Now, LogType.Warning, MessageDirection.None, "Message Queue Error': " + ex.Message, null, null); messageQueueSuccess = false; } } return(messageQueueSuccess); }
private static DicomCommandStatusType AddImage(DateTime receive, string sopInstance, string StudyInstanceUid, string SeriesInstanceUid, string ConnectionString, string AETitle, DicomDataSet dataset, string ImageDirectory) { if (string.IsNullOrEmpty(sopInstance)) { throw new ArgumentException("Missing dicom tag", "SOP Instance UID"); } if (!RecordExists(ConnectionString, "Images", "SOPInstanceUID = '" + sopInstance + "'")) { string fileName = ImageDirectory + sopInstance + ".dcm"; SqlCeResultSet rs = SqlCeHelper.ExecuteResultSet(ConnectionString, "Images"); SqlCeUpdatableRecord image = rs.CreateRecord(); image.SetValue(0, sopInstance); image.SetValue(1, SeriesInstanceUid); image.SetValue(2, StudyInstanceUid); if (HasValue(dataset, DicomTag.InstanceNumber)) { image.SetValue(3, dataset.GetValue <int>(DicomTag.InstanceNumber, 0)); } image.SetValue(4, fileName); image.SetValue(5, dataset.GetValue <string>(DicomTag.TransferSyntaxUID, DicomUidType.ImplicitVRLittleEndian)); image.SetValue(6, dataset.GetValue <string>(DicomTag.SOPClassUID, string.Empty)); image.SetValue(7, dataset.GetValue <string>(DicomTag.StationName, string.Empty)); image.SetValue(8, GetDateString(DateTime.Now, DateTime.Now)); image.SetValue(9, AETitle); rs.Insert(image); rs.Close(); // // store the file // if (!Directory.Exists(ImageDirectory)) { Directory.CreateDirectory(ImageDirectory); } dataset.Save(fileName, DicomDataSetSaveFlags.None); } else { return(DicomCommandStatusType.DuplicateInstance); } return(DicomCommandStatusType.Success); }
public static DicomDateRangeValue[] GetDateRange(DicomDataSet ds, long Tag) { // Get the date range count List <string> dateList = ds.GetValue <List <string> >(Tag, null); if (dateList == null) { return(null); } int count = dateList.Count; if (count <= 0) { return(null); } DicomDateRangeValue[] d = new DicomDateRangeValue[count]; DicomElement element = ds.FindFirstElement(null, Tag, true); if (element != null) { if (element.Length > 0) { for (int i = 0; i < count; i++) { d[i] = ds.GetDateRangeValue(element, i); } return(d); } } return(null); }
/// <summary> /// Adds the patient. /// </summary> /// <param name="ConnectionString">The connection string.</param> /// <param name="AETitle">The AE title.</param> /// <param name="dataset">The dataset.</param> /// <returns></returns> private static string AddPatient(string ConnectionString, string AETitle, DicomDataSet dataset) { string pid = dataset.GetValue <string>(DicomTag.PatientID, string.Empty); if (string.IsNullOrEmpty(pid)) { throw new ArgumentException("Missing dicom tag", "Patient ID"); } if (!RecordExists(ConnectionString, "Patients", "PatientID = '" + pid + "'")) { DateTime?bd = dataset.GetValue <DateTime?>(DicomTag.PatientBirthDate, null, GetDate); DateTime?bt = dataset.GetValue <DateTime?>(DicomTag.PatientBirthTime, null, GetDate); string sql = string.Format(PatientInsert, pid, dataset.GetValue <string>(DicomTag.PatientName, string.Empty), GetDateString(bd, bt), dataset.GetValue <string>(DicomTag.PatientSex, string.Empty), dataset.GetValue <string>(DicomTag.EthnicGroup, string.Empty), dataset.GetValue <string>(DicomTag.PatientComments, string.Empty), AETitle); SqlCeHelper.ExecuteNonQuery(ConnectionString, sql); } return(pid); }
private void PatientMatchDelegate(PatientQuery patientResult, DicomDataSet ds) { PatientData patient = new PatientData( ); #if LEADTOOLS_V19_OR_LATER patient.BirthDate = (patientResult.PatientBirthDate == null) ? string.Empty : patientResult.PatientBirthDate.StartDate.Value.ToString( ); #else patient.BirthDate = (patientResult.PatientBirthDate == null) ? string.Empty : patientResult.PatientBirthDate.Value.ToString( ); #endif patient.Comments = patientResult.PatientComments; patient.ID = patientResult.PatientId; patient.Name = (string.IsNullOrEmpty(patientResult.PatientName)) ? string.Empty : patientResult.PatientName; patient.Sex = patientResult.PatientSex; patient.NumberOfRelatedInstances = ds.GetValue <string> (DicomTag.NumberOfPatientRelatedInstances, string.Empty); patient.NumberOfRelatedSeries = ds.GetValue <string> (DicomTag.NumberOfPatientRelatedSeries, string.Empty); patient.NumberOfRelatedStudies = ds.GetValue <string> (DicomTag.NumberOfPatientRelatedStudies, string.Empty); }
/// <summary> /// If the ‘update’ parameter is true, replaces all the DataSet Patient table information with the corresponding information from the DicomDataSet. /// </summary> /// <param name="patient">Row of the patient table that is being udpated</param> /// <param name="ds">The Leadtools.Dicom.DicomDataSet that is being stored</param> /// <param name="instanceDataSet">The DataSet that contains the patient, study, series, and instance tables</param> /// <param name="patientId">The PatientID of the patient being updated</param> /// <param name="retrieveAE">retrieveAe">AE Title of the client doing the retrieval</param> /// <param name="update">If 'true', updates the DataSet Patient table information with the corresponding information from the DicomDataSet</param> /// <remarks> /// This method needs to change based on your schema. For the MyDicomDb schema, we update all fields in the patient table /// <list> /// <item>PatientName</item> /// <item>PatientBirthday</item> /// <item>PatientSex</item> /// <item>PatientComments</item> /// </list> /// </remarks> private void FillPatientInformation(MyDataSet.MyPatientTableRow patient, DicomDataSet ds, MyDataSet instanceDataSet, string patientId, string retrieveAE, bool update) { try { // PatientName string patientName = ds.MyGetStringValue(DicomTag.PatientName, AutoTruncate, instanceDataSet.MyPatientTable.PatientNameColumn.MaxLength); if (CanSetValue(patientName, update, patient, instanceDataSet.MyPatientTable.PatientNameColumn)) { patient.PatientName = patientName; } // PatientBirthday DateTime?patientBirthDate = ds.MyGetDateTime(DicomTag.PatientBirthDate, DicomTag.PatientBirthTime); if (CanSetValue(patientBirthDate, update, patient, instanceDataSet.MyPatientTable.PatientBirthdayColumn)) { patient.PatientBirthday = patientBirthDate.Value; } // PatientSex char patientSex = ds.GetValue <char>(DicomTag.PatientSex, 'X'); string patientSexString = string.Empty; switch (patientSex) { case 'O': patientSexString = "O"; break; case 'M': patientSexString = "M"; break; case 'F': patientSexString = "F"; break; } if (CanSetValue(patientSex, update, patient, instanceDataSet.MyPatientTable.PatientSexColumn)) { patient.PatientSex = patientSexString; } // PatientComments string patientComments = ds.MyGetStringValue(DicomTag.PatientComments, AutoTruncate, instanceDataSet.MyPatientTable.PatientCommentsColumn.MaxLength); if (CanSetValue(patientComments, update, patient, instanceDataSet.MyPatientTable.PatientCommentsColumn)) { patient.PatientComments = patientComments; } } catch (Exception ex) { throw ex; } }
public DicomCommandStatusType OnNAction ( DicomClient client, byte presentationId, int messageID, string affectedClass, string instance, int action, DicomDataSet request, DicomDataSet response ) { try { string JobId = request.GetValue <string>(CustomTags.JobID, null); if (string.IsNullOrEmpty(JobId)) { throw new ArgumentException(); } JobsService.Instance.JobsQ.QeueJob(JobId); response = null; return(DicomCommandStatusType.Success); } catch (System.ArgumentException) { #region LOG { string message = @"Image Download - DownloadAddin::OnNAction (Invalid Argument)"; Logger.Global.Log(string.Empty, string.Empty, -1, string.Empty, string.Empty, -1, DicomCommandType.Undefined, DateTime.Now, LogType.Information, MessageDirection.None, message, null, null); } #endregion return(DicomCommandStatusType.InvalidArgumentValue); } catch (System.Exception e) { #region LOG { string message = @"Image Download - DownloadAddin::OnNAction: " + e.Message; Logger.Global.Log(string.Empty, string.Empty, -1, string.Empty, string.Empty, -1, DicomCommandType.Undefined, DateTime.Now, LogType.Information, MessageDirection.None, message, null, null); } #endregion return(DicomCommandStatusType.Failure); } }
public static void AddDefaultImages(Configuration configGlobalPacs) { ImageCountReset(); MainForm.StoreClientSessionProxy proxy = null; InstanceCStoreCommand cmd = null; IStorageDataAccessAgent agent = DataAccessFactory.GetInstance(new StorageDataAccessConfigurationView(configGlobalPacs, DicomDemoSettingsManager.ProductNameStorageServer, null)).CreateDataAccessAgent <IStorageDataAccessAgent>(); for (int i = 1; i < ImageCountResources + 1; i++) { using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format("CSPacsDatabaseConfigurationDemo.Resources.{0}.dcm", i))) { using (DicomDataSet ds = new DicomDataSet()) { ds.Load(stream, DicomDataSetLoadFlags.None); proxy = new MainForm.StoreClientSessionProxy(); cmd = new InstanceCStoreCommand(proxy, ds, agent); proxy.AffectedSOPInstance = ds.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty); proxy.AbstractClass = ds.GetValue <string>(DicomTag.SOPClassUID, string.Empty); ds.InsertElementAndSetValue(DicomTag.MediaStorageSOPInstanceUID, proxy.AffectedSOPInstance); cmd.Execute(); ImageCountUpdate(); } } } #if (LEADTOOLS_V19_OR_LATER) InsertDefaultImages("mg", ImageCountMG, configGlobalPacs); InsertDefaultImages("cr", ImageCountCR, configGlobalPacs); InsertDefaultImages("FMX18.de", ImageCountFMX, 2, configGlobalPacs); #endif #if (LEADTOOLS_V20_OR_LATER) InsertDefaultImages("MRI.mri_", ImageCountMRI, 2, configGlobalPacs); #endif }
public static DicomCommandStatusType Insert(DateTime receive, ServerInfo info, string AETitle, DicomDataSet dataset) { string sop = dataset.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty); DicomCommandStatusType status = DicomCommandStatusType.Success; if (!string.IsNullOrEmpty(sop)) { //string filename = info.ImageDirectory + sop + ".dcm"; string pid = string.Empty; string studyInstance = string.Empty; string seriesInstance = string.Empty; string sopInstance = string.Empty; pid = AddPatient(info.ConnectionString, AETitle, dataset); studyInstance = AddStudy(receive, pid, info.ConnectionString, AETitle, dataset); seriesInstance = AddSeries(receive, studyInstance, info.ConnectionString, AETitle, dataset); status = AddImage(receive, sop, studyInstance, seriesInstance, info.ConnectionString, AETitle, dataset, info.ImageDirectory + pid + @"\"); if (status == DicomCommandStatusType.Failure) { // remove patient, study, series, image information added to database if (_newImage) { DeleteImage(sop, info.ConnectionString); } if (_newSeries) { DeleteSeries(seriesInstance, info.ConnectionString); } if (_newStudy) { DeleteStudy(studyInstance, info.ConnectionString); } if (_newPatient) { DeletePatient(pid, info.ConnectionString); } } } else { throw new ArgumentException("Missing dicom tag", "SOP Instance UID"); } return(status); }
/// <summary> /// Adds the series. /// </summary> /// <param name="receive">The receive.</param> /// <param name="StudyInstanceUid">The study instance uid.</param> /// <param name="ConnectionString">The connection string.</param> /// <param name="AETitle">The AE title.</param> /// <param name="dataset">The dataset.</param> /// <returns></returns> private static string AddSeries(DateTime receive, string StudyInstanceUid, string ConnectionString, string AETitle, DicomDataSet dataset) { string seriesInstance = dataset.GetValue <string>(DicomTag.SeriesInstanceUID, string.Empty); if (string.IsNullOrEmpty(seriesInstance)) { throw new ArgumentException("Missing dicom tag", "Series Instance UID"); } _newSeries = false; if (!RecordExists(ConnectionString, "Series", "SeriesInstanceUID = '" + seriesInstance + "'")) { DateTime? sd = dataset.GetValue <DateTime?>(DicomTag.SeriesDate, null, GetDate); DateTime? st = dataset.GetValue <DateTime?>(DicomTag.SeriesTime, null, GetDate); SqlCeResultSet rs = SqlCeHelper.ExecuteResultSet(ConnectionString, "Series"); SqlCeUpdatableRecord series = rs.CreateRecord(); series.SetValue(0, seriesInstance); series.SetValue(1, dataset.GetValue <string>(DicomTag.Modality, string.Empty)); series.SetValue(2, dataset.GetValue <string>(DicomTag.SeriesNumber, string.Empty)); string seriesDate = GetDateString(sd, st); if (seriesDate.Length > 0) { series.SetValue(3, seriesDate); } series.SetValue(4, dataset.GetValue <string>(DicomTag.SeriesDescription, string.Empty)); series.SetValue(5, dataset.GetValue <string>(DicomTag.InstitutionName, string.Empty)); seriesDate = GetDateString(receive, receive); if (seriesDate.Length > 0) { series.SetValue(6, seriesDate); } series.SetValue(7, AETitle); series.SetValue(8, StudyInstanceUid); rs.Insert(series); rs.Close(); _newSeries = true; } return(seriesInstance); }
void CopyExistingElementsValues(DicomDataSet dsTarget, DicomDataSet dsSrc) { for (int nIndex = 0; nIndex < dsTarget.ModuleCount; nIndex++) { DicomModule dm = dsTarget.FindModuleByIndex(nIndex); foreach (DicomElement elementTarget in dm.Elements) { if (elementTarget.Length == 0) { DicomElement elementSrc = dsSrc.FindFirstElement(null, elementTarget.Tag, false); if (null != elementSrc) { dsTarget.SetValue(elementTarget, dsSrc.GetValue <object>(elementSrc, null)); } } } } }
/// <summary> /// Creates an xml layout file based on DICOM Structured display. /// </summary> /// <param name="ds">The ds.</param> /// <returns></returns> public static Layout ToLayout(this DicomDataSet ds) { StructuredDisplayImageBoxModule ibModule = new StructuredDisplayImageBoxModule(); Layout layout = null; ds.Get(ibModule); if (ibModule != null) { if (ibModule.StructuredDisplayImageBoxSequence.Count > 0 && ibModule.StructuredDisplayImageBoxSequence != null && ibModule.StructuredDisplayImageBoxSequence.Count > 0) { if (!(ibModule.StructuredDisplayImageBoxSequence.Count == 1 && ibModule.StructuredDisplayImageBoxSequence[0].DisplayEnvironmentSpatialPosition == null)) { layout = new Layout(); using (MemoryStream ms = new MemoryStream()) { layout.Icon = ""; layout.Name = ""; layout.TemplateId = ds.GetValue <string>(DicomTag.TemplateIdentifier, string.Empty); foreach (SDImageBox box in ibModule.StructuredDisplayImageBoxSequence) { if (box.DisplayEnvironmentSpatialPosition != null && box.DisplayEnvironmentSpatialPosition.Count == 4) { string referencedSOPInstanceUID = (box.ReferencedImageSequence != null && box.ReferencedImageSequence.Count > 0) ? box.ReferencedImageSequence[0].ImageSopInstanceReference.ReferencedSopInstanceUid : string.Empty; DataContracts.ImageBox imageBox = new DataContracts.ImageBox(referencedSOPInstanceUID); // // Top and bottom coordinates need to be switched. In DICOM the lower left is 0,0 in our viewer the lower left is 1,1 // imageBox.Position.leftTop = new LeadPointD(box.DisplayEnvironmentSpatialPosition[0], 1 - box.DisplayEnvironmentSpatialPosition[1]); imageBox.Position.rightBottom = new LeadPointD(box.DisplayEnvironmentSpatialPosition[2], 1 - box.DisplayEnvironmentSpatialPosition[3]); layout.Boxes.Add(imageBox); } } } } } } return(layout); }
public static DicomCommandStatusType Insert(DateTime receive, string ConnectionString, string ImageDirectory, string AETitle, DicomDataSet dataset) { string sop = dataset.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty); DicomCommandStatusType status = DicomCommandStatusType.Success; if (!string.IsNullOrEmpty(sop)) { //string filename = info.ImageDirectory + sop + ".dcm"; string pid = string.Empty; string studyInstance = string.Empty; string seriesInstance = string.Empty; string sopInstance = string.Empty; pid = AddPatient(ConnectionString, AETitle, dataset); studyInstance = AddStudy(receive, pid, ConnectionString, AETitle, dataset); seriesInstance = AddSeries(receive, studyInstance, ConnectionString, AETitle, dataset); status = AddImage(receive, sop, studyInstance, seriesInstance, ConnectionString, AETitle, dataset, ImageDirectory + pid + @"\"); } return(status); }
public static string FindElementModalitiesInStudy(DicomDataSet ds) { if (ds == null) { return(string.Empty); } string sRet = string.Empty; string sQueryModality = " (Studies.StudyInstanceUID in " + "(SELECT StudyInstanceUID " + " FROM Series " + " WHERE {0}))"; DicomElement element = ds.FindFirstElement(null, DicomTag.ModalitiesInStudy, false); if (element != null) { // Get a list of strings value of an element by specifying a tag string sEndQuery = string.Empty; List <string> modalitiesInStudy = ds.GetValue <List <string> >(DicomTag.ModalitiesInStudy, null); int count = 0; if (modalitiesInStudy != null) { foreach (string s in modalitiesInStudy) { if (count > 0) { sEndQuery = sEndQuery + " OR "; } sEndQuery = sEndQuery + string.Format("(Series.Modality = '{0}')", s); count++; } sRet = string.Format(sQueryModality, sEndQuery); } } return(sRet); }
public override void OnReceiveCStoreRequest(DicomClient Client, byte presentationID, int messageID, string affectedClass, string instance, DicomCommandPriorityType priority, string moveAE, int moveMessageID, DicomDataSet dataSet) { if (Module.Options.PatientRestrictEnabled) { string patientId = dataSet.GetValue <string>(DicomTag.PatientID, string.Empty); string aeTitle = Client.AETitle; string message = string.Format("OnReceiveCStoreRequest: PatientID[{0}], AeTitle[{1}]", patientId, aeTitle); Logger.Global.SystemMessage(LogType.Information, message); if (!string.IsNullOrEmpty(patientId)) { List <string> rolesList = Module.PatientRightsDataAccess.GetAeRoles(aeTitle); foreach (string role in rolesList) { message = string.Format("PatientID[{0}], Role[{1}]", patientId, role); Logger.Global.SystemMessage(LogType.Information, message); Module.PatientRightsDataAccess.GrantRoleAccess(patientId, role); } } } }
public Dictionary <string, DicomDataSet> GetSeriesDatasets(string[] instanceUIDs) { DataSet instances; Dictionary <string, DicomDataSet> dataSets = new Dictionary <string, DicomDataSet>(); instances = QuerySeries(instanceUIDs); foreach (DataRow row in instances.Tables[DataTableHelper.InstanceTableName].Rows) { DicomDataSet ds = new DicomDataSet(); string referencedFile = row.Field <string>("ReferencedFile"); string key; ds.Load(referencedFile, DicomDataSetLoadFlags.None); key = ds.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty); if (string.IsNullOrEmpty(key)) { key = Guid.NewGuid().ToString("N"); } dataSets.Add(key, ds); } return(dataSets); }
public override void OnReceiveCFindRequest(DicomClient Client, byte presentationID, int messageID, string affectedClass, DicomCommandPriorityType priority, DicomDataSet ds) { string patientId = ds.GetValue <string>(DicomTag.PatientID, string.Empty); if (Module.Options.SearchOtherPatientId && !patientId.IsNullOrEmpty()) { MyOtherPatientIds opid = new MyOtherPatientIds(); ds.Get(opid); if (opid.OtherPatientIds == null) { opid.OtherPatientIds = new List <string>(); } if (!opid.OtherPatientIds.Contains(patientId)) { opid.OtherPatientIds.Add(patientId); ds.Set(opid); Logger.Global.SystemMessage(LogType.Information, "CFind request dataset modified: PatientID added to OtherPatientIds", Client.AETitle, ds, null); } } base.OnReceiveCFindRequest(Client, presentationID, messageID, affectedClass, priority, ds); }
public void SetClientAction(string id, string action, string dataset) { lock (_listLock) { ActionInfo actionInfo = new ActionInfo(); if (!string.IsNullOrEmpty(dataset)) { MemoryStream stream = dataset.ToStream(); DicomDataSet ds = new DicomDataSet(); try { ds.LoadXml(stream, DicomDataSetLoadXmlFlags.None); if (action.Contains("C-FIND")) { string qr = ds.GetValue <string>(DicomTag.QueryRetrieveLevel, string.Empty); if (!string.IsNullOrEmpty(qr)) { action += " [" + qr + "]"; } } actionInfo.Dataset = ds; } catch (Exception e) { Debug.WriteLine(e.Message); } } actionInfo.Action = action; _ClientActions[id].Add(actionInfo); SetLastAction(id, action); } }
internal DicomCommandStatusType DoCStores(DicomClient Client, byte PresentationId, int MessageId, string AffectedClass, DicomCommandPriorityType Priority, DicomDataSet Request) { if (Request == null) { return(DicomCommandStatusType.InvalidArgumentValue); } try { string level = Request.GetValue <string> (DicomTag.QueryRetrieveLevel, string.Empty); DicomCommandStatusType status = Module.GetAttributeStatus(level, AffectedClass, Request); if (status != DicomCommandStatusType.Success) { return(status); } switch (level.ToUpper( )) { case "PATIENT": case "STUDY": case "SERIES": case "IMAGE": status = DB.MoveImages(this, level, AffectedClass, Module.ConnectionString, Request); break; default: return(DicomCommandStatusType.InvalidAttributeValue); } return(status); } catch { return(DicomCommandStatusType.ProcessingFailure); } }
public static DicomDataSet GeneratePresentationState(string seriesInstanceUID, string annotationData, string description, DicomDataSet seriesDs, int windowCenter, int windowWidth, out string sopInstanceUID) { AnnCodecs codec = new AnnCodecs(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(annotationData))) { ms.Position = 0; AnnCodecsInfo codecInfo = codec.GetInfo(ms); ms.Position = 0; JavaScriptSerializer jsSerialzer = new JavaScriptSerializer(); DicomAnnotationsUtilities dicomAnnotationsUtilities = new DicomAnnotationsUtilities(); DicomDataSet ds = new DicomDataSet(); sopInstanceUID = SeriesGenerator.GenerateDicomUniqueIdentifier(); //Patient Module C.7.1.1 ds.InsertElementAndSetValue(DicomTag.PatientName, seriesDs.GetValue <string>(DicomTag.PatientName, string.Empty)); ds.InsertElementAndSetValue(DicomTag.PatientID, seriesDs.GetValue <string>(DicomTag.PatientID, string.Empty)); ds.InsertElementAndSetValue(DicomTag.PatientBirthDate, ""); ds.InsertElementAndSetValue(DicomTag.PatientSex, ""); //Study Module C.7.2.1 ds.InsertElementAndSetValue(DicomTag.StudyInstanceUID, seriesDs.GetValue <string>(DicomTag.StudyInstanceUID, string.Empty)); ds.InsertElementAndSetValue(DicomTag.StudyDate, ""); ds.InsertElementAndSetValue(DicomTag.StudyTime, ""); ds.InsertElementAndSetValue(DicomTag.ReferringPhysicianName, ""); ds.InsertElementAndSetValue(DicomTag.StudyID, seriesDs.GetValue <string>(DicomTag.StudyID, string.Empty)); ds.InsertElementAndSetValue(DicomTag.AccessionNumber, seriesDs.GetValue <string>(DicomTag.AccessionNumber, string.Empty)); //Series Module C.7.3.1 ds.InsertElementAndSetValue(DicomTag.SeriesInstanceUID, SeriesGenerator.GenerateDicomUniqueIdentifier()); ds.InsertElementAndSetValue(DicomTag.Modality, "PR"); ds.InsertElementAndSetValue(DicomTag.SeriesNumber, 1); ds.InsertElementAndSetValue(DicomTag.SeriesDate, DicomDateValue.Now); ds.InsertElementAndSetValue(DicomTag.SeriesTime, DicomTimeValue.Now); ds.InsertElementAndSetValue(DicomTag.SeriesDescription, "Study layout presentation state"); //General Equipment Module C.7.5.1 ds.InsertElementAndSetValue(DicomTag.Manufacturer, "LEADTOOLS IMAGING"); ds.InsertElementAndSetValue(DicomTag.InstitutionName, "LEADTOOLS, INC."); ds.InsertElementAndSetValue(DicomTag.StationName, "HTML5 Viewer"); //Presentation State Identification Module C.11.10 ds.InsertElementAndSetValue(DicomTag.PresentationCreationDate, DicomDateValue.Now); ds.InsertElementAndSetValue(DicomTag.PresentationCreationTime, DicomTimeValue.Now); //Content Identification Macro Table 10-12 ds.InsertElementAndSetValue(DicomTag.InstanceNumber, 1); ds.InsertElementAndSetValue(DicomTag.ContentLabel, "STUDY LAYOUT PRESENTATION"); ds.InsertElementAndSetValue(DicomTag.ContentDescription, description); //ds.InsertElementAndSetValue(DicomTag.ContentCreatorName, userName); //Presentation State RelationShip Module C11.11 PresentationStateRelationShip referncedSeriesSeq = new PresentationStateRelationShip(); referncedSeriesSeq.ReferencedSeriesSequence = new List <ReferencedSeries>(); ReferencedSeries referencedSeries = new ReferencedSeries(); referencedSeries.SeriesInstanceUID = seriesInstanceUID; referencedSeries.ReferencedImageSequence = new List <SopInstanceReference>(); referncedSeriesSeq.ReferencedSeriesSequence.Add(referencedSeries); Dictionary <LeadSize, List <ImageSopInstanceReference> > displayedAreaInstance = new Dictionary <LeadSize, List <ImageSopInstanceReference> >(); for (int index = 0; index < codecInfo.Pages.Length; index++) { AnnContainer container = codec.Load(ms, codecInfo.Pages[index]); ms.Position = 0; if (null == container.UserData) { continue; } AnnUserData refInstance = (AnnUserData)jsSerialzer.Deserialize <AnnUserData>(container.UserData.ToString()); if (null != refInstance && null != refInstance.ReferencedImageSequence) { referncedSeriesSeq.ReferencedSeriesSequence[0].ReferencedImageSequence.Add(refInstance.ReferencedImageSequence); // The Medical Viewer defaults dpi to 150 // In this case, there is enough information to compute the dpi, which should be 150 //double dpiX = 0; //double dpiY = 0; //container.CalculateDpi(out dpiX, out dpiY); //if (dpiX == 0 || dpiY == 0) //{ // dpiX = 150.0; // dpiY = 150.0; //} double xDpi = 150; double yDpi = 150; dicomAnnotationsUtilities.ImageDpiX = xDpi; dicomAnnotationsUtilities.ImageDpiY = yDpi; DicomElement graphicSequenceItem = dicomAnnotationsUtilities.FromAnnContainerToDataSet(ds, container); DicomElement layerElement = ds.FindFirstElement(graphicSequenceItem, DicomTag.GraphicLayer, false); if (null == layerElement) { ds.InsertElementAndSetValue(graphicSequenceItem, true, DicomTag.GraphicLayer, "LAYER1"); } else { ds.SetStringValue(layerElement, "LAYER1", DicomCharacterSetType.Default); } GraphicAnnotationsModule annModule = new GraphicAnnotationsModule(); annModule.ReferencedImageSequence = new List <ImageSopInstanceReference>(); annModule.ReferencedImageSequence.Add(refInstance.ReferencedImageSequence); ds.Set(graphicSequenceItem, annModule); } if (!refInstance.ImageSize.IsEmpty) { if (!displayedAreaInstance.ContainsKey(refInstance.ImageSize)) { displayedAreaInstance[refInstance.ImageSize] = new List <ImageSopInstanceReference>(); } displayedAreaInstance[refInstance.ImageSize].Add(refInstance.ReferencedImageSequence); } } ds.Set(referncedSeriesSeq); //Displayed Area Module // // DisplayedAreaModule displayedAreaModule = new DisplayedAreaModule(); displayedAreaModule.DisplayedAreaSelection = new List <DisplayedAreaSelection>(); foreach (KeyValuePair <LeadSize, List <ImageSopInstanceReference> > areaInstance in displayedAreaInstance) { DisplayedAreaSelection displayedArea = new DisplayedAreaSelection(); displayedAreaModule.DisplayedAreaSelection.Add(displayedArea); displayedArea.DisplayedAreaTopLeftHandCorner = new List <long>(); displayedArea.DisplayedAreaBottomRightHandCorner = new List <long>(); displayedArea.DisplayedAreaTopLeftHandCorner.Add(1); displayedArea.DisplayedAreaTopLeftHandCorner.Add(1); displayedArea.DisplayedAreaBottomRightHandCorner.Add(areaInstance.Key.Width); displayedArea.DisplayedAreaBottomRightHandCorner.Add(areaInstance.Key.Height); displayedArea.PresentationSizeMode = PresentationSizeMode.ScaleToFit; displayedArea.PresentationPixelAspectRatio = new List <int>(); displayedArea.PresentationPixelAspectRatio.Add(1); displayedArea.PresentationPixelAspectRatio.Add(1); if (displayedAreaInstance.Count > 1) { displayedArea.ReferencedImageSequence = areaInstance.Value; } } ds.Set(displayedAreaModule); //Graphic Layer Module GraphicLayerModule graphicLayerModule = new GraphicLayerModule(); GraphicLayer layer = new GraphicLayer(); graphicLayerModule.GraphicLayerSequence = new List <GraphicLayer>(); layer.GraphicLayerName = "LAYER1"; layer.GraphicLayerOrder = 1; graphicLayerModule.GraphicLayerSequence.Add(layer); ds.Set(graphicLayerModule); //Softcopy Presentation LUT Module SoftCopyPresentationLutModule presentationLut = new SoftCopyPresentationLutModule(); presentationLut.PresentationLutShape = PresentationLutShape.Identity; if (windowCenter != -1 || windowWidth != -1) { SoftCopyVoiLutModule module = new SoftCopyVoiLutModule(); module.WindowCenter = new List <double>(); module.WindowCenter.Add(windowCenter); module.WindowWidth = new List <double>(); module.WindowWidth.Add(windowWidth); ds.Set(module); } ds.Set(presentationLut); //SOP Common Module ds.InsertElementAndSetValue(DicomTag.SOPClassUID, DicomUidType.GrayscaleSoftcopyPresentationStateStorage); ds.InsertElementAndSetValue(DicomTag.SOPInstanceUID, sopInstanceUID); ds.InsertElementAndSetValue(DicomTag.InstanceCreationDate, DicomDateValue.Now); ds.InsertElementAndSetValue(DicomTag.InstanceCreationTime, DicomDateValue.Now); ds.InsertElementAndSetValue(DicomTag.InstanceNumber, 1); return(ds); } }
public DicomDataSet GenerateDerivedInstance ( DicomDataSet original, RasterImage derivedImage, string seriesDescription, string seriesNumber, string protocolName, string userName ) { string sopInstanceUID = GenerateDicomUniqueIdentifier(); string seriesInstancUID = GenerateDicomUniqueIdentifier(); PreProcessBitmap(derivedImage); DicomDataSet derivedDataSet = Duplicate(original, derivedImage); if (!string.IsNullOrEmpty(seriesDescription)) { derivedDataSet.InsertElementAndSetValue(DicomTag.SeriesDescription, seriesDescription); } if (!string.IsNullOrEmpty(seriesInstancUID)) { derivedDataSet.InsertElementAndSetValue(DicomTag.SeriesInstanceUID, seriesInstancUID); } if (string.IsNullOrEmpty(sopInstanceUID)) { throw new InvalidOperationException("SOP Instance UID can't be empty."); } if (!string.IsNullOrEmpty(seriesNumber)) { derivedDataSet.InsertElementAndSetValue(DicomTag.SeriesNumber, seriesNumber); } if (!string.IsNullOrEmpty(protocolName)) { derivedDataSet.InsertElementAndSetValue(DicomTag.ProtocolName, protocolName); } derivedDataSet.InsertElementAndSetValue(DicomTag.SeriesDate, original.GetValue <string>(DicomTag.SeriesDate, string.Empty)); derivedDataSet.InsertElementAndSetValue(DicomTag.SeriesTime, original.GetValue <string>(DicomTag.SeriesTime, string.Empty)); derivedDataSet.InsertElementAndSetValue(DicomTag.InstanceCreationDate, DateTime.Now); derivedDataSet.InsertElementAndSetValue(DicomTag.InstanceCreationTime, DateTime.Now); derivedDataSet.InsertElementAndSetValue(DicomTag.ContentDate, DateTime.Now); derivedDataSet.InsertElementAndSetValue(DicomTag.ContentTime, DateTime.Now); derivedDataSet.InsertElementAndSetValue(DicomTag.DateOfSecondaryCapture, DateTime.Now); derivedDataSet.InsertElementAndSetValue(DicomTag.TimeOfSecondaryCapture, DateTime.Now); derivedDataSet.InsertElementAndSetValue(DicomTag.SOPInstanceUID, sopInstanceUID); derivedDataSet.InsertElementAndSetValue(DicomTag.MediaStorageSOPInstanceUID, sopInstanceUID); derivedDataSet.InsertElementAndSetValue(DicomTag.OperatorName, userName); derivedDataSet.InsertElementAndSetValue(DicomTag.ConversionType, "WSD"); derivedDataSet.InsertElementAndSetValue(DicomTag.Modality, "OT"); derivedDataSet.InsertElementAndSetValue(DicomTag.InstanceNumber, GetInstanceNumber(derivedDataSet) + 1); derivedDataSet.InsertElementAndSetValue(DicomTag.ImageType, "DERIVED\\SECONDARY"); return(derivedDataSet); }
private void LoadImage(object data) { DicomDataSet ds = data as DicomDataSet; int count = 0; RasterImage image = null; if (Dataset == null) { Cell.Image = null; return; } bool isStructuredDisplay = IsStructuredDisplay(ds); DicomElement pixelData = ds.FindFirstElement(null, DicomTag.PixelData, true); if (pixelData == null) { if (isStructuredDisplay) { count = 1; } } else { count = ds.GetImageCount(pixelData); } SetLoadProgress(count > 0, count); string exceptionMessage = string.Empty; for (int i = 0; i < count; i++) { RasterImage img = null; try { if (pixelData != null) { img = ds.GetImage(pixelData, i, 0, RasterByteOrder.Rgb | RasterByteOrder.Gray, DicomGetImageFlags.AutoApplyModalityLut | DicomGetImageFlags.AutoApplyVoiLut | DicomGetImageFlags.AutoScaleModalityLut | DicomGetImageFlags.AutoScaleVoiLut | DicomGetImageFlags.AutoDetectInvalidRleCompression); } else if (isStructuredDisplay) { StructuredDisplayImageOptions sdOptions = new StructuredDisplayImageOptions(); sdOptions.ShowOverlay = _optionsAgent.Get <bool>("ExportLayoutIncludeMetadata", true); DicomGetImageFlags getImageFlags = DicomGetImageFlags.AutoScaleModalityLut | DicomGetImageFlags.AutoScaleVoiLut | DicomGetImageFlags.AutoApplyModalityLut | DicomGetImageFlags.AutoApplyVoiLut; img = ds.GetStructuredDisplayImage(GetSopInstanceCallBack, getImageFlags, sdOptions);; } } catch (Exception ex) { exceptionMessage = ex.Message; } if (img != null) { if (image == null) { image = img.Clone(); } else { image.AddPage(img); } } SetProgressValue(i + 1); Thread.Sleep(0); } string photometricInterpretation = GetDicomTag(ds, DicomTag.PhotometricInterpretation); if (!string.IsNullOrEmpty(photometricInterpretation)) { Cell.PhotometricInterpretation = photometricInterpretation; } SetCellInfo(image, ds.GetValue <string>(DicomTag.PatientID, string.Empty), ds.GetValue <string>(DicomTag.PatientName, string.Empty), ds.GetValue <string>(DicomTag.WindowWidth, string.Empty), ds.GetValue <string>(DicomTag.WindowCenter, string.Empty), isStructuredDisplay); if (!string.IsNullOrEmpty(exceptionMessage)) { string errorMessage = string.Format("Failed to show image.\n{0}", exceptionMessage); if (count > 1) { errorMessage = string.Format("Failed to load one or more image frames.\n{0}", exceptionMessage); } Messager.ShowError(this, errorMessage); } }