Exemplo n.º 1
0
        public void LoadPInfor(DicomDataSet ds)
        {
            try
            {
                this.ds = ds;
                dtPInfor = InitTableStructure();
                if (ds != null)
                {
                    AddRow("Mã BN(PatientID)", Leadtools.Dicom.DicomTag.PatientID);
                    AddRow("Tên BN(PatientName)", Leadtools.Dicom.DicomTag.PatientName);
                    AddRow("Tuổi(Age)", Leadtools.Dicom.DicomTag.PatientAge);
                    AddRow("Giới tính(Sex)", Leadtools.Dicom.DicomTag.PatientSex);
                    AddRow("Địa chỉ(Address)", Leadtools.Dicom.DicomTag.PatientAddress);
                    AddRow("Ngày sinh(BOD)", Leadtools.Dicom.DicomTag.PatientBirthDate);
                    AddRow("Giờ sinh(BOT)", Leadtools.Dicom.DicomTag.PatientBirthTime);
                    AddRow("Số đăng ký(Reg Sequence)", Leadtools.Dicom.DicomTag.RegistrationSequence);
                    AddRow("Modality", Leadtools.Dicom.DicomTag.Modality);
                }
                //Set datasource for datagridView
                Utility.SetDataSourceForDataGridView(grdList, dtPInfor, false, true, "1=1", "");

            }
            catch (Exception ex)
            {
                Utils.ShowMsg("Lỗi khi load thông tin ảnh:\n" + ex.Message, "Thông báo");
            }
        }
Exemplo n.º 2
0
        private bool LoadDicomFile(string file)
        {
            bool ret = true;

            try
            {
                using (DicomDataSet ds = new DicomDataSet())
                {
                    ds.Load(file, DicomDataSetLoadFlags.None);
                    DicomCommandStatusType status = DB.Insert(DateTime.Now, Module.ServerInfo, "TEST_AE", ds);
                    if (status != DicomCommandStatusType.Success)
                    {
                        ret = false;
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(this, e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ret = false;
            }
            return(ret);
        }
Exemplo n.º 3
0
        public static void SaveJsonFile(DicomDataSet ds, DicomDataSetSaveJsonFlags jsonFlags)
        {
            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Filter       = "JSON File(*.json)|*.json|All files (*.*)|*.*";
                saveFileDialog.AddExtension = true;
                saveFileDialog.Title        = "Save 'DICOM JSON Model' File";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        ds.SaveJson(saveFileDialog.FileName, jsonFlags);
                    }
                    catch (DicomException de)
                    {
                        string err = string.Format("Error saving dicom dataset!\r\n\r\n{0}", de.Code.ToString());

                        MessageBox.Show(err, "Error");
                        return;
                    }
                }
            }
        }
Exemplo n.º 4
0
        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);
        }
        static void FindChildElements(DicomDataSet ds, DicomElement element, long tag, List <DicomElement> elemLst)
        {
            if (null != element)
            {
                DicomElement child = ds.GetChildElement(element, true);
                if (child != null)
                {
                    if (child.Tag == tag)
                    {
                        elemLst.Add(child);
                    }

                    FindChildElements(ds, child, tag, elemLst);
                    child = ds.GetNextElement(child, true, true);

                    while (child != null)
                    {
                        FindChildElements(ds, child, tag, elemLst);
                        child = ds.GetNextElement(child, true, true);
                    }
                }
            }
        }
Exemplo n.º 6
0
        protected override void OnReceiveCStoreRequest(byte presentationID, int messageID, string affectedClass,
                                                       string instance, DicomCommandPriorityType priority, string moveAE, int moveMessageID, DicomDataSet dataSet)
        {
            DicomDataSet ds = new DicomDataSet();

            server.cfind.ResetTimeoutEvent.Set();

            server.cfind.InvokeStatusEvent(StatusType.ReceiveCStoreRequest, DicomExceptionCode.Success);
            if (dataSet == null)
            {
                SendCStoreResponse(presentationID, messageID, affectedClass, instance,
                                   DicomCommandStatusType.ProcessingFailure);
                return;
            }

            ds.Copy(dataSet, null, null);
            server.dsCollection.Add(ds);

            server.cfind.InvokeStatusEvent(StatusType.SendCStoreResponse, DicomExceptionCode.Success);
            SendCStoreResponse(presentationID, messageID, affectedClass, instance, DicomCommandStatusType.Success);

            dataSet.Dispose();
        }
Exemplo n.º 7
0
        public static TimeSpan?MyGetTime(this DicomDataSet ds, long dicomTime)
        {
            TimeSpan?    timeValue = null;
            DicomElement element   = null;

            if (dicomTime != 0)
            {
                element = ds.FindFirstElement(null, dicomTime, true);
            }

            if (null == element || element.Length == 0)
            {
                timeValue = null;
            }
            else
            {
                byte[] timeByte   = ds.GetBinaryValue(element, (int)element.Length);
                string timeString = System.Text.ASCIIEncoding.ASCII.GetString(timeByte);

                DateTime time;

                if (timeString.Length > 6)
                {
                    timeString = timeString.Substring(0, 6);
                }
                else if (timeString.Length < 6)
                {
                    timeString = timeString.PadRight(6, '0');
                }

                if (!string.IsNullOrEmpty(timeString) && DateTime.TryParseExact(timeString, "HHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out time))
                {
                    timeValue = new TimeSpan(time.Hour, time.Minute, time.Second, time.Millisecond);
                }
            }
            return(timeValue);
        }
Exemplo n.º 8
0
        public override DicomDirInsertFileCommand OnInsertFile(string fileName, DicomDataSet ds, DicomDirInsertFileStatus status, DicomExceptionCode code)
        {
            if (MainForm.cancel)
            {
                SetStatus("Cancelled");
                return(DicomDirInsertFileCommand.Stop);
            }
            if (status == DicomDirInsertFileStatus.PreAdd)
            {
                // About to add the DICOM file
                if (ds.InformationClass == DicomClassType.BasicDirectory)
                {
                    return(DicomDirInsertFileCommand.Skip);
                }
                SetStatus(string.Format("Status: Adding the file \"{0}\"", fileName));
            }
            else if (status == DicomDirInsertFileStatus.Success)
            {
                // The DICOM file has been added successfully
                m_nAddedDicomFilesCount++;
            }
            else // Failure
            {
                DialogResult dlgRes = MessageBox.Show("Invalid File Id: " + fileName + "\n Do you want to skip this file and continue?", "Error", MessageBoxButtons.YesNo);
                if (dlgRes == DialogResult.Yes)
                {
                    return(DicomDirInsertFileCommand.Skip);
                }
                else
                {
                    return(DicomDirInsertFileCommand.Stop);
                }
            }

            Application.DoEvents();
            return(DicomDirInsertFileCommand.Continue);
        }
Exemplo n.º 9
0
        private static DicomDataSet GetFirstReferencedInstanceDataSet
        (
            IStorageDataAccessAgent dataAccess,
            MediaCreationManagement mediaObject)
        {
            MatchingParameterCollection matchingCollection;
            MatchingParameterList       matchingList;
            CompositeInstanceDataSet    compositeInstance;


            matchingCollection = new MatchingParameterCollection( );
            matchingList       = new MatchingParameterList( );
            // Instance instance           = new Instance ( mediaObject.ReferencedSopSequence [ 0 ].SopInstance.ReferencedSopInstanceUid ) ;
            ICatalogEntity instance = RegisteredEntities.GetInstanceEntity(mediaObject.ReferencedSopSequence [0].SopInstance.ReferencedSopInstanceUid);


            matchingCollection.Add(matchingList);
            matchingList.Add(instance);

            compositeInstance = dataAccess.QueryCompositeInstances(matchingCollection).ToCompositeInstanceDataSet();

            if (compositeInstance.Instance.Count > 0)
            {
                DicomDataSet ds;


                ds = new DicomDataSet( );

                ds.Load(compositeInstance.Instance [0].ReferencedFile, DicomDataSetLoadFlags.None);

                return(ds);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 10
0
        public InsertReturn Insert(DicomDataSet dcm, string filename)
        {
            string       patientID;
            string       studyInstanceUID;
            string       seriesInstanceUID;
            string       sopInstanceUID;
            InsertReturn ret = InsertReturn.Success;

            patientID = AddPatient(dcm, ref ret);
            if (ret != InsertReturn.Success && ret != InsertReturn.Exists)
            {
                return(ret);
            }

            studyInstanceUID  = AddStudy(dcm, patientID, ref ret);
            seriesInstanceUID = AddSeries(dcm, studyInstanceUID, patientID, ref ret);
            sopInstanceUID    = AddImage(dcm, seriesInstanceUID, studyInstanceUID, patientID, filename, ref ret);

            if (ret == InsertReturn.Success)
            {
                Save();
            }
            return(ret);
        }
Exemplo n.º 11
0
        /*
         * Sets the Instance Numbers for this dataset
         */
        private void SetInstanceNumbers(ref DicomDataSet pDS, int nInstanceNumber)
        {
            DicomElement element;
            string       strValue;

            strValue = string.Format("{0}", nInstanceNumber);

            // Series number
            element = pDS.FindFirstElement(null, DemoDicomTags.SeriesNumber, false);
            if (element != null)
            {
                pDS.SetConvertValue(element, strValue, 1);
            }

            // Instance number
            element = pDS.FindFirstElement(null, DemoDicomTags.InstanceNumber, false);
            if (element != null)
            {
                pDS.SetConvertValue(element, strValue, 1);
            }

            // Study ID
            element = pDS.FindFirstElement(null, DemoDicomTags.StudyID, false);
            if (element != null)
            {
                pDS.SetConvertValue(element, strValue, 1);
            }

            strValue = string.Format("854125{0}", nInstanceNumber);
            // Accession number
            element = pDS.FindFirstElement(null, DemoDicomTags.AccessionNumber, false);
            if (element != null)
            {
                pDS.SetConvertValue(element, strValue, 1);
            }
        }
Exemplo n.º 12
0
        /*
         * Sets the necessary UIDs in the Dataset
         */
        private void SetInstanceUIDs(ref DicomDataSet pDS)
        {
            DicomElement element;

            // Set STUDY INSTANCE UID
            element = pDS.FindFirstElement(null, DemoDicomTags.StudyInstanceUID, false);
            if (element == null)
            {
                element = pDS.InsertElement(null, false, DemoDicomTags.StudyInstanceUID, DicomVRType.UI, false, 0);
            }
            pDS.SetConvertValue(element, Utils.GenerateDicomUniqueIdentifier(), 1);

            // Set SERIES INSTANCE UID
            element = pDS.FindFirstElement(null, DemoDicomTags.SeriesInstanceUID, false);
            if (element == null)
            {
                element = pDS.InsertElement(null, false, DemoDicomTags.SeriesInstanceUID, DicomVRType.UI, false, 0);
            }
            pDS.SetConvertValue(element, Utils.GenerateDicomUniqueIdentifier(), 1);

            // Set SOP INSTANCE UID
            element = pDS.FindFirstElement(null, DemoDicomTags.SOPInstanceUID, false);
            if (element == null)
            {
                element = pDS.InsertElement(null, false, DemoDicomTags.SOPInstanceUID, DicomVRType.UI, false, 0);
            }
            pDS.SetConvertValue(element, Utils.GenerateDicomUniqueIdentifier(), 1);

            // Media Storage SOP Instance UID
            element = pDS.FindFirstElement(null, DemoDicomTags.MediaStorageSOPInstanceUID, false);
            if (element == null)
            {
                element = pDS.InsertElement(null, false, DemoDicomTags.MediaStorageSOPInstanceUID, DicomVRType.UI, false, 0);
            }
            pDS.SetConvertValue(element, Utils.GenerateDicomUniqueIdentifier(), 1);
        }
Exemplo n.º 13
0
        /*
         * Copies the data from one element to another.
         */
        bool CopyElementData(DicomElement DstElement, DicomElement SrcElement, DicomDataSet SrcDS)
        {
            try
            {
                if ((DstElement == null) || (SrcElement == null) || (SrcDS == null))
                {
                    return(false);
                }

                if ((SrcElement.Length == 0) || (SrcElement.Length == ELEMENT_LENGTH_MAX) || (DstElement.Length == ELEMENT_LENGTH_MAX))
                {
                    return(false);
                }

                byte[] BinaryValue = SrcDS.GetBinaryValue(SrcElement, (int)SrcElement.Length);
                SrcDS.SetBinaryValue(DstElement, BinaryValue, (int)SrcElement.Length);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
            }

            return(true);
        }
Exemplo n.º 14
0
        private void SaveDicomAnnotations(string datasetFileName)
        {
            if ((_dsImage != null))
            {
                _dicomAnnotationsUtilities.DisplayWidth  = _viewer.Image.Width;
                _dicomAnnotationsUtilities.DisplayHeight = _viewer.Image.Height;

                SetPresentationStateInfo();

                DicomDataSet ds = new DicomDataSet();
                _dicomAnnotationsUtilities.FromAnnContainerToDataSet(ds, _automation.Container, _dsImage, string.Empty, string.Empty);

                string DirectoryName = Path.GetDirectoryName(datasetFileName);
                string fileName      = Path.GetFileNameWithoutExtension(datasetFileName) + ".pre";
                try
                {
                    ds.Save(Path.Combine(DirectoryName, fileName), DicomDataSetSaveFlags.None);
                }
                catch (Exception ex)
                {
                    Messager.ShowError(this, ex.Message);
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Adds a new row to the DataSet Study Table (MyInstanceTable) if the DicomDataSet SOPInstanceUID does not already exist
        /// </summary>
        /// <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="updateExistentPatient">If 'true', update the existing patient with information from dicomDataSet</param>
        /// <param name="referencedFileName">Full path of the DICOM file</param>
        /// <param name="retrieveAe">retrieveAe">AE Title of the client doing the retrieval</param>
        private void FillInstancetData(DicomDataSet ds, MyDataSet instanceDataSet, bool updateExistentInstance, string referencedFileName, string retrieveAe)
        {
            string sopInstanceUID = ds.MyGetStringValue(DicomTag.SOPInstanceUID, AutoTruncate, instanceDataSet.MyInstanceTable.SOPInstanceUIDColumn.MaxLength);

            if (null == sopInstanceUID /*|| null == seriesInstanceUID*/)
            {
                return;
            }

            MyDataSet.MyInstanceTableRow instanceRow = null;
            DataRow[] rows = instanceDataSet.MyInstanceTable.Select(string.Format("SOPInstanceUID = '{0}'", sopInstanceUID));
            MyDataSet.MyInstanceTableRow[] seriesRows = (MyDataSet.MyInstanceTableRow[])rows;

            bool instanceFound = (null != instanceRow);

            if (!instanceFound)
            {
                instanceRow = instanceDataSet.MyInstanceTable.NewMyInstanceTableRow();

                instanceRow.SOPInstanceUID = sopInstanceUID;

                instanceDataSet.MyInstanceTable.AddMyInstanceTableRow(instanceRow);
            }
            else if (!updateExistentInstance)
            {
                return;
            }

            FillInstanceInformation(instanceRow,
                                    ds,
                                    instanceDataSet,
                                    sopInstanceUID,
                                    retrieveAe,
                                    referencedFileName,
                                    updateExistentInstance);
        }
Exemplo n.º 16
0
        public void LogCS(Client client, DicomDataSet ds)
        {
            UserInfo ui;

            ui = mf.UsersData.LoadUser(client.PeerAddress, client.Association.Calling);
            if (ui != null)
            {
                string dir = GetLogDir(client.Association.Calling);
                string file;
                string command;

                //
                // File name is of the following form for command sets.
                //  cs.hNet-Command-UniqueId.dcm
                //

                command = ds.InformationCommand.ToString();
                command = command.Remove(0, command.IndexOf("_") + 1);
                command = command.Replace("_", "-");
                file    = dir + "cs." + client.Association.Calling + "-" + command + "-REQ";
                file   += "-" + Environment.TickCount.ToString() + ".dcm";
                ds.Save(file, DicomDataSetSaveFlags.None);
            }
        }
Exemplo n.º 17
0
        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);
            }
        }
Exemplo n.º 18
0
        public static string Execute(DicomDataSet ds, string code, string directory, out bool hasErrors, out int count)
        {
            string          script   = _Class.Replace("<code>", code);
            CompilerResults results  = _Compiler.CompileAssemblyFromSource(_Parameters, script);
            Assembly        assembly = null;

            count     = 0;
            hasErrors = false;
            Directory = directory;
            if (results.Errors.HasErrors)
            {
                foreach (CompilerError error in results.Errors)
                {
                    string message = string.Format("{0} ({1},{2})", error.ErrorText, error.Line - DefaultLines + 1, error.Column);

                    MessageBox.Show(message);
                }
                hasErrors = true;
                return(null);
            }

            assembly = results.CompiledAssembly;
            object o = assembly.CreateInstance("LinqScript.LinqCompiler");

            try
            {
                IQueryable query = o.GetType().InvokeMember("GetResults", BindingFlags.InvokeMethod, null, o, new object[] { ds }) as IQueryable;

                return(ConvertToHtml(query, out count));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return(null);
        }
Exemplo n.º 19
0
        public DicomCommandStatusType OnMove
        (
            DicomClient client,
            byte presentationId,
            int messageId,
            string affectedClass,
            DicomCommandPriorityType priority,
            string moveAE,
            DicomDataSet request
        )
        {
            try
            {
                _messageId      = messageId;
                _presentationId = presentationId;
                _clientSession  = new ClientSession(client);

                CMoveClientSessionProxy sessionProxy = new CMoveClientSessionProxy(_clientSession, presentationId, messageId, affectedClass);
                DicomCommand            command      = new CustomCMoveCommand(sessionProxy, request);


                _clientSession.CMoveStoreSubOperation += new EventHandler <CMoveStoreSubOperationEventArgs>(_clientSession_CMoveStoreSubOperation);
                _clientSession.CMoveResponse          += new EventHandler <CMoveResponseEventArgs>(_clientSession_CMoveResponse);

                _clientSession.ProcessCMoveRequest(presentationId, messageId, affectedClass, priority, command).WaitOne( );

                return(_status);
            }
            finally
            {
                if (request != null)
                {
                    request.Dispose( );
                }
            }
        }
Exemplo n.º 20
0
        public override void OnSendCMoveResponse(DicomClient Client, byte presentationID, int messageID, string affectedClass,
                                                 DicomCommandStatusType status, int remaining, int completed, int failed,
                                                 int warning, DicomDataSet dataset)
        {
            if (!Module.Options.EnableAutoCopy)
            {
                return;
            }

            //
            // Only do auto copy if the move command was successfull
            //
            if (status == DicomCommandStatusType.Success)
            {
                string key = Client.HostAddress + Client.HostPort.ToString();

                if (AutoCopyEngine.MoveRequests.ContainsKey(key))
                {
                    string ae = AutoCopyEngine.MoveRequests[key];

                    AutoCopyEngine.QueueDatasets(ae);
                }
            }
        }
Exemplo n.º 21
0
      public static byte[] GetBinaryValues(DicomDataSet dcm, long tag)
      {
         DicomElement element;

         element = dcm.FindFirstElement(null, tag, true);
         if(element != null)
         {
            if(element.Length > 0)
            {
               return dcm.GetBinaryValue(element, (int)element.Length);
            }
         }

         return null;
      }
Exemplo n.º 22
0
 public static StringCollection GetStringValues(DicomDataSet dcm, DicomTagType tag)
 {
    return GetStringValues(dcm, (long)tag);
 }
Exemplo n.º 23
0
 void AutoUpdatePatientInforInDcmFile_DemoMode(string Folder2Changed, string fileName, string PID, string PName, string pAge, string pSex, string StudyInstanceUID, string SeriesInstanceUID, string SOPInstanceUID)
 {
     try
     {
             //Thực hiện duyệt các file Dicom ko có chữ IDX
             string[] files = Directory.GetFiles(Folder2Changed);
             foreach (string _fileName in files)
             {
                 if (_fileName.ToUpper().Trim()== fileName.ToUpper().Trim() && Path.GetExtension(_fileName).Trim().Contains("DCM") && !Path.GetExtension(_fileName).Trim().Contains("_IDX"))
                 {
                     try
                     {
                         using (DicomDataSet ds = new DicomDataSet())
                         {
                             ds.Load(_fileName, DicomDataSetLoadFlags.LoadAndClose);
                             Leadtools.DicomDemos.Utils.SetTag(ds, DicomTag.PatientID, PID, true);
                             Leadtools.DicomDemos.Utils.SetTag(ds, DicomTag.Modality, modTypeCode, true);
                             Leadtools.DicomDemos.Utils.SetTag(ds, DicomTag.StudyInstanceUID, StudyInstanceUID, true);
                             Leadtools.DicomDemos.Utils.SetTag(ds, DicomTag.SeriesInstanceUID, SeriesInstanceUID, true);
                             Leadtools.DicomDemos.Utils.SetTag(ds, DicomTag.SOPInstanceUID, SOPInstanceUID, true);
                             Leadtools.DicomDemos.Utils.SetTag(ds, DicomTag.PatientSex, pSex, true);
                             Leadtools.DicomDemos.Utils.SetTag(ds, DicomTag.PatientName, PName, true);
                             Leadtools.DicomDemos.Utils.SetTag(ds, DicomTag.PatientAge, pAge, true);
                             ds.Save(_fileName, DicomDataSetSaveFlags.None);
                         }
                     }
                     catch
                     {
                     }
                 }
             }
        
     }
     catch
     {
     }
 }
Exemplo n.º 24
0
      public static DicomExceptionCode InsertKeyElement(DicomDataSet dcmRsp, DicomDataSet dcmReq, long tag)
      {
         DicomExceptionCode ret = DicomExceptionCode.Success;
         DicomElement element;

         try
         {
            element = dcmReq.FindFirstElement(null, tag, true);
            if(element != null)
            {
               dcmRsp.InsertElement(null, false, tag, DicomVRType.UN, false, 0);
            }
         }
         catch(DicomException de)
         {
            ret = de.Code;
         }

         return ret;
      }
Exemplo n.º 25
0
      public static DicomExceptionCode SetTag(DicomDataSet dcm, long tag, byte[] tagValue)
      {
         DicomExceptionCode ret = DicomExceptionCode.Success;
         DicomElement element;

         if(tagValue == null)
            return DicomExceptionCode.Parameter;

         element = dcm.FindFirstElement(null, tag, true);
         if(element == null)
         {
            element = dcm.InsertElement(null, false, tag, DicomVRType.UN, false, 0);
         }

         dcm.SetBinaryValue(element, tagValue, tagValue.Length);

         return ret;
      }
Exemplo n.º 26
0
      public static void SetTag(DicomDataSet dcm,long Sequence,long Tag,object TagValue)
      {
          DicomElement seqElement = dcm.FindFirstElement(null, Sequence, true);
          DicomElement seqItem = null;
          DicomElement item = null;

          if(seqElement==null)
          {
              seqElement = dcm.InsertElement(null, false, Tag, DicomVRType.SQ, true, -1);
          }

          seqItem = dcm.GetChildElement(seqElement, false);
          if (seqItem == null)
          {
#if (LTV15_CONFIG)
              seqItem = dcm.InsertElement(seqElement, true, DicomTagType.SequenceDelimitationItem, DicomVRType.SQ, true, -1);
#else
              seqItem = dcm.InsertElement(seqElement, true, DicomTag.SequenceDelimitationItem, DicomVRType.SQ, true, -1);
#endif
          }

          item = dcm.GetChildElement(seqItem, true);
          while(item!=null)
          {
#if (LTV15_CONFIG)
              if ((long)item.Tag == Tag)
                  break;
#else
              if (item.Tag == Tag)
                  break;
#endif

              item = dcm.GetNextElement(item, true, true);
          }

          if(item==null)
          {
              item = dcm.InsertElement(seqItem, true, Tag, DicomVRType.UN, false, -1);              
          }
          dcm.SetConvertValue(item, TagValue.ToString(), 1);
      }
Exemplo n.º 27
0
 public static DicomExceptionCode SetTag(DicomDataSet dcm, long tag, object tagValue)
 {
    return SetTag(dcm, tag, tagValue, true);
 }
Exemplo n.º 28
0
 public static bool IsTagPresent(DicomDataSet dcm, DicomTagType tag)
 {
    return IsTagPresent(dcm, (long)tag);
 }
Exemplo n.º 29
0
 public static byte[] GetBinaryValues(DicomDataSet dcm, DicomTagType tag)
 {
    return GetBinaryValues(dcm, (long)tag);
 }
Exemplo n.º 30
0
      public static DicomExceptionCode SetKeyElement(DicomDataSet dcmRsp, long tag, object tagValue, bool tree)
      {
         DicomExceptionCode ret = DicomExceptionCode.Success;
         DicomElement element;

         if (tagValue == null)
            return DicomExceptionCode.Parameter;

         try
         {
            element = dcmRsp.FindFirstElement(null, tag, tree);
            if (element != null)
            {
               dcmRsp.SetConvertValue(element, tagValue.ToString(), 1);
            }
         }
         catch (DicomException de)
         {
            ret = de.Code;
         }

         return ret;
      }
Exemplo n.º 31
0
        void EditWL()
        {
            try
            {
                DataRow _dr =null;
                frm_Registration newForm = new frm_Registration(m_intCurrDevice1);
                if (_currTab == AppType.AppEnum.TabMode.Acq)
                {
                    if (_LastDoubleMode == AppType.AppEnum.DoubleMode.WorkList)
                    {
                        Utility.GotoNewRow(grdWorkList, "colPATIENT_CODE", txtID2.Text.Trim());
                        if (grdWorkList.RowCount <= 0 || grdWorkList.CurrentRow == null)
                        {
                            Utility.ShowMsg("Bạn phải chọn Bệnh nhân trên lưới để sửa", "Thông báo");
                            grdWorkList.Focus();
                            return;
                        }
                        _dr = ((DataRowView)grdWorkList.CurrentRow.DataBoundItem).Row;
                        newForm.grdList = grdWorkList;
                    }
                    if (_LastDoubleMode == AppType.AppEnum.DoubleMode.StudyList)
                    {
                        Utility.GotoNewRow(grdStudyList, "colPATIENT_CODE1", txtID2.Text.Trim());
                        if (grdStudyList.RowCount <= 0 || grdStudyList.CurrentRow == null)
                        {
                            Utility.ShowMsg("Bạn phải chọn Bệnh nhân  trên lưới để sửa", "Thông báo");
                            grdStudyList.Focus();
                            return;
                        }
                        _dr = ((DataRowView)grdStudyList.CurrentRow.DataBoundItem).Row;
                        newForm.grdList = grdStudyList;
                    }
                }

                if (_currTab == AppType.AppEnum.TabMode.WorkList)
                {
                    if (grdWorkList.RowCount <= 0 || grdWorkList.CurrentRow == null)
                    {
                        Utility.ShowMsg("Bạn phải chọn Bệnh nhân trên lưới để sửa", "Thông báo");
                        grdWorkList.Focus();
                        return;
                    }
                    _dr = ((DataRowView)grdWorkList.CurrentRow.DataBoundItem).Row;
                    newForm.grdList = grdWorkList;
                }
                if (_currTab == AppType.AppEnum.TabMode.StudyList)
                {
                    if (grdStudyList.RowCount <= 0 || grdStudyList.CurrentRow == null)
                    {
                        Utility.ShowMsg("Bạn phải chọn Bệnh nhân  trên lưới để sửa", "Thông báo");
                        grdStudyList.Focus();
                        return;
                    }
                    _dr = ((DataRowView)grdStudyList.CurrentRow.DataBoundItem).Row;
                    newForm.grdList = grdStudyList;
                }
                
                newForm.ImgPath = txtImgDir.Text.Trim();

               
                newForm.Act = action.Update;
                //newForm.lblmsg1 = lblMsg;
               
                newForm.dr = _dr;
                Hasresult = new RegDetailController().HasResult(Convert.ToInt64(_dr["REG_ID"]));
                newForm.Hasresult = Hasresult;
                newForm.ShowDialog();
                if (newForm.blnRegOK)
                {
                    string Folder2Changed = "";
                    //Tự động update sang phần ACQ
                    UpdatePinforinAcqTab(Utility.Int32Dbnull(newForm.dr["Patient_ID"], -1));
                    //Kiểm tra nếu tên tuổi hoặc giới tính khác thông tin cũ thì tạo luồng cập nhật dữ liệu trong các file ảnh dicom
                    if (newForm.oldSex.Trim().ToUpper() != newForm.NewSex.Trim().ToUpper() || newForm.oldName.Trim().Replace(newForm.oldAge.Trim().ToUpper(), "").Trim().ToUpper() != newForm.NewName.Trim().Replace(newForm.NewAge.Trim().ToUpper(), "").Trim().ToUpper() || newForm.oldAge.Trim().ToUpper() != newForm.NewAge.Trim().ToUpper())
                    {
                       
                        //Duyệt tất cả các ảnh trong thư mục ảnh của BN ở thời điểm hiện tại
                        if (newForm.oldFolderName.Trim().ToUpper() == newForm.newFolderName.Trim().ToUpper())
                        {
                            Folder2Changed = newForm.oldFolderName;
                        }
                        else//Tất cả các ảnh đã được chuyển sang thư mục mới-->Cần thay đổi thông tin dicomdataset trong thư mục mới
                        {
                            Folder2Changed = newForm.newFolderName;
                        }
                        //Thực hiện duyệt các file Dicom ko có chữ IDX
                        string[] files = Directory.GetFiles(Folder2Changed);
                        foreach (string _fileName in files)
                        {
                            if (Path.GetExtension(_fileName).Trim().Contains("DCM") && !Path.GetExtension(_fileName).Trim().Contains("_IDX"))
                            {
                                try
                                {
                                    using (DicomDataSet ds = new DicomDataSet())
                                    {
                                        ds.Load(_fileName, DicomDataSetLoadFlags.LoadAndClose);
                                        if (newForm.oldSex.Trim().ToUpper() != newForm.NewSex.Trim().ToUpper())
                                        {
                                            Leadtools.DicomDemos.Utils.SetTag(ds, DicomTag.PatientSex, newForm.NewSex.Trim().ToUpper(), true);
                                        }
                                        if (newForm.oldName.Trim().ToUpper() != newForm.NewName.Trim().ToUpper())
                                        {
                                            Leadtools.DicomDemos.Utils.SetTag(ds, DicomTag.PatientName, newForm.NewName.Trim().ToUpper(), true);
                                        }
                                        if (newForm.oldAge.Trim().ToUpper() != newForm.NewAge.Trim().ToUpper())
                                        {
                                            Leadtools.DicomDemos.Utils.SetTag(ds, DicomTag.PatientAge, newForm.NewAge.Trim().ToUpper(), true);
                                        }
                                        ds.Save(_fileName, DicomDataSetSaveFlags.None);
                                    }
                                }
                                catch
                                {
                                }
                            }
                            
                        }

//Update Thumbnail
                        UpdateThumbnailImgFolder(Folder2Changed, Convert.ToInt32(_dr["REG_ID"]));

                    }


                }
            }
            catch
            {
            }
            finally
            {
                _CurrAct = action.FirstOrFinished;
            }
        }
Exemplo n.º 32
0
 private void SetSomeTag(DicomDataSet ds, string FileName)
 {
     try
     {
         
         DicomElement element = ds.FindFirstElement(null, DicomTag.PatientID, false);
         if (element != null)
         {
             ds.DeleteElement(element);
             ds = ds.InsertElementAndSetValue(DicomTag.PatientID, txtID2.Text.Trim());
         }
         if (element == null) ds = ds.InsertElementAndSetValue(DicomTag.PatientID, txtID2.Text.Trim());
         //RegistrationSequence
         element = ds.FindFirstElement(null, DicomTag.RegistrationSequence, false);
         if (element != null)
         {
             ds.DeleteElement(element);
             ds = ds.InsertElementAndSetValue(DicomTag.RegistrationSequence, txtRegNumber2.Text.Trim());
         }
         if (element == null) ds = ds.InsertElementAndSetValue(DicomTag.RegistrationSequence, txtRegNumber2.Text.Trim());
         //Sex
         element = ds.FindFirstElement(null, DicomTag.PatientSex, false);
         if (element != null)
         {
             ds.DeleteElement(element);
             ds = ds.InsertElementAndSetValue(DicomTag.PatientSex, Sex);
         }
         if (element == null) ds = ds.InsertElementAndSetValue(DicomTag.PatientSex, Sex);
         //CreatedDate
         element = ds.FindFirstElement(null, DicomTag.DateTime, false);
         if (element != null)
         {
             ds.DeleteElement(element);
             ds = ds.InsertElementAndSetValue(DicomTag.DateTime, RegDate.ToLongTimeString());
         }
         if (element == null) ds = ds.InsertElementAndSetValue(DicomTag.DateTime, RegDate.ToLongTimeString());
         //pBirthdate
         element = ds.FindFirstElement(null, DicomTag.PatientBirthDate, false);
         if (element != null)
         {
             ds.DeleteElement(element);
             ds = ds.InsertElementAndSetValue(DicomTag.PatientBirthDate, BirthDate);
         }
         if (element == null) ds = ds.InsertElementAndSetValue(DicomTag.PatientBirthDate, BirthDate);
         //pName
         element = ds.FindFirstElement(null, DicomTag.PatientName, false);
         if (element != null)
         {
             ds.DeleteElement(element);
             ds = ds.InsertElementAndSetValue(DicomTag.PatientName, Bodau(txtName2.Text.Trim()));
         }
         if (element == null) ds = ds.InsertElementAndSetValue(DicomTag.PatientName, Bodau(txtName2.Text.Trim()));
         //pAge
         element = ds.FindFirstElement(null, DicomTag.PatientAge, false);
         if (element != null)
         {
             ds.DeleteElement(element);
             ds = ds.InsertElementAndSetValue(DicomTag.PatientAge, txtAge.Text.Trim());
         }
         if (element == null) ds = ds.InsertElementAndSetValue(DicomTag.PatientAge, txtAge.Text.Trim());
     }
     catch
     {
     }
 }
Exemplo n.º 33
0
 private void AutpSetDefaultTagForImgInfor(string fileName, DicomDataSet ds)
 {
     try
     {
         if (ds == null) ds = new DicomDataSet();
         string NewFileName = fileName.ToLower().Replace(".raw", ".dcm");
         SetSomeTag(ds, fileName);
         ds.Save(NewFileName, DicomDataSetSaveFlags.BigEndian);
     }
     catch
     {
     }
 }
Exemplo n.º 34
0
         public void OpenDicom( ref bool IsCroping, ref int _Idx, string fileName, bool IsOnlyImg, bool CanCreatePicBox)
         {
             //Stopwatch _sw = new Stopwatch();
             try
             {
                 _DicomMedicalViewer._medicalViewer.BeginUpdate();
                 pnlScheduled.Enabled = false;
                 //_sw.Start();
                
                 #region Chế độ Demo
                 if (_AppMode == AppType.AppEnum.AppMode.Demo && !File.Exists(fileName))
                 {
                     ScheduledControl _selected = GetSelectedScheduled();
                     bool _isSelected = true;
                     string RAWFilePath = "";
                     //Tạo các thư mục theo cấp ngày\Bệnh nhân(Mã bệnh nhân _ Tên Bệnh nhân _ Tuổi)
                     if (!Directory.Exists(txtImgDir.Text + @"\" + SubDirLv1())) Directory.CreateDirectory(txtImgDir.Text + @"\" + SubDirLv1());
                     if (!Directory.Exists(txtImgDir.Text + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient())) Directory.CreateDirectory(txtImgDir.Text + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient());
                     //Kiểm tra nếu chưa chọn thủ tục nào thì cần lưu ảnh thành tên file theo định dạng
                     //YYYY_MM_DD_HH_mm_ss
                     if (_selected == null || RAWFileNameWillbeCreated == "NONE_SELECTED")
                     {
                         _isSelected = false;
                         RAWFileNameWillbeCreated = "NONE_SELECTED_" + Utility.GetYYYYMMDDHHMMSS(DateTime.Now);
                         if (!Directory.Exists(txtImgDir.Text + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient() + @"\NONE_SELECTED")) Directory.CreateDirectory(txtImgDir.Text + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient() + @"\NONE_SELECTED");
                         RAWFilePath = txtImgDir.Text + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient() + @"\NONE_SELECTED\" + RAWFileNameWillbeCreated + ".RAW";
                     }
                     else
                         RAWFilePath = txtImgDir.Text + @"\" + SubDirLv1() + @"\" + SubDirLv2_Patient() + @"\" + RAWFileNameWillbeCreated + ".RAW";//RAWFileNameWillbeCreated=REGNUM+_Detail_ID+_ACode+_Pcode tại phần click của Scheduled
                     fileName = Application.StartupPath + @"\DemoImg\" + m_strCurrACode + "-" + m_strCurrPCode + ".DCM";
                     string destFile = RAWFilePath.ToUpper().Replace(".RAW", ".DCM");
                     try2MoveFileInDemoMode(fileName, destFile);
                     fileName = destFile;
                     //Tự động cập nhật kết quả đã có hình ảnh
                     AutoUpdateResultAfterCapturingPictureFromModality();
                     AutoUpdatePatientInforInDcmFile_DemoMode(Path.GetDirectoryName(fileName), fileName, txtID2.Text, txtName2.Text, txtAge.Text, Sex,_selected.StudyInstanceUID, _selected.SeriesInstanceUID, _selected.SOPInstanceUID);
                 }
                 #endregion

                 isLoadding = true;
                 //stopToolStripMenuItem1_Click(mnuStop, new EventArgs());
                 TempCrop = IsCroping;
                 int _ww = 0;
                 int _wc = 0;
                 this.Text = MultiLanguage.GetText(globalVariables.DisplayLanguage, "VietBaIT JCS - DROC", "VietBaIT JSC-DROC");
                 if (!IsCroping) FilePath = fileName;
                 bool IsRawFile = false;
                 _images = 1;
                
                     try
                     {
                         #region Xử lý lại ảnh dcm từ ảnh gốc(Raw file)
                         try
                         {
                             if (IsGenDcmFromRaw)
                             {
                                 IsGenDcmFromRaw = false;
                                 string tempf_raw = fileName.ToUpper().Replace(".DCM", ".RAW");

                                 //Kiểm tra xem có ảnh Raw không
                                 if (File.Exists(tempf_raw))
                                 {
                                     //xóa file Dcm đang có
                                     string tempf_dcm = fileName.ToUpper().Replace(".RAW", ".DCM");
                                     try
                                     {
                                         File.Delete(tempf_dcm);
                                     }
                                     catch
                                     {
                                     }
                                     //Gán lại giá trị cho fileName để bước kế tiếp load lại raw file
                                     fileName = tempf_raw;
                                 }

                             }
                         }
                         catch(Exception ex0)
                         {
                             AppLogger.LogAction.LogActions("==>OpenDicom.if (IsGenDcmFromRaw)().Exception occurred at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + "." + ex0.ToString());
                         }
                         try
                         {
                             if (Path.GetExtension(fileName).ToUpper().Contains("RAW"))
                             {
                                 if (IsUsingDicomConverter || lblAutoDcmConverter.IsChecked)//Tự động convert thành file Dicom
                                 {
                                     ConvertRaw2DicomFileReprocess(fileName);
                                     AutoUpdateResultAfterCapturingPictureFromModality();
                                     fileName = fileName.ToLower().Replace(".raw", ".dcm");
                                     IsUsingDicomConverter = true;
                                     v_blnHasConvertRawin2DicomFile = true;
                                     //Thực hiện thuật toán xử lý ảnh ở ngay sau bước load ảnh Dicom

                                 }
                                 else
                                 {
                                     new frm_LargeMsgBoxOK(MultiLanguage.GetText(globalVariables.DisplayLanguage, "Thông báo", "Warning"), MultiLanguage.GetText(globalVariables.DisplayLanguage, "Cần vào tab Cấu hình đánh dấu vào mục tự động Convert thành file Dicom", "go to Configuration Tab and check Auto Convert to Dicom File"), MultiLanguage.GetText(globalVariables.DisplayLanguage, "Đã hiểu", "OK"), MultiLanguage.GetText(globalVariables.DisplayLanguage, "Không hiểu", "Cancel")).ShowDialog();
                                 }
                             }
                         }
                         catch (Exception ex01)
                         {
                             AppLogger.LogAction.LogActions("==>OpenDicom.ReGenDcmFromRAWFile().Exception occurred at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + "." + ex01.ToString());
                         }
                         #endregion
                         
                         if (File.Exists(fileName))
                         {
                             AppLogger.LogAction.AddLog2List(lstFPD560,DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + fileName + " exists");
                             FreeMemoryCapturedByMedicalviewerCell();
                             using (RasterCodecs _codecs = new RasterCodecs())
                             {
                                 //using (CounterDialog counter = new CounterDialog(this, _codecs))
                                 //{
                                 //    counter.Show(this);
                                 //    counter.Update();
                                 //if (chkLoadIn2Memory.IsChecked==false ) _codecs.Options.Load.DiskMemory = true;

                                 if (_codecs.Options.Load.DiskMemory) SetText(lblUsingMemo, "MEM");
                                 else SetText(lblUsingMemo, "NOTMEM");
                                 using (RasterImage _image = _codecs.Load(fileName))
                                 {

                                     cmdCreateDcmfromRaw.Enabled = true;
                                     //try2FreeImage(orginalImg);
                                    _DicomMedicalViewer.try2FreeImage(ref orginalImg);
                                     // try2FreeOriginalImage();
                                     if (_CurrCell != null)
                                     {
                                         RasterImage img = _CurrCell.Image;
                                         _DicomMedicalViewer.try2FreeImage(ref img);
                                     }
                                     orginalImg = _image.CloneAll();
                                     //Xóa các cell sau khi đã giải phóng bộ nhớ
                                     _DicomMedicalViewer._medicalViewer.Cells.Clear();
                                     //Tạo cell mới
                                     MedicalViewerMultiCell cell = new MedicalViewerMultiCell();
                                     cell.BeginUpdate();
                                     cell.FitImageToCell = true;
                                     cell.Columns = 1;
                                     cell.Rows = 1;
                                     _DicomMedicalViewer.InitializeCell(cell);
                                     _DicomMedicalViewer.CopyPropertiesFromGlobalCell(cell);
                                     _Idx = 0;
                                     if (IsOnlyImg) return;
                                     CurrCellFileName = fileName;
                                     //cell.SetTag(4, MedicalViewerTagAlignment.TopLeft, MedicalViewerTagType.Frame);
                                     cell.SetTag(6, MedicalViewerTagAlignment.TopLeft, MedicalViewerTagType.Scale);
                                     cell.SetTag(2, MedicalViewerTagAlignment.BottomLeft, MedicalViewerTagType.WindowLevelData);
                                     //cell.SetTag(1, MedicalViewerTagAlignment.BottomLeft, MedicalViewerTagType.FieldOfView);
                                     cell.SetTag(0, MedicalViewerTagAlignment.BottomLeft, MedicalViewerTagType.RulerUnit);
                                     DicomDataSet ds = new DicomDataSet();

                                     try
                                     {
                                         ds.Load(fileName, DicomDataSetLoadFlags.LoadAndClose);
                                         CurrentDicomDS = ds;
                                     }
                                     catch (Exception ex) { ds = null; }
                                     //DicomDS.Add(fileName, ds);
                                     if (ds != null)
                                     {

                                         if (IsRawFile)
                                             AutpSetDefaultTagForImgInfor(fileName, ds);
                                         _ww = Convert.ToInt32(GetStringValue(ds, DicomTag.WindowWidth));
                                         _wc = Convert.ToInt32(GetStringValue(ds, DicomTag.WindowCenter));
                                         string ID_Name = GetStringValue(ds, Leadtools.Dicom.DicomTag.PatientID) + " " + GetStringValue(ds, Leadtools.Dicom.DicomTag.PatientName);
                                         string Birthday_Sex_Age = "";
                                         string BD = GetStringValue(ds, Leadtools.Dicom.DicomTag.PatientBirthDate).Trim();
                                         string BT = GetStringValue(ds, Leadtools.Dicom.DicomTag.PatientBirthTime).Trim();
                                         string Sex = TranslateSex(GetStringValue(ds, Leadtools.Dicom.DicomTag.PatientSex).Trim());
                                         string Age = GetStringValue(ds, Leadtools.Dicom.DicomTag.PatientAge).Trim();
                                         ID_Name_Age_Sex = ID_Name + " " + Age + " " + Sex;
                                         if (BD != "") Birthday_Sex_Age += BD;
                                         //if (BT != "") Birthday_Sex_Age += BD;
                                         if (Sex != "") Birthday_Sex_Age += " [" + Sex + "] ";
                                         if (Age != "") Birthday_Sex_Age += Age + " T";
                                         //Mã+Tên BN
                                         cell.SetTag(0, MedicalViewerTagAlignment.TopLeft, MedicalViewerTagType.UserData, ID_Name);
                                         //Ngày sinh-Giới tính-Tuổi
                                         cell.SetTag(1, MedicalViewerTagAlignment.TopLeft, MedicalViewerTagType.UserData, Birthday_Sex_Age);
                                         //Các thông tin khác

                                         cell.SetTag(0, MedicalViewerTagAlignment.TopRight, MedicalViewerTagType.UserData, HospitalName);
                                         cell.SetTag(1, MedicalViewerTagAlignment.TopRight, MedicalViewerTagType.UserData, DepartmentName);
                                         cell.SetTag(2, MedicalViewerTagAlignment.TopRight, MedicalViewerTagType.UserData, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                                     }
                                     else
                                     {
                                         //Mã+Tên BN
                                         cell.SetTag(0, MedicalViewerTagAlignment.TopLeft, MedicalViewerTagType.UserData, "");
                                         //Ngày sinh-Giới tính-Tuổi
                                         cell.SetTag(1, MedicalViewerTagAlignment.TopLeft, MedicalViewerTagType.UserData, "");
                                         //Các thông tin khác

                                         cell.SetTag(0, MedicalViewerTagAlignment.TopRight, MedicalViewerTagType.UserData, "");
                                         cell.SetTag(1, MedicalViewerTagAlignment.TopRight, MedicalViewerTagType.UserData, "");
                                         cell.SetTag(2, MedicalViewerTagAlignment.TopRight, MedicalViewerTagType.UserData, "");
                                     }

                                     //Load Annotation
                                     string Anfn = GetAnnPath(fileName);
                                     if (System.IO.File.Exists(Anfn))
                                     {
                                         LoadAnnotation(cell, Anfn, true);
                                     }

                                    _DicomMedicalViewer.ApplyToCell(cell);
                                     cell.ShowTags = lblDisplayTag.IsChecked;
                                     cell.DisplayRulers = (MedicalViewerRulers)cboRuler.SelectedIndex;
                                     AddNewMecicalViewerCell(cell);
                                     int CellCount = _DicomMedicalViewer._medicalViewer.Cells.Count;
                                     _Idx = CellCount - 1;
                                     //Dùng CloneAll() để giải phóng _image

                                     cell.Tag = fileName;
                                     if (GetSelectedScheduled() != null)
                                         cell.TabIndex = GetSelectedScheduled().DETAIL_ID;
                                     else
                                         cell.TabIndex = m_intCurrentDetail_ID <= 0 ? 0 : m_intCurrentDetail_ID;
                                     //v_blnHasConvertRawin2DicomFile=true xảy ra ở 2 sự kiện
                                     //1. Nhận ảnh từ FPD và có tự động chuyển thành file Dicom
                                     //2. Nhận ảnh từ FPD và để dưới dạng file RAW, sau đó tại hàm OpenDicom() nếu chưa có ảnh Dcm sẽ tự động Convert file RAW thành DCM
                                     if (v_blnHasConvertRawin2DicomFile && lblDisplayRaw.ImageIndex != 0)
                                     {
                                             using (Cursor _Cursor = Cursors.WaitCursor)
                                             {
                                                 AppLogger.LogAction.ShowEventStatus(lblFPDStatus,MultiLanguage.GetText(globalVariables.DisplayLanguage, "Đang xử lý ảnh...", "image processing..."));
                                                 AppLogger.LogAction.AddLog2List(lstFPD560,DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + MultiLanguage.GetText(globalVariables.DisplayLanguage, "Đang xử lý ảnh...", "image processing..."));
                                                 _DicomMedicalViewer.ApplyIEConfig(_currDRIEData, _image, lblGridMode.IsChecked, lblAppliedMed.IsChecked);
                                                 AutoApplyWW_WC(_image);
                                                 AppLogger.LogAction.AddLog2List(lstFPD560,DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + MultiLanguage.GetText(globalVariables.DisplayLanguage, "Đã xử lý xong...", "image processed..."));
                                                 AppLogger.LogAction.ShowEventStatus(lblFPDStatus,MultiLanguage.GetText(globalVariables.DisplayLanguage, "Đã xử lý xong...", "image processed..."));

                                                 if ( ((_FPDMode != AppType.AppEnum.FPDMode.Other && chkAutoVFlip1.IsChecked) || (_FPDMode == AppType.AppEnum.FPDMode.Other && ((FPDSeq == 1 && chkAutoVFlip1.IsChecked) || (FPDSeq == 2 && chkAutoVFlip2.IsChecked)))))
                                                 {
                                                     _DicomMedicalViewer.ApplyFilter(_image, new FlipCommand(true));
                                                 }
                                                 if (((_FPDMode != AppType.AppEnum.FPDMode.Other && chkAutoHFlip1.IsChecked) || (_FPDMode == AppType.AppEnum.FPDMode.Other && ((FPDSeq == 1 && chkAutoHFlip1.IsChecked) || (FPDSeq == 2 && chkAutoHFlip2.IsChecked)))))
                                                 {
                                                     _DicomMedicalViewer.ApplyFilter(_image, new FlipCommand(false));
                                                 }
                                                 if (AUTO_FLIPV == 1)
                                                 {
                                                     _DicomMedicalViewer.ApplyFilter(_image, new FlipCommand(true));
                                                 }
                                                 if (AUTO_FLIPH == 1)
                                                 {
                                                     _DicomMedicalViewer.ApplyFilter(_image, new FlipCommand(false));
                                                 }
                                                 AutoDetectRowsAndCols(cell, _image.PageCount);
                                                 cell.Image = _image.CloneAll();
                                                 if (!_DicomMedicalViewer.IsValidCell()) return;
                                                 _DicomMedicalViewer._medicalViewer.Cells.SelectAll(false);
                                                 _DicomMedicalViewer._medicalViewer.VisibleRow = _Idx;
                                                 cell.Selected = true;
                                                 _DicomMedicalViewer._medicalViewer.Invalidate();
                                                 if (AllowAppliedWL)
                                                 {
                                                     _DicomMedicalViewer.SetWindowLevel(cell, WW,WC);
                                                     
                                                 }
                                                 AllowAppliedWL = true;
                                             }

                                             _ww = WW;
                                             _wc = WC;
                                         //Thử tạo thông tin Annotation
                                         //CreateDefaultAnnotationOnImage(_DicomMedicalViewer._medicalViewer, Color.White, Color.Black, HospitalName, DepartmentName, ID_Name_Age_Sex, DateTime.Now.ToString("dd/MM/yyyy"));
                                         SaveImg();
                                         v_blnHasConvertRawin2DicomFile = false;
                                         //Tự động chuyển sang Tab xử lý ảnh
                                         tabCtrlAcq.SelectedTab = tabPageImgTools;
                                         //PlayBeep(5);
                                     }
                                     else
                                     {
                                         AutoDetectRowsAndCols(cell, _image.PageCount);
                                         cell.Image = _image.CloneAll();
                                         //cell.Bounds = cell.GetDisplayedClippedImageRectangle();
                                         if (!_DicomMedicalViewer.IsValidCell()) return;
                                         _DicomMedicalViewer._medicalViewer.Cells.SelectAll(false);
                                         _DicomMedicalViewer._medicalViewer.VisibleRow = _Idx;
                                         cell.Selected = true;
                                         _DicomMedicalViewer._medicalViewer.Invalidate();
                                         if (_AppMode == AppType.AppEnum.AppMode.Demo && FirstExposure)
                                         {
                                             SaveImg();
                                         }
                                     }
                                     //Áp dụng windowLeveling khi thực hiện lưu ảnh.
                                     //AutoApplyWW_WC();
                                     if (_ww != 0)
                                     {
                                         _DicomMedicalViewer.SetWindowLevel(cell,_ww,_wc);

                                         _DicomMedicalViewer._medicalViewer.Invalidate();
                                     }
                                     cell.EndUpdate();
                                     _DicomMedicalViewer._medicalViewer.Invalidate();
                                 }
                                 // }
                             }
                             _DicomMedicalViewer._medicalViewer.EndUpdate();
                             AppLogger.LogAction.ShowEventStatus(lblFPDStatus,MultiLanguage.GetText(globalVariables.DisplayLanguage, "Mời bạn tiếp tục xử lý", "Image Result"));
                         }
                         else
                         {
                             mdlStatic.isDisplayImg = false;
                             if (_AppMode == AppType.AppEnum.AppMode.License || (_AppMode == AppType.AppEnum.AppMode.Demo && _ViewState == AppType.AppEnum.ViewState.Capture))
                                 MessageBox.Show("Không tồn tại file ảnh sau:\n" + fileName);
                         }
                     }
                     catch (Exception ex)
                     {

                         AppLogger.LogAction.LogActions("==>OpenDicom.SecondsException().Exception occurred at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + "." + ex.ToString());
                         Utility.ShowMsg("2225 " + ex.ToString() + "\n" + fileName);
                         GC.Collect();
                         isLoadding = false;
                        
                         DeleteCurrentImg(_DicomMedicalViewer._medicalViewer, _DicomMedicalViewer._medicalViewerCellIndex);

                     }
                     finally
                     {
                         isLoadding = false;

                     }
                
                 isLoadding = false;
             }
             catch (Exception ex1)
             {
                 AppLogger.LogAction.LogActions("==>OpenDicom.FirstException().Exception occurred at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + "." + ex1.ToString());
                 AppLogger.LogAction.AddLog2List(lstFPD560,"0002: " + ex1.Message);
             }
             finally
             {
                 _DicomMedicalViewer._medicalViewer.BeginUpdate();
                 pnlScheduled.Enabled = true;
                //_sw.Stop();
                 //AppLogger.LogAction.ShowEventStatus(lblFPDStatus,((decimal)_sw.ElapsedMilliseconds / 1000).ToString());
                 IsUsingDicomConverter = false;
                 lblMemory.Text = getAvailableRAM();
                 //Kiểm tra nếu đang chế độ Crop mà lại chọn mục xem lại ảnh gốc thì cần khôi phục lại chế độ đó
                 if (_DicomMedicalViewer._IsCropping && IsLoadOriginalImage)
                 {
                     cmdAcqCrop_Click(cmdAcqCrop,new EventArgs());//Trạng thái ban đầu
                     cmdAcqCrop_Click(cmdAcqCrop, new EventArgs());//Trạng thái Crop
                 } 
             }
         }
Exemplo n.º 35
0
      public static bool IsTagPresent(DicomDataSet dcm, long tag)
      {
         DicomElement element;

         element = dcm.FindFirstElement(null, tag, true);
         return (element != null);
      }
Exemplo n.º 36
0
        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);
            }
        }
Exemplo n.º 37
0
      /// <summary>
      /// 
      /// </summary>
      /// <param name="dcm"></param>
      /// <param name="tag"></param>
      /// <param name="tagValue"></param>
      /// <returns></returns>
      public static DicomExceptionCode SetTag(DicomDataSet dcm, long tag, object tagValue, bool tree)
      {
         DicomExceptionCode ret = DicomExceptionCode.Success;
         DicomElement element;

         if (tagValue == null)
            return DicomExceptionCode.Parameter;

         element = dcm.FindFirstElement(null, tag, tree);
         if (element == null)
         {
            element = dcm.InsertElement(null, false, tag, DicomVRType.UN, false, 0);
         }

         if (element == null)
            return DicomExceptionCode.Parameter;

         try
         {
            dcm.SetConvertValue(element, tagValue.ToString(), 1);
         }
         catch (DicomException de)
         {
            ret = de.Code;
         }

         return ret;
      }
        private void MWL_Server_QueryReceived(object sender, QueryReceivedArgs e)
        {
            #region "Tracing all calls to Server"
            Log.Trace("MWL_Server_QueryReceived with QueryRoot: " + e.Root.ToString());
            #endregion

            #region "Abort if not an MWL query"
            if (e.Root != QueryRoot.ModalityWorklist)
            {
                e.Errors.Add(Keyword.ErrorComment, "Invalid Query Root : None");
                e.Status = StatusCodes.InvalidQueryRoot;
                return;
            }
            #endregion

            DicomDataSetCollection            NullSequence = new DicomDataSetCollection();
            DicomDataSet                      requestFromAssociation;
            DicomDataSet                      requestedProcedureStep = null;
            IEnumerable <ExamsScheduledTable> results = new List <ExamsScheduledTable>();
            int status = 0;
            System.Data.SqlClient.SqlConnection db = null;
            try
            {
                #region "Open PowerPath db"
                try
                {
                    db = new System.Data.SqlClient.SqlConnection(powerpathloginconfig.ConnectionString);
                    db.Open();
                }
                catch (SqlException se)
                {
                    Log.Error("Sql Error opening Database -- " + se.Message);
                    status = StatusCodes.GeneralError; // Error, unable to process!
                    return;
                }
                #endregion

                using (var DBContext = new System.Data.Linq.DataContext(db))
                {
                    // Get the Imcoming Query Request
                    requestFromAssociation = e.RequestAssociation.Request;

                    #region "Build SQL query based on SCU request"
                    // the "where 1=1" makes the syntax of adding further conditions simpler, as all are then " AND x=y"
                    //TODO: refactor hard-coded table into Powerpath configuration item
                    string tableWithExamsScheduled = @"vwsu_scheduled_speciman_xrays";
                    if (this.dicomserverconfig.ExamScheduledTable.Length > 4)
                    {
                        tableWithExamsScheduled = dicomserverconfig.ExamScheduledTable;
                    }
                    string sql = "SELECT * from " + tableWithExamsScheduled + " Where 1=1";
                    SqlQueryUtils.AddCondition(ref sql, requestFromAssociation[Keyword.PatientID], "PatientID");
                    SqlQueryUtils.AddNameCondition(ref sql, requestFromAssociation[Keyword.PatientName], "surname", "Forename");

                    if (requestFromAssociation[Keyword.ScheduledProcedureStepSequence].ExistsWithValue)
                    {
                        DicomDataSetCollection requestedProcedureSteps;
                        //TODO: in what circumstances would there be more than one requested step?
                        requestedProcedureSteps = (DicomDataSetCollection)requestFromAssociation[Keyword.ScheduledProcedureStepSequence].Value;
                        requestedProcedureStep  = requestedProcedureSteps[0];

                        // Required Matching keys
                        SqlQueryUtils.AddCondition(ref sql, requestedProcedureStep[Keyword.ScheduledStationAETitle], "ScheduledAET");
                        // always blank from PowerPath //SqlQueryUtils.AddCondition(ref sql, rq1[Keyword.PerformingPhysicianName], "PerformingPhysician");
                        SqlQueryUtils.AddCondition(ref sql, requestedProcedureStep[Keyword.Modality], "Modality");


                        // AddDateCondition looks for a leading or trailing -hyphen-

                        // if only date is specified, then using standard matching
                        //but if both are specified, then MWL defines a combined match
                        //note: for PowerPath, there is no Scheduled Time that makes any sense
                        if (requestedProcedureStep[Keyword.ScheduledProcedureStepStartDate].ExistsWithValue && requestedProcedureStep[Keyword.ScheduledProcedureStepStartTime].ExistsWithValue) // if both Date and Time are specified
                        {
                            SqlQueryUtils.AddDateTimeCondition(ref sql, requestedProcedureStep[Keyword.ScheduledProcedureStepStartDate], requestedProcedureStep[Keyword.ScheduledProcedureStepStartTime], "ExamDateAndTime");
                        }
                        else if (requestedProcedureStep[Keyword.ScheduledProcedureStepStartDate].ExistsWithValue) // if Date is specified
                        {
                            SqlQueryUtils.AddDateCondition(ref sql, requestedProcedureStep[Keyword.ScheduledProcedureStepStartDate], "ExamDateAndTime");
                        }

                        // Optional (but commonly used) matching keys.
                        SqlQueryUtils.AddCondition(ref sql, requestedProcedureStep[Keyword.ScheduledProcedureStepLocation], "ExamRoom");
                        SqlQueryUtils.AddCondition(ref sql, requestedProcedureStep[Keyword.ScheduledProcedureStepDescription], "ExamDescription");
                    }

                    sql = sql + " Order by Surname, Forename";
                    Log.Debug("SQL query statement:" + Environment.NewLine + sql);
                    #endregion

                    #region "Execute Sql Query"
                    try
                    {
                        results = DBContext.ExecuteQuery <ExamsScheduledTable>(sql);
                    }
                    catch (Exception ex)
                    {
                        Log.Error("Error executing SQL: '" + sql + "'. " + ex.Message);
                        status = StatusCodes.GeneralError;
                        return;
                    }
                    #endregion

                    #region "Parse results"
                    DicomDataSet           rr1;
                    DicomDataSet           rr;
                    DicomDataSetCollection rrs;
                    foreach (ExamsScheduledTable result in results)
                    {
                        rr1 = new DicomDataSet();
                        rr  = new DicomDataSet();
                        rrs = new DicomDataSetCollection {
                            rr1
                        };

                        if (requestedProcedureStep != null)
                        {
                            rr.Add(Keyword.ScheduledProcedureStepSequence, rrs);
                        }

                        // add results to  "main" dataset

                        AddResultItem(rr, requestFromAssociation, Keyword.AccessionNumber, result.AccessionNumber);                                   // T2
                        AddResultItem(rr, requestFromAssociation, Keyword.InstitutionName, result.HospitalName);
                        AddResultItem(rr, requestFromAssociation, Keyword.ReferringPhysicianName, result.ReferringPhysician);                         // T2

                        AddResultItem(rr, requestFromAssociation, Keyword.PatientName, result.Surname + "^" + result.Forename + "^^" + result.Title); //T1
                        AddResultItem(rr, requestFromAssociation, Keyword.PatientID, result.PatientID);                                               // T1
                        AddResultItem(rr, requestFromAssociation, Keyword.PatientBirthDate, result.DateOfBirth);                                      // T2
                        AddResultItem(rr, requestFromAssociation, Keyword.PatientSex, result.Sex);                                                    //T2

                        AddResultItem(rr, requestFromAssociation, Keyword.StudyInstanceUID, result.StudyUID);                                         // T1

                        AddResultItem(rr, requestFromAssociation, Keyword.RequestingPhysician, result.ReferringPhysician);                            //T2
                        AddResultItem(rr, requestFromAssociation, Keyword.RequestedProcedureDescription, result.ExamDescription);                     //T1C

                        AddResultItem(rr, requestFromAssociation, Keyword.RequestedProcedureID, result.ProcedureID);                                  // T1

                        // Scheduled Procedure Step sequence T1
                        // add results to procedure step dataset
                        // Return if requested
                        if (requestedProcedureStep != null)
                        {
                            AddResultItem(rr1, requestedProcedureStep, Keyword.ScheduledStationAETitle, result.ScheduledAET);                 // T1
                            AddResultItem(rr1, requestedProcedureStep, Keyword.ScheduledProcedureStepStartDate, result.ExamDateAndTime);      //T1
                            AddResultItem(rr1, requestedProcedureStep, Keyword.ScheduledProcedureStepStartTime, result.ExamDateAndTime);      //T1
                            AddResultItem(rr1, requestedProcedureStep, Keyword.Modality, result.Modality);                                    // T1

                            AddResultItem(rr1, requestedProcedureStep, Keyword.ScheduledPerformingPhysicianName, result.PerformingPhysician); //T2
                            AddResultItem(rr1, requestedProcedureStep, Keyword.ScheduledProcedureStepDescription, result.ExamDescription);    // T1C
                            AddResultItem(rr1, requestedProcedureStep, Keyword.ScheduledProcedureStepID, result.ProcedureStepID);             // T1
                            AddResultItem(rr1, requestedProcedureStep, Keyword.ScheduledStationName, result.ExamRoom);                        //T2
                            AddResultItem(rr1, requestedProcedureStep, Keyword.ScheduledProcedureStepLocation, result.ExamRoom);              //T2
                        }

                        // Put blanks in for unsupported fields which are type 2 (i.e. must have a value even if NULL)
                        // In a real server, you may wish to support some or all of these, but they are not commonly supported

                        AddResultItem(rr, requestFromAssociation, Keyword.ReferencedStudySequence, NullSequence);
                        AddResultItem(rr, requestFromAssociation, Keyword.Priority, "");
                        AddResultItem(rr, requestFromAssociation, Keyword.PatientTransportArrangements, "");
                        AddResultItem(rr, requestFromAssociation, Keyword.AdmissionID, "");
                        AddResultItem(rr, requestFromAssociation, Keyword.CurrentPatientLocation, "");
                        AddResultItem(rr, requestFromAssociation, Keyword.ReferencedPatientSequence, NullSequence);
                        AddResultItem(rr, requestFromAssociation, Keyword.PatientWeight, "");
                        AddResultItem(rr, requestFromAssociation, Keyword.ConfidentialityConstraintOnPatientDataDescription, "");
                        Log.Debug("Sending response ..");
                        // Send Reponse Back
                        e.SendResponse(rr, StatusCodes.Pending);
                        Log.Info("PowerPath Database Disconnected Normally");
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error processing MWL request -- " + ex.Message);
                status = StatusCodes.GeneralError; // Error, unable to process!
            }
            finally
            {
                if (null != db)
                {
                    try
                    {
                        db.Close();
                    }
                    catch { /* ignore an SqlException here */ }
                    db.Dispose();
                }
                e.Status = status;
            }
        }
Exemplo n.º 39
0
 public static void SetTag(DicomDataSet dcm, DicomTagType seq,DicomTagType tag, object tagValue)
 {
    SetTag(dcm, (long)seq,(long)tag, tagValue);
 }
Exemplo n.º 40
0
        public static DicomDataSet GeneratePresentationStateForAnnotations
        (
            string userName,
            string seriesInstanceUID,
            string annotationData,
            string description,
            string userData,
            DataSet seriesDs
        )
        {
            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();

                if (null == seriesDs || seriesDs.Tables[DataTableHelper.PatientTableName].Rows.Count == 0 || seriesDs.Tables[DataTableHelper.StudyTableName].Rows.Count == 0)
                {
                    throw new Exception("Series not found");
                }

                DicomDataSet ds = new DicomDataSet();

                {
                    DataRow patient = seriesDs.Tables[DataTableHelper.PatientTableName].Rows[0];
                    DataRow study   = seriesDs.Tables[DataTableHelper.StudyTableName].Rows[0];

                    IPatientInfo        patientInfo = RegisteredDataRows.PatientInfo;
                    PersonNameComponent pn          = patientInfo.Name(patient);
                    string sFamilyName = pn.FamilyName;
                    string sGivenName  = pn.GivenName;
                    string sMiddleName = pn.MiddleName;
                    string sNamePrefix = pn.NamePrefix;
                    string sNameSuffix = pn.NameSuffix;
                    string sPatientId  = patientInfo.GetElementValue(patient, DicomTag.PatientID);

                    //Patient Module C.7.1.1
                    ds.InsertElementAndSetValue(DicomTag.PatientName, string.Format("{0}^{1}^{2}^{3}^{4}",
                                                                                    string.IsNullOrEmpty(sFamilyName) ? "" : sFamilyName,
                                                                                    string.IsNullOrEmpty(sGivenName) ? "" : sGivenName,
                                                                                    string.IsNullOrEmpty(sMiddleName) ? "" : sMiddleName,
                                                                                    string.IsNullOrEmpty(sNamePrefix) ? "" : sNamePrefix,
                                                                                    string.IsNullOrEmpty(sNameSuffix) ? "" : sNameSuffix));

                    ds.InsertElementAndSetValue(DicomTag.PatientID, sPatientId);
                    ds.InsertElementAndSetValue(DicomTag.PatientBirthDate, "");
                    ds.InsertElementAndSetValue(DicomTag.PatientSex, "");

                    IStudyInfo studyInfo         = RegisteredDataRows.StudyInfo;
                    string     sStudyInstanceUid = studyInfo.GetElementValue(study, DicomTag.StudyInstanceUID);
                    string     sAccessionNumber  = studyInfo.GetElementValue(study, DicomTag.AccessionNumber);
                    string     sStudyId          = studyInfo.GetElementValue(study, DicomTag.StudyID);

                    //Study Module C.7.2.1
                    ds.InsertElementAndSetValue(DicomTag.StudyInstanceUID, sStudyInstanceUid);
                    ds.InsertElementAndSetValue(DicomTag.StudyDate, "");
                    ds.InsertElementAndSetValue(DicomTag.StudyTime, "");
                    ds.InsertElementAndSetValue(DicomTag.ReferringPhysicianName, "");
                    ds.InsertElementAndSetValue(DicomTag.StudyID, string.IsNullOrEmpty(sStudyId) ? "" : sStudyId);
                    ds.InsertElementAndSetValue(DicomTag.AccessionNumber, string.IsNullOrEmpty(sAccessionNumber) ? "" : sAccessionNumber);

                    //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, "Annotations 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, "ANNOTATIONS");
                    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();
                    graphicLayerModule.GraphicLayerSequence = new List <GraphicLayer>();
                    GraphicLayer layer = new 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;

                    ds.Set(presentationLut);

                    //SOP Common Module
                    ds.InsertElementAndSetValue(DicomTag.SOPClassUID, DicomUidType.GrayscaleSoftcopyPresentationStateStorage);
                    ds.InsertElementAndSetValue(DicomTag.SOPInstanceUID, SeriesGenerator.GenerateDicomUniqueIdentifier());
                    ds.InsertElementAndSetValue(DicomTag.InstanceCreationDate, DicomDateValue.Now);
                    ds.InsertElementAndSetValue(DicomTag.InstanceCreationTime, DicomDateValue.Now);
                    ds.InsertElementAndSetValue(DicomTag.InstanceNumber, 1);
                }
                return(ds);
            }
        }
Exemplo n.º 41
0
 public static DicomExceptionCode SetTag(DicomDataSet dcm, DicomTagType tag, object tagValue, bool tree)
 {
     return SetTag(dcm, (long)tag, tagValue, tree);
 }
Exemplo n.º 42
0
        DataRow MakeDcmConverterInfor(MedicalViewerCell _cell, DicomDataSet ds)
        {

            try
            {
                DataRow dr = m_dtDicomconverterInfo.NewRow();
                dr[colPid] = "PATIENT_ID";
                dr[colPatientName] = "PATIENT_NAME";
                dr[colPatientSex] = "M";
                dr[colPatientAge] = "0";
                dr[colPatientBirthdate] = ToDicomString(DateTime.Now);
                dr[colRegDate] = ToDicomString(DateTime.Now);
                dr[colRegNum] = "REG_NUMBER";
                dr[colKVP] = "96";
                dr[colMAS] = "7";

                dr[colImgHeight] = _cell.Image.Height;
                dr[colImgWidth] = _cell.Image.Width;

                dr[colModalityCode] = GetStringValue(ds, DicomTag.Modality);
                dr[colAtonomyCode] = "A_CODE";
                dr[colProjectionCode] = "P_CODE";
                dr[colHostpitalName] = Bodau(HospitalName);
                dr[colDepartmentName] = Bodau(DepartmentName);
                dr[colAcqDate] = Utility.GetYYYYMMDD(DateTime.Now);
                dr[colAppName] = "DROC";
                dr[_colStudyInstanceUID] = ClearCanvas.Dicom.DicomUid.GenerateUid().UID.ToString();
                dr[colSOPInstanceUID] = ClearCanvas.Dicom.DicomUid.GenerateUid().UID.ToString();
                dr[colSeriesInstanceUID] = ClearCanvas.Dicom.DicomUid.GenerateUid().UID.ToString();
                dr[colBitsStored] = GetStringValue(ds, DicomTag.BitsStored);
                dr[colHightBit] = GetStringValue(ds, DicomTag.HighBit);
                dr[colBitsAllocated] = GetStringValue(ds, DicomTag.BitsAllocated);
                return dr;
            }
            catch (Exception ex)
            {
                Utility.ShowMsg("Lỗi khi tạo thông tin BN để dùng cho hàm DicomConverter\n" + ex.Message);
                return null;
            }
        }
Exemplo n.º 43
0
 public static DicomExceptionCode InsertKeyElement(DicomDataSet dcmRsp, DicomDataSet dcmReq, DicomTagType tag)
 {
    return InsertKeyElement(dcmRsp, dcmReq, (long)tag);
 }
Exemplo n.º 44
0
      public static StringCollection GetStringValues(DicomDataSet dcm, long tag)
      {
         DicomElement element;
         StringCollection sc = new StringCollection();

         element = dcm.FindFirstElement(null, tag, true);
         if(element != null)
         {
            if(dcm.GetElementValueCount(element) > 0)
            {
               string s = dcm.GetConvertValue(element);
               string[] items = s.Split('\\');

               foreach(string value in items)
               {
                  sc.Add(value);
               }
            }
         }

         return sc;
      }
Exemplo n.º 45
0
 public static DicomExceptionCode SetKeyElement(DicomDataSet dcmRsp, DicomTagType tag, object tagValue, bool tree)
 {
     return SetKeyElement(dcmRsp, (long)tag, tagValue, tree);
 }
Exemplo n.º 46
0
 /// <summary>
 /// Lấy giá trị của một Tag từ DicomDataset của ảnh
 /// </summary>
 /// <param name="ds"></param>
 /// <param name="tag"></param>
 /// <returns></returns>
 string GetStringValue(DicomDataSet ds, long tag)
 {
     try
     {
         if (ds == null) return "";
         DicomElement element;
         element = ds.FindFirstElement(null, tag, false);
         if (element != null)
         {
             if (ds.GetElementValueCount(element) > 0)
             {
                 return ds.GetConvertValue(element);
             }
         }
         return "";
     }
     catch
     {
         return "";
     }
 }
Exemplo n.º 47
0
 public static DicomExceptionCode SetKeyElement(DicomDataSet dcmRsp, long tag, object tagValue)
 {
    return SetKeyElement(dcmRsp, tag, tagValue, true);
 }
Exemplo n.º 48
0
 public override void OnBeforeSendCMoveRequest(DicomClient Client, byte presentationID, int messageID, string affectedClass, DicomCommandPriorityType priority, string moveAE, DicomDataSet dataSet)
 {
     // View or change parameters
     base.OnBeforeSendCMoveRequest(Client, presentationID, messageID, affectedClass, priority, moveAE, dataSet);
 }
Exemplo n.º 49
0
 public override void OnBeforeSendCGetResponse(DicomClient Client, byte presentationID, int messageID, string affectedClass, DicomCommandStatusType status, int remaining, int completed, int failed, int warning, DicomDataSet dataset)
 {
     // View or change parameters
     base.OnBeforeSendCGetResponse(Client, presentationID, messageID, affectedClass, status, remaining, completed, failed, warning, dataset);
 }
Exemplo n.º 50
0
 public ViewDatasetDialog(DicomDataSet ds) : this()
 {
     Dataset = ds;
 }
Exemplo n.º 51
0
        protected override void OnDoWork(DoWorkEventArgs e)
        {
            int count = 0;
            int imagesToExportCount   = 0;
            InstanceCStoreCommand cmd = null;

            MatchingParameterCollection matchingParamCollection;
            MatchingParameterList       matchingParamList;

            if (this.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            ExportDicomWorkerArgs args = e.Argument as ExportDicomWorkerArgs;

            if (args == null)
            {
                throw new ArgumentException("Invalid ExportDicom argument");
            }

            if (args.CreateDicomDir)
            {
                DicomDirectory = new DicomDir(args.OutputFolder);
            }

            if (args.Anonymize)
            {
                Anonymizer.BeginBatch();
            }

            try
            {
                ViewGenerator.ViewDataRow[] exportRows = (args.Rows);

                imagesToExportCount = exportRows.Length;

                foreach (ViewGenerator.ViewDataRow exportRow in exportRows)
                {
                    try
                    {
                        string rowKeyValue;
                        string rowKeyName;
                        string viewName;

                        if (this.CancellationPending)
                        {
                            e.Cancel = true;

                            return;
                        }

                        DataRow originalRow = exportRow.OriginalRow;
                        matchingParamCollection = new MatchingParameterCollection( );
                        matchingParamList       = new MatchingParameterList( );

                        matchingParamCollection.Add(matchingParamList);

                        if (string.Compare(originalRow.Table.TableName, DataTableHelper.InstanceTableName) == 0)
                        {
                            string         sSopInstanceUid = RegisteredDataRows.InstanceInfo.GetElementValue(originalRow, DicomTag.SOPInstanceUID);
                            ICatalogEntity imageInstance   = RegisteredEntities.GetInstanceEntity(sSopInstanceUid);

                            rowKeyValue = sSopInstanceUid;
                            rowKeyName  = "SOPInstanceUID";
                            viewName    = "Images";

                            matchingParamList.Add(imageInstance);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.SeriesTableName) == 0)
                        {
                            string         sSeriesInstanceUid = RegisteredDataRows.SeriesInfo.GetElementValue(originalRow, DicomTag.SeriesInstanceUID);
                            ICatalogEntity seriesEntity       = RegisteredEntities.GetSeriesEntity(sSeriesInstanceUid);

                            rowKeyValue = sSeriesInstanceUid;
                            rowKeyName  = "SeriesInstanceUID";
                            viewName    = "Series";

                            matchingParamList.Add(seriesEntity);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.StudyTableName) == 0)
                        {
                            string         sStudyInstanceUid = RegisteredDataRows.StudyInfo.GetElementValue(originalRow, DicomTag.StudyInstanceUID);
                            ICatalogEntity studyEntity       = RegisteredEntities.GetStudyEntity(sStudyInstanceUid);

                            rowKeyValue = sStudyInstanceUid;
                            rowKeyName  = "StudyInstanceUID";
                            viewName    = "Studies";

                            matchingParamList.Add(studyEntity);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.PatientTableName) == 0)
                        {
                            string         sPatientId    = RegisteredDataRows.PatientInfo.GetElementValue(originalRow, DicomTag.PatientID);
                            ICatalogEntity patientEntity = RegisteredEntities.GetPatientEntity(sPatientId);

                            rowKeyValue = sPatientId;
                            rowKeyName  = "PatientId";
                            viewName    = "Patients";

                            matchingParamList.Add(patientEntity);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.HangingProtocolTableName) == 0)
                        {
                            string         sSopInstanceUid         = RegisteredDataRows.InstanceInfo.GetElementValue(originalRow, DicomTag.SOPInstanceUID);
                            ICatalogEntity hangingProtocolInstance = RegisteredEntities.GetHangingProtocolEntity(sSopInstanceUid);

                            rowKeyValue = sSopInstanceUid;
                            rowKeyName  = "SOPInstanceUID";
                            viewName    = "Hanging Protocol";

                            matchingParamList.Add(hangingProtocolInstance);
                        }
                        else
                        {
                            throw new ApplicationException("Deleted row is not a valid DICOM format.");
                        }

                        DataSet   exportDataSet = null;
                        DataRow[] rows          = null;

                        if (string.Compare(originalRow.Table.TableName, DataTableHelper.HangingProtocolTableName) == 0 && _dataAccessAgent3 != null)
                        {
                            exportDataSet = _dataAccessAgent3.QueryHangingProtocol(matchingParamCollection);
                            rows          = exportDataSet.Tables[DataTableHelper.HangingProtocolTableName].Select();
                        }
                        else
                        {
                            exportDataSet = _dataAccessAgent.QueryCompositeInstances(matchingParamCollection);
                            rows          = exportDataSet.Tables[DataTableHelper.InstanceTableName].Select();
                        }

                        foreach (DataRow row in rows)
                        {
                            DicomDataSet dicomDataSet = RegisteredDataRows.InstanceInfo.LoadDicomDataSet(row);

                            if (args.Anonymize)
                            {
                                Anonymizer.Anonymize(dicomDataSet);
                            }

                            AddDicomBackgroundWorker.StoreClientSessionProxy proxy = new AddDicomBackgroundWorker.StoreClientSessionProxy();
                            proxy.AffectedSOPInstance = dicomDataSet.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty);
                            proxy.AbstractClass       = dicomDataSet.GetValue <string>(DicomTag.SOPClassUID, string.Empty);


                            try
                            {
                                cmd = new InstanceCStoreCommand(proxy, dicomDataSet, _dataAccessAgent);

                                OnStoreCommandCreated(this, new StoreCommandEventArgs(cmd));

                                cmd.Configuration.DataSetStorageLocation = args.OutputFolder;
#if (LEADTOOLS_V19_OR_LATER)
                                cmd.Configuration.HangingProtocolLocation = args.OutputFolder;
#endif

                                string fileLocation = CStoreCommand.GetStorageFullPath(cmd.Configuration, dicomDataSet);
                                if (args.Overwrite || !File.Exists(fileLocation))
                                {
                                    // Only exporting, so do not validate SopInstance and do not add to database
                                    cmd.DoValidateSopInstance      = false;
                                    cmd.DoUpdateDatabase           = false;
                                    cmd.DoUseExternalStoreSettings = false;
                                    cmd.DataSetStored += cmd_DataSetStored;

                                    cmd.Execute();
                                }
                                else
                                {
                                    // File already exists -- it is not overwritten
                                    DataSetStoredEventArgs storedArgs = new DataSetStoredEventArgs(dicomDataSet, string.Empty, string.Empty, fileLocation);
                                    cmd_DataSetStored(this, storedArgs);
                                }
                            }
                            finally
                            {
                                if (cmd != null)
                                {
                                    cmd.DataSetStored -= cmd_DataSetStored;
                                }
                            }
                        }

                        count++;

                        ExportDicomWorkerProgressState state = new ExportDicomWorkerProgressState( );

                        state.Error               = null;
                        state.CurrentCount        = count;
                        state.ExportRow           = exportRow;
                        state.ExportedImagesCount = 1;
                        state.TotalCount          = imagesToExportCount;
                        state.RowKeyValue         = rowKeyValue;
                        state.RowKeyName          = rowKeyName;
                        state.ViewName            = viewName;

                        ReportProgress((count * 100) / exportRows.Length, state);
                    }
                    catch (Exception exception)
                    {
                        ExportDicomWorkerProgressState state = new ExportDicomWorkerProgressState( );

                        count++;

                        state.Error               = exception;
                        state.CurrentCount        = count;
                        state.ExportRow           = exportRow;
                        state.TotalCount          = imagesToExportCount;
                        state.ExportedImagesCount = 0;

                        ReportProgress((count * 100) / exportRows.Length, state);
                    }
                }
            }
            finally
            {
                e.Result = imagesToExportCount;
                if (DicomDirectory != null)
                {
                    DicomDirectory.Save();
                    DicomDirectory = null;
                }

                if (Anonymizer != null)
                {
                    Anonymizer.EndBatch();
                    Anonymizer = null;
                }
            }
        }
Exemplo n.º 52
0
      private void AddStudyItem(DicomDataSet ds)
      {
         ListViewItem item;
         string tagValue;

         if(InvokeRequired)
         {
            Invoke(new AddStudyItemDelegate(AddStudyItem), ds);
         }
         else
         {
            tagValue = Utils.GetStringValue(ds, DemoDicomTags.PatientName);
            item = listViewStudies.Items.Add(tagValue);

            tagValue = Utils.GetStringValue(ds, DemoDicomTags.PatientID);
            item.SubItems.Add(tagValue);

            tagValue = Utils.GetStringValue(ds, DemoDicomTags.AccessionNumber);
            item.SubItems.Add(tagValue);

            tagValue = Utils.GetStringValue(ds, DemoDicomTags.StudyDate);
            item.SubItems.Add(tagValue);

            tagValue = Utils.GetStringValue(ds, DemoDicomTags.ReferringPhysicianName);
            item.SubItems.Add(tagValue);

            tagValue = Utils.GetStringValue(ds, DemoDicomTags.StudyDescription);
            item.SubItems.Add(tagValue);

            item.Tag = ds;
         }
      }
Exemplo n.º 53
0
        private bool IsStructuredDisplay(DicomDataSet ds)
        {
            string sopClassUid = ds.GetValue <string>(DicomTag.SOPClassUID, string.Empty);

            return(sopClassUid == DicomUidType.BasicStructuredDisplayStorage);
        }
Exemplo n.º 54
0
      private void AddSeriesItem(DicomDataSet ds)
      {
         ListViewItem item;
         string tagValue;

         if(InvokeRequired)
         {
            Invoke(new AddSeriesItemDelegate(AddSeriesItem), ds);
         }
         else
         {
            tagValue = Utils.GetStringValue(ds, DemoDicomTags.SeriesDate);
            item = listViewSeries.Items.Add(tagValue);

            tagValue = Utils.GetStringValue(ds, DemoDicomTags.SeriesNumber);
            item.SubItems.Add(tagValue);

            tagValue = Utils.GetStringValue(ds, DemoDicomTags.SeriesDescription);
            item.SubItems.Add(tagValue);

            tagValue = Utils.GetStringValue(ds, DemoDicomTags.Modality);
            item.SubItems.Add(tagValue);

            tagValue = Utils.GetStringValue(ds, DemoDicomTags.NumberOfSeriesRelatedInstances);
            item.SubItems.Add(tagValue);

            item.Tag = ds;
         }
      }
Exemplo n.º 55
0
        public void RunThread(IExternalStoreDataAccessAgent externalStoreAgent, IStorageDataAccessAgent storageAgent, DateRange range)
        {
            DicomUtilities.DebugString(DebugStringOptions.ShowCounter, "RestoreProcess.Run");

            lock (_restoreLock)
            {
                ExternalStoreInstance[] instances = externalStoreAgent.GetRestoreList(range);
                string message = string.Format("{0} {1} found to restore", instances.Length, "dataset(s)");
                MatchingParameterCollection mpc = new MatchingParameterCollection();

                Logger.Global.SystemMessage(LogType.Information, message, _serviceName);

                CStoreCommandConfiguration storeConfig = new CStoreCommandConfiguration();
                storeConfig.DicomFileExtension = _storageAddinsConfiguration.StoreAddIn.StoreFileExtension;
                FillStoreCommandDefaultSettings(storeConfig, _storageAddinsConfiguration);

                foreach (ExternalStoreInstance instance in instances)
                {
                    if (_cancelRestore)
                    {
                        _cancelRestore = false;
                        Logger.Global.SystemMessage(LogType.Information, "Cancelling Restore Process", _serviceName);
                        break;
                    }

                    MatchingParameterList mpl = new MatchingParameterList();

                    ICatalogEntity instanceEntity = RegisteredEntities.GetInstanceEntity(instance.SOPInstanceUID);
                    mpl.Add(instanceEntity);
                    mpc.Add(mpl);
                    try
                    {
                        DataSet ds = storageAgent.QueryCompositeInstances(mpc);

                        DataRow[] rows = ds.Tables[DataTableHelper.InstanceTableName].Select();
                        foreach (DataRow row in rows)
                        {
                            // Get the ICrud that the file was originally stored with
                            ICrud crud = DataAccessServiceLocator.Retrieve <ICrud>(instance.ExternalStoreGuid);
                            if (crud != null)
                            {
                                DicomDataSet dicomDataSet = null;
                                Exception    ex           = crud.RetrieveDicom(row, DicomDataSetLoadFlags.None, out dicomDataSet);
                                if (ex == null)
                                {
                                    string storageLocation   = CStoreCommand.GetStorageLocation(storeConfig, dicomDataSet);
                                    string dicomInstancePath = Path.Combine(storageLocation,
                                                                            instance.SOPInstanceUID) + "." + storeConfig.DicomFileExtension;

                                    ex = crud.RetrieveFile(row, dicomInstancePath);
                                    if (ex != null)
                                    {
                                        throw ex;
                                    }

                                    externalStoreAgent.SetReferencedFile(instance.SOPInstanceUID, dicomInstancePath);
                                    Logger.Global.SystemMessage(LogType.Information, string.Format("File Restored: {0} ", dicomInstancePath), _serviceName);
                                }
                            }
                            else
                            {
                                Logger.Global.SystemMessage(LogType.Information, string.Format("Error:  File Not Restored -- Store Token: {0}.  The Addin that for ExternalStoreGuid '{1}' cannot be found.", instance.StoreToken, instance.ExternalStoreGuid), _serviceName);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        message = string.Format("Error ({0}) restoring instance: {1}", e.Message, instance.SOPInstanceUID);
                        Logger.Global.SystemMessage(LogType.Error, message, _serviceName);
                    }
                    finally
                    {
                        mpc.Clear();
                    }
                }
            }
        }
Exemplo n.º 56
0
      /// <summary>
      /// Helper method to get string value from a DICOM dataset.
      /// </summary>
      /// <param name="dcm">The DICOM dataset.</param>
      /// <param name="tag">Dicom tag.</param>
      /// <returns>String value of the specified DICOM tag.</returns>
      public static string GetStringValue(DicomDataSet dcm, long tag, bool tree)
      {
         DicomElement element;

         element = dcm.FindFirstElement(null, tag, tree);
         if(element != null)
         {
            if(dcm.GetElementValueCount(element) > 0)
            {
               return dcm.GetConvertValue(element);
            }
         }

         return "";
      }
Exemplo n.º 57
0
        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);
        }
Exemplo n.º 58
0
 public static string GetStringValue(DicomDataSet dcm, long tag)
 {
    return GetStringValue(dcm, tag, true);
 }
Exemplo n.º 59
0
        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);
            }
        }
Exemplo n.º 60
0
 public static string GetStringValue(DicomDataSet dcm, DicomTagType tag)
 {
 return GetStringValue(dcm,(long)tag);
 }