Ejemplo n.º 1
0
        public static YCom Open(int no, string serverAETitle)
        {
            string key = no + "_" + serverAETitle;

            if (lockObjs.ContainsKey(key))
            {
                return(lockObjs[key]);
            }

            lock (sync)
            {
                if (lockObjs.ContainsKey(key))
                {
                    return(lockObjs[key]);
                }

                var sv = YCOM.GetStoreServer(serverAETitle);
                if (sv == null || sv.IPAddr == "" || sv.PortNumber == "")
                {
                    LogUtil.Error1("YCOM AEエラー[{0}]", serverAETitle);
                    return(null);
                }

                int port = 0;
                Int32.TryParse(sv.PortNumber, out port);

                var             ycom   = new YCom(sv.IPAddr, port, AppUtil.YComClientInfo, AppUtil.YComHospitalID, AppUtil.YComUserID);
                YComErrorStatus status = ycom.Open();
                if (status != YComErrorStatus.Success)
                {
                    LogUtil.Error("YComErrorStatus=" + status);
                }

                lockObjs.Add(key, ycom);
                return(ycom);
            }
        }
Ejemplo n.º 2
0
        //DICOMファイルの圧縮
        public static bool DicomToComp(string file, string dicomFile, Dictionary <string, string> tags)
        {
            try
            {
                //モダリティ
                string Modality = tags[DcmTag.Modality.Name];

                //圧縮タイプ
                string CompType;
                if (!AppUtil.ModalityCompType.TryGetValue(Modality, out CompType))
                {
                    CompType = AppUtil.CompType;
                }

                //圧縮オプション
                string CompOption;
                if (!AppUtil.ModalityCompOption.TryGetValue(Modality, out CompOption))
                {
                    CompOption = AppUtil.CompOption;
                }

                //ディレクトリ作成
                string dicomDir = Path.GetDirectoryName(dicomFile);
                if (!Directory.Exists(dicomDir))
                {
                    Directory.CreateDirectory(dicomDir);
                }

                //ファイル削除
                if (File.Exists(dicomFile))
                {
                    lock (fileLock)
                    {
                        File.Delete(dicomFile);
                    }
                }

                //圧縮
                if (CompType == "0")
                {
                    //なし
                    return(FileUtil.Copy(file, dicomFile));
                }
                else if (CompType == "2")
                {
                    //MEG
                    var scale = double.Parse(CompOption);
                    DicomToMeg(file, dicomFile, scale);
                    return(true);
                }
                else
                {
                    //転送構文UID
                    string TransferSyntaxUID = tags[DcmTag.TransferSyntaxUID.Name];

                    if (TransferSyntaxUID != "1.2.840.10008.1.2" && TransferSyntaxUID != "1.2.840.10008.1.2.1")
                    {
                        LogUtil.Debug1("TransferSyntaxUID[{0}]", TransferSyntaxUID);
                    }

                    //画素表現
                    string PixelRepresentation = tags[DcmTag.PixelRepresentation.Name];

                    var dcmCtrl = new DicomFile(file);

                    //圧縮対象
                    if (TransferSyntaxUID == "1.2.840.10008.1.2" || TransferSyntaxUID == "1.2.840.10008.1.2.1" || TransferSyntaxUID == "1.2.840.10008.1.2.2")
                    {
                        //JPEG-Lossy(8bit)圧縮
                        if (CompType == "50" && dcmCtrl.EncodeToJpeg("+eb +un", dicomFile))
                        {
                            dcmCtrl = new DicomFile(dicomFile);
                        }
                        //JPEG-Lossy(12bit)圧縮
                        else if (CompType == "51" && dcmCtrl.EncodeToJpeg("+ee +un", dicomFile))
                        {
                            dcmCtrl = new DicomFile(dicomFile);
                        }
                        //JPEG-Lossless圧縮
                        else if (CompType == "70" && dcmCtrl.EncodeToJpeg("+e1", dicomFile))
                        {
                            dcmCtrl = new DicomFile(dicomFile);
                        }
                        //JPEG2000圧縮
                        else if (CompType == "90" || CompType == "91")
                        {
                            string tmpFile = "";
                            try
                            {
                                //Explicit変換
                                if (TransferSyntaxUID != "1.2.840.10008.1.2.1")
                                {
                                    tmpFile = dcmCtrl.FileName + ".tmp";
                                    if (dcmconv("+te", dcmCtrl.FileName, tmpFile))
                                    {
                                        dcmCtrl = new DicomFile(tmpFile);
                                    }
                                }

                                //JPEG2000変換
                                if (!File.Exists(AppUtil.CompExe))
                                {
                                    throw new FileNotFoundException(AppUtil.CompExe + " NOT FOUND");
                                }

                                //EXE引数
                                string compArg;

                                //JPEG2000-Lossless圧縮
                                if (CompType == "90")
                                {
                                    compArg = "\"" + dcmCtrl.FileName + "\" \"" + dicomFile + "\"";
                                }
                                //JPEG2000-Lossy圧縮
                                else
                                {
                                    string ratio;
                                    if (!AppUtil.ModalityCompOption.TryGetValue(Modality, out ratio))
                                    {
                                        ratio = AppUtil.CompOption;
                                    }

                                    string[] ratios = ratio.Split(':');
                                    if (ratios.Length == 1 || (ratios.Length == 2 && ratios[0] == ratios[1]))
                                    {
                                        ratio = ratios[0];
                                    }
                                    else
                                    {
                                        //画素表現により決定
                                        if (PixelRepresentation == "1")
                                        {
                                            ratio = ratios[1];
                                        }
                                        else
                                        {
                                            ratio = ratios[0];
                                        }
                                    }

                                    compArg = "\"" + dcmCtrl.FileName + "\" \"" + dicomFile + "\" " + ratio;
                                }

                                bool moveFlag = true;

                                using (Process p = new Process())
                                {
                                    p.StartInfo.FileName        = AppUtil.CompExe;
                                    p.StartInfo.Arguments       = compArg;
                                    p.StartInfo.UseShellExecute = false;
                                    p.StartInfo.CreateNoWindow  = true;
                                    if (p.Start())
                                    {
                                        if (p.WaitForExit(AppUtil.ExeTimeout))
                                        {
                                            if (File.Exists(dicomFile))
                                            {
                                                dcmCtrl  = new DicomFile(dicomFile);
                                                moveFlag = false;
                                            }
                                            else
                                            {
                                                LogUtil.Warn("CompExe:ExitCode={0}" + p.ExitCode);
                                            }
                                        }
                                        else
                                        {
                                            LogUtil.Warn("CompExe:Timeout");
                                            try
                                            {
                                                p.Kill();
                                                p.WaitForExit();
                                            }
                                            catch { }
                                        }
                                    }
                                    else
                                    {
                                        LogUtil.Warn("CompExe:Process.Start()=false");
                                    }
                                }

                                if (moveFlag)
                                {
                                    for (int i = 0; i < AppUtil.RetryCount; i++)
                                    {
                                        try
                                        {
                                            if (File.Exists(dicomFile))
                                            {
                                                lock (fileLock2)
                                                {
                                                    File.Delete(dicomFile);
                                                }
                                            }
                                            return(FileUtil.Copy(file, dicomFile));
                                        }
                                        catch (Exception ex)
                                        {
                                            LogUtil.Warn(ex);
                                        }

                                        //リトライ
                                        if (i < AppUtil.RetryCount - 1)
                                        {
                                            System.Threading.Thread.Sleep(AppUtil.SleepTime);
                                            LogUtil.Info1("RETRY:{0}", i + 1);
                                        }
                                        else
                                        {
                                            LogUtil.Error1("DicomFile.Move():失敗 [{0}]", dicomFile);
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                if (tmpFile != "")
                                {
                                    FileUtil.Delete(tmpFile, true);
                                }
                            }
                        }
                        else
                        {
                            //無変換
                            return(FileUtil.Copy(file, dicomFile));
                        }
                    }
                    else
                    {
                        //無変換
                        return(FileUtil.Copy(file, dicomFile));
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex.ToString());
                return(false);
            }
        }
Ejemplo n.º 3
0
        //スタディ一覧の取得 (過去検査)
        public static void GetStudyList_Kako(string patientid, StudyKey key, out List <StudyTag> tags)
        {
            tags = new List <StudyTag>();

            using (var pc = new PacsComm())
            {
                var prm2 = new PacsComm.FindParam();
                if (patientid.Trim() == "")
                {
                    prm2.StudyInstanceUID = key.StudyInstanceUID;
                }
                else
                {
                    prm2.PatientID = patientid;
                }

                DicomTagsResult ret = pc.CFindStudy(prm2);
                if (!ret.IsSuccess)
                {
                    LogUtil.Error("CFINDに失敗しました。");
                    return;
                }

                foreach (var dcmTag in ret.Tags)
                {
                    var stkey = new StudyKey()
                    {
                        StudyInstanceUID = dcmTag.GetTagValue(DicomDic.Find("StudyInstanceUID").Tag),
                        IsPacsSearch     = true
                    };

                    var tag = new StudyTag();
                    tag.StudyKey = ConvertUtil.Serialize(stkey);

                    tag.StudyDate       = dcmTag.GetTagValue(DicomDic.Find("StudyDate").Tag);
                    tag.StudyTime       = dcmTag.GetTagValue(DicomDic.Find("StudyTime").Tag);
                    tag.AccessionNumber = dcmTag.GetTagValue(DicomDic.Find("AccessionNumber").Tag);
                    tag.PatientName     = dcmTag.GetTagValue(DicomDic.Find("PatientsName").Tag);
                    tag.PatientID       = dcmTag.GetTagValue(DicomDic.Find("PatientID").Tag);

                    tag.Modality         = dcmTag.GetTagValue(DicomDic.Find("ModalitiesInStudy").Tag);
                    tag.StudyDescription = dcmTag.GetTagValue(DicomDic.Find("StudyDescription").Tag);
                    tag.PatientBirthDate = dcmTag.GetTagValue(DicomDic.Find("PatientsBirthDate").Tag);
                    tag.PatientSex       = dcmTag.GetTagValue(DicomDic.Find("PatientsSex").Tag);
                    tag.PatientAge       = dcmTag.GetTagValue(DicomDic.Find("PatientsAge").Tag);
                    Int32.TryParse(dcmTag.GetTagValue(DicomDic.Find("NumberOfStudyRelatedInstances").Tag), out tag.NumberOfImages);

                    //メモ有無
                    using (var db = new TryDbConnection(LCL.settings))
                    {
                        using (var cmd = db.CreateCommand())
                        {
                            cmd.CommandText = "SELECT COUNT(*) cnt FROM T_StudyMemo WHERE StudyInstanceUID=@0";
                            cmd.Add(stkey.StudyInstanceUID);

                            using (var dr = cmd.ExecuteReader())
                            {
                                if (dr.Read())
                                {
                                    tag.StudyMemoUmu = Convert.ToInt32(dr["cnt"]);
                                }
                            }
                        }
                    }

                    //ソート用
                    tag.StudyInstanceUID = dcmTag.GetTagValue(DicomDic.Find("StudyInstanceUID").Tag);

                    tags.Add(tag);
                }
            }

            //ソート
            tags.Sort(new StudyTagComparer());
        }
Ejemplo n.º 4
0
        //画像一覧の取得
        public static void GetImageList(LoginItem login, SeriesKey key, out List <ImageTag> imTags, out List <SeriesTag> seTags)
        {
            imTags = null;
            seTags = null;
            var tags = new List <ImageTag>();

            if (key.IsImage)
            {
                var imkey = new ImageKey()
                {
                    StudyInstanceUID  = key.StudyInstanceUID,
                    SeriesInstanceUID = key.SeriesInstanceUID,
                    SOPInstanceUID    = key.SOPInstanceUID,
                    StorageID         = login.StorageID
                };

                var tag = new ImageTag();
                tag.ImageKey = ConvertUtil.Serialize(imkey);

                tags.Add(tag);
            }
            else
            {
                using (var pc = new PacsComm())
                {
                    DicomTagsResult ret = pc.CFindImage(key.StudyInstanceUID, key.SeriesInstanceUID);
                    if (!ret.IsSuccess)
                    {
                        LogUtil.Error("CFINDに失敗しました。");
                        return;
                    }

                    foreach (var dcmTag in ret.Tags)
                    {
                        var imkey = new ImageKey()
                        {
                            StudyInstanceUID  = key.StudyInstanceUID,
                            SeriesInstanceUID = key.SeriesInstanceUID,
                            SOPInstanceUID    = dcmTag.GetTagValue(DicomDic.Find("SOPInstanceUID").Tag),
                            StorageID         = login.StorageID
                        };

                        var tag = new ImageTag();
                        tag.ImageKey = ConvertUtil.Serialize(imkey);
                        Int64.TryParse(dcmTag.GetTagValue(DicomDic.Find("InstanceNumber").Tag), out tag.InstanceNumber);

                        //ソート用
                        tag.SOPInstanceUID = dcmTag.GetTagValue(DicomDic.Find("SOPInstanceUID").Tag);

                        tags.Add(tag);
                    }
                }

                //ソート
                tags.Sort(new ImageTagComparer());
            }

            //DICOMファイルの取得
            int cnt = 0;

            foreach (var tag in tags)
            {
                var imkey = ConvertUtil.Deserialize <ImageKey>(tag.ImageKey);

                var sto = DbCacheUtil.GetStorage(imkey.StorageID);
                using (var imp = new Impersonate(sto.LogonUsername, sto.LogonPassword))
                {
                    var dcmfile = FileUtil.GetDicomFile(imkey);
                    if (!File.Exists(dcmfile))
                    {
                        cnt++;
                    }
                }
            }
            if (cnt > 0)
            {
                DCM.GetImage(login, key);
            }

            int MultiCount = 0;

            //タグの取得
            foreach (var tag in tags)
            {
                var imkey = ConvertUtil.Deserialize <ImageKey>(tag.ImageKey);

                var sto = DbCacheUtil.GetStorage(imkey.StorageID);
                using (var imp = new Impersonate(sto.LogonUsername, sto.LogonPassword))
                {
                    var dcmfile = FileUtil.GetDicomFile(imkey);
                    if (File.Exists(dcmfile))
                    {
                        ImageTag tmp = null;
                        DicomUtil.GetImageTag(dcmfile, out tmp);

                        tag.InstanceNumber          = tmp.InstanceNumber;
                        tag.SliceThickness          = tmp.SliceThickness;
                        tag.ImagePositionPatient    = tmp.ImagePositionPatient;
                        tag.ImageOrientationPatient = tmp.ImageOrientationPatient;
                        tag.SliceLocation           = tmp.SliceLocation;
                        tag.Rows           = tmp.Rows;
                        tag.Columns        = tmp.Columns;
                        tag.PixelSpacing   = tmp.PixelSpacing;
                        tag.WindowCenter   = tmp.WindowCenter;
                        tag.WindowWidth    = tmp.WindowWidth;
                        tag.NumberOfFrames = tmp.NumberOfFrames;

                        if (tag.IsMultiframe)
                        {
                            MultiCount += 1;
                        }
                    }
                }
            }

            if (key.IsImage)
            {
                var sto = DbCacheUtil.GetStorage(key.StorageID);
                using (var imp = new Impersonate(sto.LogonUsername, sto.LogonPassword))
                {
                    var dcmfile = FileUtil.GetDicomFile(key);
                    if (File.Exists(dcmfile))
                    {
                        imTags = new List <ImageTag>();

                        ImageTag tmp = tags[0];
                        if (tmp.IsMultiframe)
                        {
                            for (var i = 0; i < tmp.NumberOfFrames; i++)
                            {
                                var imkey = new ImageKey()
                                {
                                    StudyInstanceUID  = key.StudyInstanceUID,
                                    SeriesInstanceUID = key.SeriesInstanceUID,
                                    SOPInstanceUID    = key.SOPInstanceUID,
                                    FrameNumber       = i,
                                };

                                var tag = new ImageTag();
                                tag.ImageKey                = ConvertUtil.Serialize(imkey);
                                tag.InstanceNumber          = i;
                                tag.SliceThickness          = tmp.SliceThickness;
                                tag.ImagePositionPatient    = tmp.ImagePositionPatient;
                                tag.ImageOrientationPatient = tmp.ImageOrientationPatient;
                                tag.SliceLocation           = tmp.SliceLocation;
                                tag.Rows           = tmp.Rows;
                                tag.Columns        = tmp.Columns;
                                tag.PixelSpacing   = tmp.PixelSpacing;
                                tag.WindowCenter   = tmp.WindowCenter;
                                tag.WindowWidth    = tmp.WindowWidth;
                                tag.NumberOfFrames = tmp.NumberOfFrames;

                                imTags.Add(tag);
                            }
                        }
                        else
                        {
                            imTags.Add(tmp);
                        }
                    }
                }
            }
            else if (MultiCount >= 1)
            {
                //マルチフレームがある場合はシリーズで返す
                seTags = new List <SeriesTag>();

                foreach (var tag in tags)
                {
                    var imkey = ConvertUtil.Deserialize <ImageKey>(tag.ImageKey);

                    var sto = DbCacheUtil.GetStorage(imkey.StorageID);
                    using (var imp = new Impersonate(sto.LogonUsername, sto.LogonPassword))
                    {
                        var dcmfile = FileUtil.GetDicomFile(imkey);
                        if (File.Exists(dcmfile))
                        {
                            SeriesTag tmp;
                            DicomUtil.GetSeriesTag(dcmfile, out tmp);

                            var sekey = new SeriesKey()
                            {
                                StudyInstanceUID  = imkey.StudyInstanceUID,
                                SeriesInstanceUID = imkey.SeriesInstanceUID,
                                SOPInstanceUID    = imkey.SOPInstanceUID,
                                StorageID         = login.StorageID,
                                IsImage           = true,
                                IsPacsSearch      = key.IsPacsSearch
                            };

                            tmp.SeriesKey = ConvertUtil.Serialize(sekey);

                            seTags.Add(tmp);
                        }
                    }
                }

                //ソート
                seTags = seTags.OrderBy(n => n.SeriesNumber).ToList();
            }
            else
            {
                imTags = tags;
            }
        }
Ejemplo n.º 5
0
        //シリーズ一覧の取得
        public static void GetSeriesList(StudyKey key, out List <SeriesTag> seTags)
        {
            seTags = new List <SeriesTag>();
            var tags = new List <SeriesTag>();

            using (var pc = new PacsComm())
            {
                DicomTagsResult ret = pc.CFindSeries(key.StudyInstanceUID);
                if (!ret.IsSuccess)
                {
                    LogUtil.Error("CFINDに失敗しました。");
                    return;
                }

                foreach (var dcmTag in ret.Tags)
                {
                    string mod = dcmTag.GetTagValue(DicomDic.Find("Modality").Tag);

                    //無視するモダリティ
                    if (Array.IndexOf(AppUtil.SkipModality, mod) >= 0)
                    {
                        continue;
                    }

                    var sekey = new SeriesKey()
                    {
                        StudyInstanceUID  = key.StudyInstanceUID,
                        SeriesInstanceUID = dcmTag.GetTagValue(DicomDic.Find("SeriesInstanceUID").Tag),
                        IsImage           = false,
                        IsPacsSearch      = true
                    };

                    var tag = new SeriesTag();
                    tag.SeriesKey = ConvertUtil.Serialize(sekey);
                    tag.Modality  = mod;
                    Int64.TryParse(dcmTag.GetTagValue(DicomDic.Find("SeriesNumber").Tag), out tag.SeriesNumber);
                    Int32.TryParse(dcmTag.GetTagValue(DicomDic.Find("NumberOfSeriesRelatedInstances").Tag), out tag.NumberOfImages);
                    tag.SeriesDescription = dcmTag.GetTagValue(DicomDic.Find("SeriesDescription").Tag);

                    //ソート用
                    tag.SeriesInstanceUID = dcmTag.GetTagValue(DicomDic.Find("SeriesInstanceUID").Tag);

                    tags.Add(tag);
                }
            }

            //ソート
            tags.Sort(new SeriesTagComparer());

            //重複チェック
            foreach (var tag in tags)
            {
                var sekey = ConvertUtil.Deserialize <SeriesKey>(tag.SeriesKey);

                bool chk = true;
                foreach (var setag in seTags)
                {
                    var sekey2 = ConvertUtil.Deserialize <SeriesKey>(setag.SeriesKey);

                    if (sekey.StudyInstanceUID == sekey2.StudyInstanceUID && sekey.SeriesInstanceUID == sekey2.SeriesInstanceUID)
                    {
                        chk = false;
                        break;
                    }
                }

                if (chk)
                {
                    seTags.Add(tag);
                }
            }
        }
Ejemplo n.º 6
0
        //スタディの取得 (URLコール用)
        public static bool GetStudyKey(FindParam prm, out string patientid, out List <string> studykey)
        {
            patientid = "";
            studykey  = new List <string>();

            var tags = new List <StudyTag>();

            using (var pc = new PacsComm())
            {
                var prm2 = new PacsComm.FindParam();
                prm2.SetStudyDate(prm.StudyDateFrom, prm.StudyDateTo);
                prm2.AccessionNumber = prm.AccessionNumber;
                prm2.PatientName     = prm.PatientName;
                prm2.PatientID       = prm.PatientID;
                prm2.Modality        = prm.Modality;

                DicomTagsResult ret = pc.CFindStudy(prm2);
                if (!ret.IsSuccess)
                {
                    LogUtil.Error("CFINDに失敗しました。");
                    return(true);
                }

                foreach (var dcmTag in ret.Tags)
                {
                    var tag = new StudyTag();
                    tag.StudyDate = dcmTag.GetTagValue(DicomDic.Find("StudyDate").Tag);
                    tag.StudyTime = dcmTag.GetTagValue(DicomDic.Find("StudyTime").Tag);
                    tag.PatientID = dcmTag.GetTagValue(DicomDic.Find("PatientID").Tag);

                    //ソート用
                    tag.StudyInstanceUID = dcmTag.GetTagValue(DicomDic.Find("StudyInstanceUID").Tag);

                    tags.Add(tag);
                }
            }

            if (tags.Count == 0)
            {
                return(true);
            }

            //ソート
            tags.Sort(new StudyTagComparer());

            foreach (var tag in tags)
            {
                var key = new StudyKey()
                {
                    StudyInstanceUID = tag.StudyInstanceUID,
                    IsPacsSearch     = true
                };
                studykey.Add(ConvertUtil.Serialize(key));

                if (studykey.Count == 1)
                {
                    patientid = tag.PatientID;
                }
                else
                {
                    if (patientid != tag.PatientID)
                    {
                        patientid = null;
                        studykey  = null;
                        return(false);
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 7
0
        public static void LoginUrl(string loginID, out string SID)
        {
            SID = null;
            var now = DateTime.Now;

            using (var db = new TryDbConnection(settings))
            {
                using (var cmd = db.CreateCommand())
                {
                    cmd.CommandText = "SELECT PASSWORD FROM UserTbl WHERE USER_ID=@0";
                    cmd.Add(loginID);

                    using (var dr = cmd.ExecuteReader())
                    {
                        if (dr.Read())
                        {
                        }
                        else
                        {
                            return;
                        }
                    }
                }
            }

            using (var db = new TryDbConnection(LCL.settings))
            {
                db.BeginTransaction();
                try
                {
                    string sid = null;
                    lock (typeof(LCL))
                    {
                        var len = new Random(Environment.TickCount).Next(8, 16);
                        sid = System.Web.Security.Membership.GeneratePassword(len, 0);
                    }

                    //有効期限の作成
                    using (var cmd = db.CreateCommand())
                    {
                        cmd.CommandText = "INSERT INTO M_Login(SID,GroupID,UserID,StorageID,TimeLimit) VALUES(@0,@1,@2,@3,@4)";
                        cmd.Add(sid);
                        cmd.Add("");
                        cmd.Add(loginID);
                        cmd.Add("");
                        cmd.Add(now.AddHours(AppUtil.TimeLimit));

                        cmd.ExecuteNonQuery();
                    }

                    db.Commit();

                    SID = sid;
                }
                catch (Exception ex)
                {
                    db.Rollback();
                    LogUtil.Error(ex.ToString());
                }
            }
        }
Ejemplo n.º 8
0
        //STUDYの更新
        public static bool UpdateStudy(string StudyUid)
        {
            for (int i = 0; i < AppUtil.RetryCount; i++)
            {
                using (var db = new TryDbConnection(settings))
                {
                    var modList = new List <string>();
                    var bodList = new List <string>();
                    int images  = 0;

                    using (var cmd = db.CreateCommand())
                    {
                        cmd.CommandText = "SELECT Modality,BodyPartExamined,NumberOfImages FROM T_Series WHERE StudyInstanceUID=@0 ORDER BY SeriesNumber";
                        cmd.Add(StudyUid);

                        using (var dr = cmd.ExecuteReader())
                        {
                            var modUQ = new List <string>();
                            var bodUQ = new List <string>();

                            while (dr.Read())
                            {
                                var mod = ((string)dr["Modality"]).Trim();
                                if (mod != "" && !modUQ.Contains(mod.ToUpper()))
                                {
                                    modList.Add(mod);
                                    modUQ.Add(mod.ToUpper());
                                }

                                var bod = ((string)dr["BodyPartExamined"]).Trim();
                                if (bod != "" && !bodUQ.Contains(bod.ToUpper()))
                                {
                                    bodList.Add(bod);
                                    bodUQ.Add(bod.ToUpper());
                                }

                                images += (int)dr["NumberOfImages"];
                            }
                        }
                    }

                    db.BeginTransaction();
                    try
                    {
                        using (var cmd = db.CreateCommand())
                        {
                            var sb = new StringBuilder();
                            sb.Append("UPDATE T_Study SET NumberOfImages=" + cmd.Add(images).ParameterName);

                            if (modList.Count > 0)
                            {
                                sb.Append(",Modality=" + cmd.Add(modList.ToString('\\', LEN_Study_Modality)).ParameterName);
                            }

                            if (bodList.Count > 0)
                            {
                                sb.Append(",BodyPartExamined=" + cmd.Add(bodList.ToString('\\', LEN_Study_BodyPartExamined)).ParameterName);
                            }

                            sb.Append(" WHERE StudyInstanceUID=" + cmd.Add(StudyUid).ParameterName);

                            cmd.CommandText = sb.ToString();

                            cmd.ExecuteNonQuery();
                        }

                        db.Commit();
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        db.Rollback();
                        LogUtil.Warn(ex.ToString());
                    }
                }

                //リトライ
                if (i < AppUtil.RetryCount - 1)
                {
                    System.Threading.Thread.Sleep(AppUtil.SleepTime);
                    LogUtil.Info1("RETRY:{0}", i + 1);
                }
                else
                {
                    LogUtil.Error("T_Study更新:失敗");
                    return(false);
                }
            }

            return(false);
        }
Ejemplo n.º 9
0
        //検査メモの設定
        public static bool SetStudyMemo(StudyKey key, StudyMemoItem item)
        {
            for (int i = 0; i < AppUtil.RetryCount; i++)
            {
                string err = "";
                var    now = DateTime.Now;

                using (var db = new TryDbConnection(settings))
                {
                    db.BeginTransaction();
                    try
                    {
                        using (var cmd = db.CreateCommand())
                        {
                            cmd.CommandText = "DELETE FROM T_StudyMemo WHERE StudyInstanceUID=@0";
                            cmd.Add(key.StudyInstanceUID);

                            cmd.ExecuteNonQuery();
                        }

                        if (item.Memo.Trim() != "")
                        {
                            using (var cmd = db.CreateCommand())
                            {
                                cmd.CommandText = "INSERT INTO T_StudyMemo(StudyInstanceUID,MemoDate,Memo,UserName) VALUES(@0,@1,@2,@3)";
                                cmd.Add(key.StudyInstanceUID);
                                cmd.Add(now);
                                cmd.Add(item.Memo);
                                cmd.Add(item.UserName);

                                cmd.ExecuteNonQuery();
                            }
                        }

                        using (var cmd = db.CreateCommand())
                        {
                            cmd.CommandText = "INSERT INTO T_StudyMemoHistory(StudyInstanceUID,MemoDate,Memo,UserName) VALUES(@0,@1,@2,@3)";
                            cmd.Add(key.StudyInstanceUID);
                            cmd.Add(now);
                            cmd.Add(item.Memo);
                            cmd.Add(item.UserName);

                            cmd.ExecuteNonQuery();
                        }

                        db.Commit();
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        db.Rollback();
                        err = ex.ToString();
                    }
                }

                //リトライ
                if (i < AppUtil.RetryCount - 1)
                {
                    System.Threading.Thread.Sleep(AppUtil.SleepTime);
                }
                else
                {
                    LogUtil.Error(err);
                }
            }

            return(false);
        }
Ejemplo n.º 10
0
        static AppUtil()
        {
            //LOGフォルダ
            LogPath = Path.Combine(LogPath, Path.GetFileName(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath.TrimEnd('\\')));

            LogUtil.Info("START");

            //ライセンスチェック
            if (File.Exists(LicensePath))
            {
                //////var License = File.ReadAllText(LicensePath);
                //////if (License != CryptoUtil.LicenseString())
                //////{
                //////    LogUtil.Error("License NG");
                //////    return;
                //////}
            }
            else
            {
                LogUtil.Error("License Not Found");
                return;
            }

            //ServerConfig取得
            Dictionary <string, string> svcfg;

            LCL.GetServerConfig(out svcfg);

            //サーバー設定
            if (svcfg.ContainsKey("DbType"))
            {
                DbType = svcfg["DbType"];
            }
            if (svcfg.ContainsKey("LoginAuth"))
            {
                LoginAuth = svcfg["LoginAuth"];
            }

            if (svcfg.ContainsKey("ThumbPath"))
            {
                ThumbPath = svcfg["ThumbPath"];
            }
            if (svcfg.ContainsKey("ReportPath"))
            {
                ReportPath = svcfg["ReportPath"];
            }
            if (svcfg.ContainsKey("MemoOutputPath"))
            {
                MemoOutputPath = svcfg["MemoOutputPath"];
            }
            if (svcfg.ContainsKey("DeletePath"))
            {
                DeletePath = svcfg["DeletePath"];
            }

            if (svcfg.ContainsKey("RetryCount"))
            {
                RetryCount = int.Parse(svcfg["RetryCount"]);
            }
            if (svcfg.ContainsKey("SleepTime"))
            {
                SleepTime = int.Parse(svcfg["SleepTime"]);
            }

            if (svcfg.ContainsKey("DBTimeout"))
            {
                DBTimeout = int.Parse(svcfg["DBTimeout"]);
            }
            if (svcfg.ContainsKey("ExeTimeout"))
            {
                ExeTimeout = int.Parse(svcfg["ExeTimeout"]) * 1000;
            }

            if (svcfg.ContainsKey("LockoutThreshold"))
            {
                LockoutThreshold = int.Parse(svcfg["LockoutThreshold"]);
            }
            if (svcfg.ContainsKey("LockoutDuration"))
            {
                LockoutDuration = int.Parse(svcfg["LockoutDuration"]);
            }
            if (svcfg.ContainsKey("LockoutReset"))
            {
                LockoutReset = int.Parse(svcfg["LockoutReset"]);
            }

            if (svcfg.ContainsKey("TimeLimit"))
            {
                TimeLimit = int.Parse(svcfg["TimeLimit"]);
            }

            if (svcfg.ContainsKey("MaxStudyList"))
            {
                MaxStudyList = int.Parse(svcfg["MaxStudyList"]);
            }

            if (svcfg.ContainsKey("DicomExt"))
            {
                DicomExt = svcfg["DicomExt"];
            }
            if (svcfg.ContainsKey("CompExe"))
            {
                CompExe = svcfg["CompExe"];
            }
            if (svcfg.ContainsKey("CompType"))
            {
                CompType = svcfg["CompType"];
            }
            if (svcfg.ContainsKey("CompOption"))
            {
                CompOption = svcfg["CompOption"];
            }
            if (svcfg.ContainsKey("ThumbPos"))
            {
                ThumbPos = svcfg["ThumbPos"];
            }

            if (svcfg.ContainsKey("LoginUrl"))
            {
                LoginUrl = svcfg["LoginUrl"];
            }

            if (svcfg.ContainsKey("RapidServ_Port"))
            {
                rsPort = ushort.Parse(svcfg["RapidServ_Port"]);
            }
            if (svcfg.ContainsKey("RapidServ_Nas"))
            {
                rsNas = int.Parse(svcfg["RapidServ_Nas"]);
            }
            if (svcfg.ContainsKey("RapidServ_Max"))
            {
                rsMax = int.Parse(svcfg["RapidServ_Max"]);
            }
            if (svcfg.ContainsKey("RapidServ_CM_PatientID"))
            {
                cmPatientID = int.Parse(svcfg["RapidServ_CM_PatientID"]);
            }
            if (svcfg.ContainsKey("RapidServ_CM_PatientName"))
            {
                cmPatientName = int.Parse(svcfg["RapidServ_CM_PatientName"]);
            }
            if (svcfg.ContainsKey("RapidServ_CM_AccessionNumber"))
            {
                cmAccessionNumber = int.Parse(svcfg["RapidServ_CM_AccessionNumber"]);
            }
            if (svcfg.ContainsKey("RapidServ_CM_Modality"))
            {
                cmModality = int.Parse(svcfg["RapidServ_CM_Modality"]);
            }

            if (svcfg.ContainsKey("YComClientInfo"))
            {
                YComClientInfo = svcfg["YComClientInfo"];
            }
            if (svcfg.ContainsKey("YComHospitalID"))
            {
                YComHospitalID = svcfg["YComHospitalID"];
            }
            if (svcfg.ContainsKey("YComUserID"))
            {
                YComUserID = svcfg["YComUserID"];
            }
            if (svcfg.ContainsKey("YComOnlineLocation"))
            {
                YComOnlineLocation = int.Parse(svcfg["YComOnlineLocation"]);
            }

            if (svcfg.ContainsKey("DcmtkExePath"))
            {
                DcmtkExePath = svcfg["DcmtkExePath"];
            }
            if (svcfg.ContainsKey("DcmtkDicPath"))
            {
                DcmtkDicPath = svcfg["DcmtkDicPath"];
            }
            if (svcfg.ContainsKey("DcmtkTempPath"))
            {
                DcmtkTempPath = svcfg["DcmtkTempPath"];
            }
            if (svcfg.ContainsKey("DcmtkCFindOptions"))
            {
                DcmtkCFindOptions = svcfg["DcmtkCFindOptions"];
            }
            if (svcfg.ContainsKey("DcmtkCMoveOptions"))
            {
                DcmtkCMoveOptions = svcfg["DcmtkCMoveOptions"];
            }
            if (svcfg.ContainsKey("DcmtkMyAETitle"))
            {
                DcmtkMyAETitle = svcfg["DcmtkMyAETitle"];
            }
            if (svcfg.ContainsKey("DcmtkMyPort"))
            {
                DcmtkMyPort = svcfg["DcmtkMyPort"];
            }
            if (svcfg.ContainsKey("DcmtkPacsAETitle"))
            {
                DcmtkPacsAETitle = svcfg["DcmtkPacsAETitle"];
            }
            if (svcfg.ContainsKey("DcmtkPacsPeer"))
            {
                DcmtkPacsPeer = svcfg["DcmtkPacsPeer"];
            }
            if (svcfg.ContainsKey("DcmtkPacsPort"))
            {
                DcmtkPacsPort = svcfg["DcmtkPacsPort"];
            }

            if (svcfg.ContainsKey("CFindTimeout"))
            {
                CFindTimeout = int.Parse(svcfg["CFindTimeout"]) * 1000;
            }
            if (svcfg.ContainsKey("CMoveTimeout"))
            {
                CMoveTimeout = int.Parse(svcfg["CMoveTimeout"]) * 1000;
            }

            if (svcfg.ContainsKey("ImageCacheMax"))
            {
                ImageCacheMax = int.Parse(svcfg["ImageCacheMax"]);
            }
            if (svcfg.ContainsKey("ImageCacheTime"))
            {
                ImageCacheTime = int.Parse(svcfg["ImageCacheTime"]);
            }

            if (svcfg.ContainsKey("HideData"))
            {
                HideData = svcfg["HideData"];
            }

            string mods = "";

            if (svcfg.ContainsKey("SkipModality"))
            {
                mods = svcfg["SkipModality"];
            }
            SkipModality = mods.Split(',');

            mods = "";
            if (svcfg.ContainsKey("ModalityCompType"))
            {
                mods = svcfg["ModalityCompType"];
            }
            foreach (string mod in mods.Split(','))
            {
                string[] tmp = mod.Split('=');
                if (tmp.Length > 1)
                {
                    ModalityCompType.Add(tmp[0], tmp[1]);
                }
            }

            mods = "";
            if (svcfg.ContainsKey("ModalityCompOption"))
            {
                mods = svcfg["ModalityCompOption"];
            }
            foreach (string mod in mods.Split(','))
            {
                string[] tmp = mod.Split('=');
                if (tmp.Length > 1)
                {
                    ModalityCompOption.Add(tmp[0], tmp[1]);
                }
            }

            mods = "";
            if (svcfg.ContainsKey("ModalityThumbPos"))
            {
                mods = svcfg["ModalityThumbPos"];
            }
            foreach (string mod in mods.Split(','))
            {
                string[] tmp = mod.Split('=');
                if (tmp.Length > 1)
                {
                    ModalityThumbPos.Add(tmp[0], tmp[1]);
                }
            }

            string addr = "";

            if (svcfg.ContainsKey("RapidServ_Addr"))
            {
                addr = svcfg["RapidServ_Addr"];
            }
            if (addr != "")
            {
                var tmp1 = new List <byte>();
                foreach (var s in addr.Split('.'))
                {
                    tmp1.Add(Convert.ToByte(s));
                }
                rsAddr = tmp1.ToArray();
            }

            //TryDb初期化
            TryDb.TryDbConfig.CommandTimeout = DBTimeout;
        }
Ejemplo n.º 11
0
        //サムネイルの作成
        public static void GetThumbnail(SeriesKey key, out byte[] thumb)
        {
            thumb = null;

            if (key.SOPInstanceUID == null || key.SOPInstanceUID == "")
            {
                using (var pc = new PacsComm())
                {
                    DicomTagsResult ret = pc.CFindImage(key.StudyInstanceUID, key.SeriesInstanceUID);
                    if (!ret.IsSuccess)
                    {
                        LogUtil.Error("CFINDに失敗しました。");
                        return;
                    }

                    var tags = new List <Tuple <string, long> >();

                    foreach (var dcmTag in ret.Tags)
                    {
                        long InstanceNumber = 0;
                        Int64.TryParse(dcmTag.GetTagValue(DicomDic.Find("InstanceNumber").Tag), out InstanceNumber);

                        var tag = Tuple.Create(dcmTag.GetTagValue(DicomDic.Find("SOPInstanceUID").Tag), InstanceNumber);
                        tags.Add(tag);
                    }

                    //ソート
                    tags = tags.OrderBy(n => n.Item2).ToList();

                    if (tags.Count > 0)
                    {
                        key.SOPInstanceUID = tags[0].Item1;
                    }
                }
            }

            if (key.SOPInstanceUID != null && key.SOPInstanceUID != "")
            {
                //DICOMがある
                {
                    LCL.GetImageStorageID(ref key);
                    if (key.StorageID != null && key.StorageID != "")
                    {
                        var sto = DbCacheUtil.GetStorage(key.StorageID);
                        using (var imp = new Impersonate(sto.LogonUsername, sto.LogonPassword))
                        {
                            var file = FileUtil.GetDicomFile(key);
                            if (File.Exists(file))
                            {
                                DicomUtil.DicomToThumb(file, out thumb);
                                if (thumb != null)
                                {
                                    return;
                                }
                            }
                        }
                    }
                }

                //DICOMがない
                using (var pc = new PacsComm())
                {
                    //画像取得
                    DicomFilesResult ret = pc.CMoveImage(key.StudyInstanceUID, key.SeriesInstanceUID, key.SOPInstanceUID);
                    if (!ret.IsSuccess)
                    {
                        LogUtil.Error("CMoveImage");
                        return;
                    }

                    if (ret.Files.Length == 0)
                    {
                        LogUtil.Error("CMoveImage [File=0]");
                        return;
                    }

                    LogUtil.Debug1("CMoveImage [File={0}]", ret.Files.Length.ToString());

                    foreach (DicomFile dcmfile in ret.Files)
                    {
                        var file = dcmfile.FileName.Trim();
                        if (!File.Exists(file))
                        {
                            continue;
                        }

                        DicomUtil.DicomToThumb(file, out thumb);

                        if (thumb != null)
                        {
                            return;
                        }
                    }
                }
            }
        }
Ejemplo n.º 12
0
        private static void GetImage(string UserName, string StorageID, string StudyUID, string SeriesUID, string SopUID)
        {
            LogUtil.Debug3("CMOVE [{0}][{1}][{2}]", StudyUID, SeriesUID, SopUID);

            var sto = DbCacheUtil.GetStorage(StorageID);

            using (var pc = new PacsComm())
            {
                //画像取得
                DicomFilesResult ret = pc.CMoveImage(StudyUID, SeriesUID, SopUID);
                if (!ret.IsSuccess)
                {
                    LogUtil.Error("CMoveImage");
                    return;
                }

                if (ret.Files.Length == 0)
                {
                    LogUtil.Error("CMoveImage [File=0]");
                    return;
                }

                LogUtil.Debug1("CMoveImage [File={0}]", ret.Files.Length.ToString());

                var seriesList = new Dictionary <string, List <Dictionary <string, string> > >();
                int cnt        = 0;

                foreach (DicomFile dcmfile in ret.Files)
                {
                    var file = dcmfile.FileName.Trim();
                    if (!File.Exists(file))
                    {
                        continue;
                    }

                    var tags = new Dictionary <string, string>();

                    tags.Add("StorageID", sto.StorageID);
                    tags.Add("UserName", UserName);

                    tags.Add("AETitle", "");
                    tags.Add("File", file);

                    var fi = new FileInfo(file);
                    tags.Add("FileSize", fi.Length.ToString());

                    //タグ取得
                    using (var dcm = new DicomData(file))
                    {
                        var tmpTags = new List <uint>(DcmTag.ToTagArray(AppUtil.IMAGE_TAG));
                        var dic     = DicomTagDictionary.Open(dcm, tmpTags.ToArray());

                        foreach (DcmTag dcmTag in AppUtil.IMAGE_TAG)
                        {
                            tags.Add(dcmTag.Name, dic.GetString(dcmTag.Tag));
                        }

                        if (dcm.Images.Load())
                        {
                            if (dcm.Images.Bits == 8 || dcm.Images.Bits == 24)
                            {
                                tags.SetString("WindowCenter", "127");
                                tags.SetString("WindowWidth", "255");
                            }
                            else
                            {
                                ImageControl ctrl = null;

                                if (dcm.Images.WindowCenters.Length > 0)
                                {
                                    tags.SetString("WindowCenter", dcm.Images.WindowCenters[0].ToString());
                                }
                                else
                                {
                                    if (ctrl == null)
                                    {
                                        ctrl = dcm.Images.CreateImageControl(0);
                                    }

                                    //MinMax
                                    if (ctrl != null)
                                    {
                                        tags.SetString("WindowCenter", ctrl.WindowCenter.ToString());
                                    }
                                }

                                if (dcm.Images.WindowWidths.Length > 0)
                                {
                                    tags.SetString("WindowWidth", dcm.Images.WindowWidths[0].ToString());
                                }
                                else
                                {
                                    if (ctrl == null)
                                    {
                                        ctrl = dcm.Images.CreateImageControl(0);
                                    }

                                    //MinMax
                                    if (ctrl != null)
                                    {
                                        tags.SetString("WindowWidth", ctrl.WindowWidth.ToString());
                                    }
                                }
                            }
                        }
                    }

                    var studyUid  = tags[DcmTag.StudyInstanceUID.Name];
                    var seriesUid = tags[DcmTag.SeriesInstanceUID.Name];
                    var sopUid    = tags[DcmTag.SOPInstanceUID.Name];
                    var mod       = tags[DcmTag.Modality.Name];

                    //DICOMチェック
                    if (studyUid == "" || seriesUid == "" || sopUid == "" || mod == "")
                    {
                        LogUtil.Error1("NOT DICOM [{0}]", Path.GetFileName(file));
                        continue;
                    }

                    //無視するモダリティ
                    if (Array.IndexOf(AppUtil.SkipModality, mod) >= 0)
                    {
                        LogUtil.Debug2("SKIP:{0} [{1}]", mod, Path.GetFileName(file));
                        continue;
                    }

                    if (!seriesList.ContainsKey(seriesUid))
                    {
                        seriesList.Add(seriesUid, new List <Dictionary <string, string> >());
                    }

                    seriesList[seriesUid].Add(tags);
                    cnt++;
                }

                //SERIES毎のSOPソート
                foreach (var series in seriesList.Values)
                {
                    series.Sort((x, y) =>
                    {
                        long n1, n2;
                        if (!long.TryParse(x[DcmTag.SeriesNumber.Name], out n1))
                        {
                            n1 = long.MaxValue;
                        }
                        if (!long.TryParse(y[DcmTag.SeriesNumber.Name], out n2))
                        {
                            n2 = long.MaxValue;
                        }
                        return((int)(n1 - n2));
                    });
                }

                int idx = 0;

                foreach (var series in seriesList.Values)
                {
                    if (series.Count == 0)
                    {
                        continue;
                    }

                    LogUtil.Info5("AETitle[{0}] StudyDate[{1}] StudyTime[{2}] Modality[{3}] PatientID[{4}]",
                                  series[0]["AETitle"], series[0][DcmTag.StudyDate.Name], series[0][DcmTag.StudyTime.Name], series[0][DcmTag.Modality.Name], series[0][DcmTag.PatientID.Name]);

                    var importList = new List <Dictionary <string, string> >();

                    foreach (var sop in series)
                    {
                        var studyUid  = sop[DcmTag.StudyInstanceUID.Name];
                        var seriesUid = sop[DcmTag.SeriesInstanceUID.Name];
                        var sopUid    = sop[DcmTag.SOPInstanceUID.Name];
                        var file      = sop["File"];

                        idx++;
                        LogUtil.Debug3("{0}/{1} [{2}]", idx, cnt, Path.GetFileName(file));

                        //画像圧縮
                        using (var imp = new Impersonate(sto.LogonUsername, sto.LogonPassword))
                        {
                            var dicomFile = Path.Combine(sto.DicomPath, studyUid, seriesUid, sopUid + AppUtil.DicomExt);
                            if (DicomUtil.DicomToComp(file, dicomFile, sop))
                            {
                                sop.Add("DicomFile", dicomFile);
                                LogUtil.Debug("圧縮 end");

                                var fi = new FileInfo(dicomFile);
                                sop.Add("CompFileSize", fi.Length.ToString());
                            }
                            else
                            {
                                LogUtil.Error1("圧縮エラー [{0}]", file);
                                return;
                            }
                        }

                        importList.Add(sop);
                    }

                    //DB登録
                    if (importList.Count > 0)
                    {
                        if (DbUtil.DicomToDB(importList))
                        {
                            LogUtil.Debug("DB登録 end");
                        }
                        else
                        {
                            LogUtil.Error("DB登録エラー");
                        }
                    }
                    else
                    {
                        LogUtil.Debug("DB登録 なし");
                    }
                }

                //DB更新
                DbUtil.UpdateStudy(StudyUID);
            }
        }