Exemple #1
0
        protected bool ParseHeader(string p_strMsg, ref XmlDocument p_xml, ref HEADER p_header)
        {
            try
            {
                p_xml.LoadXml(p_strMsg);
                XmlElement headerTag = p_xml.SelectSingleNode("WRH_MSG/HEADER") as XmlElement;

                XmlElement element = headerTag.SelectSingleNode("Category") as XmlElement;
                p_header.Category = element.InnerText;

                element            = headerTag.SelectSingleNode("CommandNo") as XmlElement;
                p_header.CommandNo = element.InnerText;

                element          = headerTag.SelectSingleNode("Command") as XmlElement;
                p_header.Command = element.InnerText;

                element = headerTag.SelectSingleNode("RequesterId") as XmlElement;
                p_header.RequesterId = element.InnerText;

                element           = headerTag.SelectSingleNode("DateTime") as XmlElement;
                p_header.DateTime = element.InnerText;
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("[{0}] WRH 메세지 헤더 파싱중 예외가 발생하였습니다.[{1}]", m_nThreadNo, p_strMsg));
                return(false);
            }

            return(true);
        }
        // 페이지수 다르게 SPLIT
        //      파라미터 : 원본 파일 이름
        public static bool SplitTif(string p_strPath, string p_strSrcFile, string p_strPages, string p_strOutFilePrefix, ref List <DbModule.SPLIT_FILE_INFO> p_lstOutFiles)
        {
            bool   bResult;
            Bitmap srcFile = null;

            bResult = true;
            try
            {
                srcFile = new Bitmap(p_strPath + '/' + p_strSrcFile);

                if (!SplitTif(p_strPath, srcFile, p_strPages, p_strOutFilePrefix, ref p_lstOutFiles))
                {
                    bResult = false;
                }
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, "TIF파일 분리 시, 예외가 발생하였습니다.");
                bResult = false;
            }

            try
            {
                if (srcFile != null)
                {
                    srcFile.Dispose();
                }
            }
            catch { }

            return(bResult);
        }
Exemple #3
0
        /// <summary>
        /// Connect to pop3 server "host" using "port" and auth SSL as client.
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public bool Connect(string host, int port)
        {
            try
            {
                m_tcpClient = new TcpClient(host, port);
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, "Connect()");
                return(false);
            }

            try
            {
                //m_tcpClient.Connect(host, port);
                m_sslStream = new SslStream(m_tcpClient.GetStream());
                m_sslStream.AuthenticateAsClient(host);
                // Read the stream to make sure we are connected
                int bytes = m_sslStream.Read(m_buffer, 0, m_buffer.Length);
                return(Encoding.ASCII.GetString(m_buffer, 0, bytes).Contains("+OK"));
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("Connect()에서 다음과 같은 오류가 발생하였습니다."));
                return(false);
            }
        }
        // 페이지수 다르게 SPLIT
        //      파라미터 : 원본 파일 비트맵 객체
        public static bool SplitTif(string p_strPath, Bitmap p_srcFile, string p_strPages, string p_strOutFilePrefix, ref List <DbModule.SPLIT_FILE_INFO> p_lstOutFiles)
        {
            int from, to;

            char[] dash = new char[] { '-' };
            DbModule.SPLIT_FILE_INFO splitFileInfo = new DbModule.SPLIT_FILE_INFO();

            try
            {
                string[] pages = p_strPages.Split(new char[] { ',' });

                // SPLIT 루프
                for (int i = 0; i < pages.Length; ++i)
                {
                    // SPLIT 파일 정보 SET
                    splitFileInfo.Clear();
                    splitFileInfo.p_strPagesInOrg = pages[i];
                    splitFileInfo.p_strFile       = string.Format("{0}_{1}.tif", p_strOutFilePrefix, i + 1);

                    // SPLIT 파일 : from - to 얻기
                    string[] fromTo = pages[i].Split(dash);

                    if (fromTo.Length == 1)
                    {
                        from = Convert.ToInt32(fromTo[0]);
                        to   = from;;
                    }
                    else if (fromTo.Length == 2) // 예1) "3-5", 예2) "7-"
                    {
                        from = Convert.ToInt32(fromTo[0]);
                        if (fromTo[1].Length > 0)
                        {
                            to = Convert.ToInt32(fromTo[1]);                    // 예1) "3-5"
                        }
                        else
                        {
                            to = p_srcFile.GetFrameCount(FrameDimension.Page);  // 예2) "7-". 끝페이지까지
                        }
                    }
                    else
                    {
                        AppLog.Write(LOG_LEVEL.ERR, string.Format("TIF파일 분리 시, 분리 페이지 정보가 잘 못 되었습니다.({0})", p_strPages));
                        return(false);
                    }

                    // SPLIT
                    SplitTif(p_strPath, p_srcFile, from, to, ref splitFileInfo);

                    // SPLIT 파일 정보 추가
                    p_lstOutFiles.Add(splitFileInfo);
                }
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, "TIF파일 분리 시, 예외가 발생하였습니다.");
                return(false);
            }

            return(true);
        }
Exemple #5
0
        protected override void ThreadEntry()
        {
            HttpListenerContext context;

            AppLog.Write(LOG_LEVEL.MSG, string.Format("### [{0}] 큐 폴링 쓰레드 시작 ###", m_nThreadNo));
            while (!BtfaxThread.Stop)
            {
                Thread.Sleep(QUEUE_POLLING_SLEEP);
                context = WebRequestQueue.Instance.Dequeue();
                if (context == null)
                {
                    continue;
                }

                try
                {
                    RequestHandler(context);
                }
                catch (Exception ex)
                {
                    AppLog.ExceptionLog(ex, string.Format("[{0}] WEB 요청 처리시, 예외가 발생하였습니다.", m_nThreadNo));
                }
            }

            AppLog.Write(LOG_LEVEL.MSG, string.Format("### [{0}] 큐 폴링 쓰레드 종료 ###", m_nThreadNo));
        }
        /// <summary>
        /// 쓰레드 시작시 Process 폴더에 파일이 존재하면 Upload 폴더로 이동한다.
        /// </summary>
        private void CheckProcessFolder()
        {
            ///// 확인용, 작업용 확장자
            //string[] extensions = new string[] { Config.FILE_CHECK_EXT, Config.FILE_WORK_EXT }.Distinct().ToArray();
            /// Process 폴더의 모든 파일 가져오기
            string[] allFiles = Directory.GetFiles(m_ProcessPath);
            /// TIF, DAT 파일만 선택
            List <string> files = new List <string>();
            /// 파일 정보 변수
            FileInfo fi = null;

            /// 확인용 파일만 선택 (DAT)
            /// 작업용 파일만 선택 (TIF)
            files.AddRange(allFiles.Where((f) => f.Substring(f.LastIndexOf(".") + 1).ToUpper() == Config.FILE_CHECK_EXT ||
                                          f.Substring(f.LastIndexOf(".") + 1).ToUpper() == Config.FILE_WORK_EXT));

            try
            {
                foreach (string f in files)
                {
                    fi = new FileInfo(f);
                    fi.MoveTo(string.Format("{0}{1}", m_UploadPath, fi.Name));
                }
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("Process({0}) 경로의 파일을 Upload({1}) 경로로 이동중 오류가 발생하였지만 계속 진행합니다.", m_ProcessPath, m_ProcessPath));
            }
        }
Exemple #7
0
        /// <summary>
        /// 처리되지 않은 예외
        /// </summary>
        public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;

            AppLog.ExceptionLog(ex, string.Join("\t", "처리되지 않은 예외입니다.", "종료 여부 : ", e.IsTerminating.ToString()));
            Process.GetCurrentProcess().Kill();
            //throw ex;
        }
        public void ListenLoop_()
        {
            bool bResult = ThreadPool.SetMaxThreads(Config.SESSION_CNT, Config.SESSION_CNT);

            Socket sock_listen = null;

            try
            {
                IPEndPoint ep = new IPEndPoint(IPAddress.Any, Config.LISTEN_PORT);

                sock_listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock_listen.Bind(ep);
                sock_listen.Listen(Config.LISTEN_PORT);
                AppLog.Write(LOG_LEVEL.MSG, string.Format("### 리슨 시작 : 포트[{0}] ###", Config.LISTEN_PORT));

                while (!BtfaxThread.Stop)
                {
                    if (!sock_listen.Poll(ONE_SECOND, SelectMode.SelectRead))
                    {
                        continue;
                    }

                    Socket sock_session = sock_listen.Accept();

                    int nThreadCnt, nNotUse;
                    ThreadPool.GetAvailableThreads(out nThreadCnt, out nNotUse);
                    if (nThreadCnt <= 0)
                    {
                        AppLog.Write(LOG_LEVEL.WRN, "사용가능한 세션이 존재하지 않습니다. : GetAvailableThreads()");
                        SendErrorPacket(sock_session, RESULT.F_SESSION_FULL);
                        continue;
                    }

                    TcpSessionThread sessionThread = AssignSessionThread_();
                    if (sessionThread == null) // add bok - 20130528
                    {
                        AppLog.Write(LOG_LEVEL.WRN, "사용가능한 세션이 존재하지 않습니다. : AssignSessionThread_()");
                        SendErrorPacket(sock_session, RESULT.F_SESSION_FULL);
                        continue;
                    }

                    sessionThread.Socket = sock_session;
                    ThreadPool.QueueUserWorkItem(new WaitCallback(sessionThread.ThreadEntry));
                }
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, "리슨 소켓 쓰레드에서 다음과 같은 오류가 발생하였습니다.");
            }

            if (sock_listen != null)
            {
                sock_listen.Close();
            }

            AppLog.Write(LOG_LEVEL.MSG, string.Format("### 리슨 종료 : 포트[{0}] ###", Config.LISTEN_PORT));
        }
Exemple #9
0
        /// <summary>
        /// Name       : PollingLoop_
        /// Content    : 폴링 루프
        /// Writer     : 장동훈
        /// Date       : 2012.10.24
        /// </summary>
        private void PollingLoop_()
        {
            /// 마지막 실행시간 (Sleep 실행의 기준시간)
            /// 첫 Sleep 실행시 바로 실행 되도록 시간 수정
            DateTime lastExecuteTime = DateTime.Now.AddMilliseconds(Config.UDP_CHECK_POLLING_TIME * -1);

            try
            {
                while (!BtfaxThread.Stop)
                {
                    if (DateTime.Now.Subtract(lastExecuteTime).TotalMilliseconds < Config.UDP_CHECK_POLLING_TIME)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }

                    lastExecuteTime = DateTime.Now;

                    try
                    {
                        if (m_UdpSocket == null)
                        {
                            m_UdpSocket = new UdpSocket();
                            m_UdpSocket.UdpSocketInit(Config.LISTEN_PORT, Config.BUFFER_SIZE * 2, string.Format("FAX_{0}_FAS_{1}_UdpSocket", Config.SYSTEM_NO, Config.PROCESS_NO), true);
                            m_UdpSocket.OnSent        += new UdpSocket.UdpMessageSentEventHandler(this.UdpMessage_OnSent);
                            m_UdpSocket.OnReceived    += new UdpSocket.UdpMessageReceivedEventHandler(this.UdpMessage_OnReceived);
                            m_UdpSocket.OnRaisedError += new UdpSocket.UdpMessageRaisedErrorEventHandler(m_UdpSocket_OnRaisedError);

                            m_UdpSocket.StartListen();
                        }

                        lastExecuteTime = DateTime.Now;
                    }
                    catch (Exception ex)
                    {
                        lastExecuteTime = DateTime.Now;

                        m_UdpSocket.CloseClientSocket();
                        m_UdpSocket = null;

                        AppLog.ExceptionLog(ex, string.Format("{0} 쓰레드에서 다음과 같은 오류가 발생하였습니다.", m_ThreadName));
                    }
                }

                m_UdpSocket.CloseClientSocket();
                m_UdpSocket = null;
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("{0} 쓰레드에서 다음과 같은 오류가 발생하였습니다. 쓰레드를 종료합니다.", m_ThreadName));
                throw ex;
            }
        }
Exemple #10
0
 protected string ComposeErrorResponse(RESULT p_result)
 {
     try
     {
         return(string.Format("<WRH_MSG><RESULT><Result>F</Result><Reason>{0}{1}</Reason><ReasonName>{2}</ ReasonName ></RESULT></WRH_MSG>",
                              'H', p_result.ToString("D3"), p_result.ToString()));
     }
     catch (Exception ex)
     {
         AppLog.ExceptionLog(ex, string.Format("[{0}] WRH 에러 메세지 생성 중 예외가 발생하였습니다.[{1}]", m_nThreadNo, p_result));
         return("<WRH_MSG><RESULT><Result>F</Result><Reason>H381</Reason><ReasonName>F_COMPOSE_ERROR</ ReasonName ></RESULT></WRH_MSG>");
     }
 }
        public string ConvertBase64ToFile(string localPath, POP3_BoundaryInfo bi)
        {
            if (bi.IsFileAttach == false)
            {
                return("");
            }

            if (string.Compare(bi.ContentTransferEncoding, "base64", true) != 0)
            {
                return("");
            }

            if (bi.Encoding != null)
            {
                return("");
            }

            string fileName = bi.RepresentationFilename;

            if (fileName.Length == 0)
            {
                return("");
            }



            if (Directory.Exists(localPath) == false)
            {
                Directory.CreateDirectory(localPath);
            }
            string filePath = string.Format("{0}{1}", localPath, fileName);

            try
            {
                byte[] data = ConvertBase64ToByteArray(GetBodyLines(bi));

                using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(data);
                    bw.Flush();
                }
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, "파일 생성에 실패했습니다.");
                filePath = "";
            }
            return(filePath);
        }
Exemple #12
0
        public POP3_Parsing GetMessage(int messageNumber)
        {
            POP3_Parsing parse = new POP3_Parsing();

            try
            {
                parse.MailMessage(RetrieveMessage(messageNumber));

                parse.ParseHeader();
                parse.ParseBody();
                parse.ConvertStringBoundaryBody();

                parse.IsParseSuccess = true;

                AppLog.Write(LOG_LEVEL.MSG, string.Format("[ Subject: {0} ] 메일을 수신 완료하였습니다.", parse.Subject));

                #region For Debug
                //AppLog.Write(LOG_LEVEL.TRC, "----------------------------------------------------------------------------------------------------");
                //AppLog.Write(LOG_LEVEL.TRC, parse.Subject);

                //foreach (POP3_BoundaryInfo info in parse.BoundaryInfoList)
                //{
                //    AppLog.IsDisplay = false;
                //    AppLog.Write(LOG_LEVEL.TRC, "----------------------------------------------------------------------------------------------------");
                //    AppLog.Write(LOG_LEVEL.TRC, "Convert Body                     : " + info.ContentType);
                //    AppLog.Write(LOG_LEVEL.TRC, "CharSet                          : " + info.ContentTypeCharSet);
                //    AppLog.Write(LOG_LEVEL.TRC, "ContentTransferEncoding          : " + info.ContentTransferEncoding);
                //    AppLog.Write(LOG_LEVEL.TRC, "ConvertBody                      : " + info.ConvertBody);
                //    AppLog.Write(LOG_LEVEL.TRC, "ContentTypeName                  : " + info.ContentTypeName);
                //    AppLog.Write(LOG_LEVEL.TRC, "ContentDispositionAttachFileName : " + info.ContentDispositionAttachFileName);
                //    AppLog.IsDisplay = true;
                //}
                //AppLog.Write(LOG_LEVEL.TRC, " ");
                //AppLog.Write(LOG_LEVEL.TRC, " ");
                //AppLog.Write(LOG_LEVEL.TRC, " ");
                //AppLog.Write(LOG_LEVEL.TRC, " ");
                //AppLog.Write(LOG_LEVEL.TRC, " ");
                //AppLog.Write(LOG_LEVEL.TRC, " ");
                #endregion
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("[ Subject:{0} ] 메일을 수신 실패하였습니다.", parse.Subject));
            }
            return(parse);
        }
        public bool Start()
        {
            try
            {
                AppLog.Write(LOG_LEVEL.MSG, string.Format("### 웹리스터 오픈 시도 : {0}", Config.HTTP_URL));
                m_listener.Prefixes.Add(Config.HTTP_URL);
                m_listener.Start();
                AppLog.Write(LOG_LEVEL.MSG, "### 웹리스터 오픈 시작됨 ###");

                IAsyncResult result = m_listener.BeginGetContext(new AsyncCallback(HttpRequestCallback), this);
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, "Web Listener 시작 시, 예외가 발생하였습니다.");
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Name       : PollingLoop_
        /// Content    : 폴링 루프
        /// Writer     : 장동훈
        /// Date       : 2012.10.24
        /// </summary>
        private void PollingLoop_()
        {
            /// 마지막 실행시간 (Sleep 실행의 기준시간)
            /// 첫 Sleep 실행시 바로 실행 되도록 시간 수정
            DateTime lastExecuteTime = DateTime.Now.AddMilliseconds(Config.UDP_CHECK_POLLING_TIME * -1);

            try
            {
                while (!BtfaxThread.Stop)
                {
                    if (DateTime.Now.Subtract(lastExecuteTime).TotalMilliseconds < Config.UDP_CHECK_POLLING_TIME)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }

                    lastExecuteTime = DateTime.Now;

                    try
                    {
                        if (m_SocketListener == null)
                        {
                            m_SocketListener = new SocketListener();
                        }
                    }
                    catch (Exception ex)
                    {
                        lastExecuteTime = DateTime.Now;
                        AppLog.ExceptionLog(ex, string.Format("{0} 쓰레드에서 다음과 같은 오류가 발생하였습니다.", m_ThreadName));
                        AppLog.ExceptionLog(ex, "리슨 소켓 쓰레드에서 다음과 같은 오류가 발생하였습니다.");
                    }
                }

                m_SocketListener.CleanUpOnExit();
                m_SocketListener = null;
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("{0} 쓰레드에서 다음과 같은 오류가 발생하였습니다. 쓰레드를 종료합니다.", m_ThreadName));
                throw ex;
            }
        }
        public static bool SendMail(string p_emailTO)
        {
            bool result = false;

            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(Config.SMTP_FROM);     // BTFAX 관리자 이메일 주소
                mail.To.Add(new MailAddress(p_emailTO));           // BTF_FAX_USER_MSTR.EMAIL_NOTIFY 컬럼의 이메일 주소

                mail.Subject         = Config.SMTP_SUBJECT;        // 제목
                mail.Body            = Config.SMTP_SUBJECT;        // 수신메세지
                mail.SubjectEncoding = Encoding.UTF8;
                mail.BodyEncoding    = Encoding.UTF8;

                using (SmtpClient smtpClient = new SmtpClient())
                {
                    smtpClient.Host = Config.SMTP_IP;                                     // SMTP Server IP
                    smtpClient.Port = Config.SMTP_PORT;                                   // SMTP Server Port

                    smtpClient.UseDefaultCredentials = Config.SMTP_USEDEFAULTCREDENTIALS; // 기본인증 사용 여부
                    smtpClient.EnableSsl             = Config.SMTP_ENABLESSL;             // 보안 연결 (SSL) 사용 여부
                    smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;        //
                    //smtpClient.Credentials = new NetworkCredential(id, pw);               // SMTP Server 인증 ID / PW
                    smtpClient.Timeout = Config.SMTP_TIMEOUT;                             // 연결 제한시간

                    try
                    {
                        smtpClient.Send(mail);
                        result = true;
                    }
                    catch (Exception ex)
                    {
                        AppLog.ExceptionLog(ex, string.Join("\t", "MailHelper()", "SendMail()"));
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Name       : PollingLoop_
        /// Parameters : Empty
        /// Content    : 폴링 루프
        /// Return     : Empty
        /// Writer     : 장동훈
        /// Date       : 2012.09.03
        /// </summary>
        private void PollingLoop_()
        {
            DbModule.SendRequestMasterInfo reqInfo_mstr = new DbModule.SendRequestMasterInfo();
            DbModule.SendRequestDetailInfo reqInfo_dtl  = new DbModule.SendRequestDetailInfo();
            DbModule.SEND_REQ_SITE         reqInfo_site = new DbModule.SEND_REQ_SITE();
            P_TYPE   destProcessType = P_TYPE.PSC;
            FileInfo fi = null;

            string[] files        = null;
            string[] checkFiles   = null;
            string[] workFiles    = null;
            int      successCount = 0;
            string   destFileName = null;   // Detail 테이블에 기록될 Unique 파일 이름

            try
            {
                /// 에러로 인해 Process -> Finish 처리가 안된 팩스들 Process 폴더 -> Upload 폴더로 이동
                CheckProcessFolder();

                /// Storage 경로 확인
                if (CheckStoragePath() == false)
                {
                    return;
                }

                while (!BtfaxThread.Stop)
                {
                    /// 초기화
                    files        = null;
                    checkFiles   = null;
                    workFiles    = null;
                    successCount = 1;
                    destFileName = null;

                    /// 파일 업로드 여부 확인
                    if (CheckUploadFiles(ref files, ref checkFiles, ref workFiles) == true)
                    {
                        foreach (string f in checkFiles)
                        {
                            /// 한번에 처리할 최대 개수
                            if (successCount++ > Config.FILE_PROCESS_COUNT)
                            {
                                break;
                            }

                            /// 초기 설정
                            fi = new FileInfo(f);
                            reqInfo_mstr.Clear();
                            reqInfo_dtl.Clear();
                            reqInfo_site.clear();

                            try
                            {
                                Thread.Sleep(100);

                                /// 작업할 파일 작업폴더로 이동
                                if (FileMove(fi, FileMoveLocationEnum.Process, ref destFileName) == false)
                                {
                                    continue;
                                }

                                /// 파일 파싱
                                if (ParseTifFile(fi, reqInfo_mstr, reqInfo_dtl) == false)
                                {
                                    continue;
                                }

                                /// 파싱 성공 후 이미지 폴더로 파일 이동 (+ 이름 변경)
                                if (FileMove(fi, FileMoveLocationEnum.Done, ref destFileName) == false)
                                {
                                    continue;
                                }

                                /// DB 에 저장될 파일명 변경
                                if (FileRenameForDB(reqInfo_dtl, destFileName) == false)
                                {
                                    continue;
                                }

                                /// DB Insert
                                if (InsertToDb(reqInfo_mstr, reqInfo_dtl, reqInfo_site) != RESULT.SUCCESS)
                                {
                                    continue;
                                }

                                /// Pass Over
                                if (PassOverSendRequest(destProcessType, reqInfo_mstr, reqInfo_dtl) != RESULT.SUCCESS)
                                {
                                    continue;
                                }
                            }
                            catch (Exception ex)
                            {
                                AppLog.ExceptionLog(ex, string.Format("{0} 쓰레드에서 다음과 같은 오류가 발생하였습니다.", m_ThreadName));
                                break;
                            }
                        }
                    }

                    /// Wait - Storage polling time
                    /// Sleep 시간이 길 경우 Thread.Join() 도 길어져 Sleep 시간을 줄임
                    for (int i = 0; !BtfaxThread.Stop && (i * 100 < Config.SOTRAGE_POLLING_TIME); i++)
                    {
                        Thread.Sleep(100);
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("{0} 쓰레드에서 다음과 같은 오류가 발생하였습니다. 쓰레드를 종료합니다.", m_ThreadName));
                //throw ex;
            }
        }
Exemple #17
0
        protected void RequestHandler(HttpListenerContext p_context)
        {
            int         nPos;
            string      strUrl;
            string      strMsg, strResponseMsg;
            XmlDocument xml;
            HEADER      header;
            RESULT      result;

            // HTTP:REQUEST 로그
            AppLog.Write(LOG_LEVEL.TRC, string.Format("[{0}][REQ][Remote={1:15}][{2:4}][Url={3}]",
                                                      m_nThreadNo,
                                                      p_context.Request.RemoteEndPoint.Address,
                                                      p_context.Request.HttpMethod,
                                                      p_context.Request.Url));

            result = RESULT.SUCCESS;
            header = new HEADER();
            xml    = new XmlDocument();
            strMsg = "";
            try
            {
                // WRH MSG 추출 <- URL
                strUrl = p_context.Request.RawUrl;
                strUrl = strUrl.Replace("%3C", "<");
                strUrl = strUrl.Replace("%3E", ">");
                strUrl = strUrl.Replace("%20", " ");

                nPos   = strUrl.IndexOf("<WRH_MSG>");
                strMsg = strUrl.Substring(nPos);


                // 헤더 파싱
                if (!ParseHeader(strMsg, ref xml, ref header))
                {
                    result = RESULT.F_PARSE_ERROR;
                }
            }
            catch (Exception ex)
            {
                result = RESULT.F_PARSE_ERROR;
            }


            // 요청 처리
            strResponseMsg = "";
            if (result == RESULT.SUCCESS)
            {
                switch (header.Category)
                {
                case "OUTBOUND":
                    switch (header.CommandNo)
                    {
                    case "1":
                        Handle_OUTBOUND_01(xml, strMsg, header, out strResponseMsg);
                        break;

                    default:
                        result = RESULT.F_SYSTEMHEADER_INVALID_COMMAND_NO;
                        break;
                    }
                    break;

                case "INBOUND":
                    switch (header.CommandNo)
                    {
                    case "1":
                        result = Handle_INBOUND_01(xml, strMsg, header, out strResponseMsg);
                        break;

                    default:
                        result = RESULT.F_SYSTEMHEADER_INVALID_COMMAND_NO;
                        break;
                    }
                    break;

                default:
                    result = RESULT.F_SYSTEMHEADER_INVALID_CATEGORY;
                    break;
                }
            }

            // 에러 응답 메세지 생성
            if (result != RESULT.SUCCESS)
            {
                strResponseMsg = ComposeErrorResponse(result);

                // 알람메시지 전송
                AlarmAPI.Instance.SendFaultAlarm((UInt32)result);
            }

            // HTTP:RESPONSE 로그
            string strResponseMsgLog;

            strResponseMsgLog = strResponseMsg.Replace("\r\n", "");
            strResponseMsgLog = strResponseMsgLog.Replace(">  <", "><");
            strResponseMsgLog = strResponseMsgLog.Replace(">    <", "><");
            AppLog.Write(LOG_LEVEL.TRC, string.Format("[{0}][RES][Remote={1:15}][Msg={2}]",
                                                      m_nThreadNo,
                                                      p_context.Request.RemoteEndPoint.Address,
                                                      strResponseMsgLog));

            // 응답 메세지 전송
            try
            {
                p_context.Response.AddHeader("Content-Type", "text/plain");
                p_context.Response.AddHeader("Access-Control-Allow-Origin", "*");
                p_context.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS");
                p_context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                p_context.Response.AddHeader("Access-Control-Max-Age", "86400");
                p_context.Response.AddHeader("Access-Control-Allow-Headers", "X-Requested-With,X-HTTP-Method_override,Content-Type,Accept");

                StreamWriter writer = new StreamWriter(p_context.Response.OutputStream, Encoding.UTF8);
                writer.Write(strResponseMsg);
                writer.Close();
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("[{0}] WEB 요청에 대한 처리 중, 예외가 발생하였습니다.", m_nThreadNo));
                return;
            }
        }
Exemple #18
0
        static void Main(string[] strArgs)
        {
            // 프로세스 아규먼트 처리
            if (strArgs.Length <= 0)
            {
                MessageBox.Show("프로세스 아이디가 입력되지 않았습니다",
                                "실행 오류",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            if (!long.TryParse(strArgs[0], out Config.PROCESS_NO))
            {
                MessageBox.Show("프로세스 아이디가 잘못되었습니다.",
                                "실행 오류",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            //// 환경 파일 로딩 ////
            string iniFile = string.Format("{0}\\..\\Btfax.ini", Application.StartupPath);

            if (!Config.LoadIni(iniFile))
            {
                MessageBox.Show(string.Format("환경파일({0}) 읽기 실패.", iniFile), "실행 오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            CommonMsgBox.IsMsgPopup = false;

            // 윈폼 생성
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Program.s_frmMain = new FrmMain();

            // 초기화
            AppLog.LogDefaultPath = Application.StartupPath + "\\log";
            AppLog.LogPrefix      = string.Format("FAX_{0}_WRH_{1}", Config.SYSTEM_NO, Config.PROCESS_NO);
            //AppLog.DisplayDelegate = s_frmMain.Display_AddLog;
            //AppLog.DisplayIncrementErrorDelegate = s_frmMain.IncrementError;
            //Config.DisplayDelegate = Program.s_frmMain.Display_Config;

            // 프로세스 시작
            Config.APP_VER = string.Format("v{0}", Assembly.GetExecutingAssembly().GetName().Version);
            AppLog.Write(LOG_LEVEL.MSG, string.Format("### WRH {0} 프로세스  시작 ###", Config.APP_VER));
#if DEBUG
            AppLog.Write(LOG_LEVEL.MSG, "### This is DEBUG mode. ###");
#endif

            // DB 접속
            if (!DbModule.Instance.Open(Config.DB_CONNECTION_STRING))
            {
                AppLog.Write(LOG_LEVEL.ERR, "DB 접속에 실패하였습니다");
                return;
            }
            AppLog.Write(LOG_LEVEL.MSG, "DB : 접속 완료");

            // 환경 DB 로딩
            if (!Config.LoadDb())
            {
                AppLog.Write(LOG_LEVEL.ERR, "환경파일 읽기를 실패하였습니다");
                return;
            }
            AppLog.LogLevel = Config.LOG_LEVEL;
            AppLog.Write(LOG_LEVEL.MSG, "실행환경 적용 완료");

            //// 알람API 초기화 ////
            int alarmRet = AlarmAPI.Instance.Init((uint)Config.SYSTEM_NO
                                                  , Config.SYSTEM_GROUP
                                                  , Config.IOA_MODULE_ID
                                                  , Config.IOA_ALARM_PORT
                                                  , Config.IOA_ALARM_BASE_CODE
                                                  , (uint)Config.PROCESS_NO
                                                  , Config.PROCESS_TYPE.ToString()
                                                  , 1
                                                  , AppLog.LogDefaultPath + "\\alarm\\"
                                                  );
            if (alarmRet != 0)
            {
                AppLog.Write(LOG_LEVEL.WRN, "Alarm API 설정을 실패하였습니다");
            }
            else
            {
                AppLog.Write(LOG_LEVEL.MSG, "Alarm API 로드 완료");
            }

            if (!System.IO.Directory.Exists(Config.TIF_MANIPULATE_PATH))
            {
                System.IO.Directory.CreateDirectory(Config.TIF_MANIPULATE_PATH);
            }

            // 쓰레드 객체 생성
            // Making Tiff 쓰레드
            for (int i = 0; i < Config.REQUEST_HANDLER_THREAD_CNT; i++)
            {
                RequestHandlerThread thread = new RequestHandlerThread();
                Program.s_requestHandlerThreads.Add(thread);
            }

            // 윈폼 실행
            try
            {
                Program.StartService();
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                Application.ThreadException += new ThreadExceptionEventHandler(ApplicationThreadException);
                Application.Run(Program.s_frmMain);
                Program.StopService();
            }
            catch (Exception ex)
            {
                Program.StopService();
                AppLog.ExceptionLog(ex, "어플리케이션 예외가 발생하였습니다.");
            }

            // 프로세스 종료 로그 기록
            AppLog.Write(LOG_LEVEL.MSG, "### WRH 프로세스  종료 ###");
        }
Exemple #19
0
        static void Main(string[] strArgs)
        {
            // 프로세스 아규먼트 처리
            if (strArgs.Length <= 0)
            {
                MessageBox.Show("프로세스 아이디가 입력되지 않았습니다",
                                "실행 오류",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            if (!long.TryParse(strArgs[0], out Config.PROCESS_NO))
            {
                MessageBox.Show("프로세스 아이디가 잘못되었습니다.",
                                "실행 오류",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            //// 윈폼 생성 ////
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Program.s_frmMain = new FrmMain();

            //// 환경 파일 로딩 ////
            string iniFile = string.Format("{0}\\..\\Btfax.ini", Application.StartupPath);

            if (!Config.LoadIni(iniFile))
            {
                MessageBox.Show(string.Format("환경파일({0}) 읽기 실패.", iniFile), "실행 오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            CommonMsgBox.IsMsgPopup = false;

            //// 로그 초기화 ////
            AppLog.LogDefaultPath = Application.StartupPath + "\\log";
            AppLog.LogPrefix      = string.Format("FAX_{0}_DCV_{1}", Config.SYSTEM_NO, Config.PROCESS_NO);
            //AppLog.IsDisplay = false;
            //AppLog.DisplayDelegate = Program.s_frmMain.Display_AddLog;
            //Config.DisplayDelegate = Program.s_frmMain.Display_Config;

            //// 프로세스 시작 ////
            Config.APP_VER = string.Format("v{0}", Assembly.GetExecutingAssembly().GetName().Version);
            AppLog.Write(LOG_LEVEL.MSG, string.Format("### DCV {0} 프로세스 시작 ###", Config.APP_VER));

            if (!Directory.Exists(Config.TIFF_CONVERTING_PATH))
            {
                Directory.CreateDirectory(Config.TIFF_CONVERTING_PATH);
            }

#if DEBUG
            AppLog.Write(LOG_LEVEL.MSG, "### This is DEBUG mode. ###");
#endif
            //// DB 접속 ////
            if (!DbModule.Instance.Open(Config.DB_CONNECTION_STRING))
            {
                AppLog.Write(LOG_LEVEL.ERR, "DB 접속에 실패하였습니다");
                return;
            }
            AppLog.Write(LOG_LEVEL.MSG, "DB 접속 완료");

            //// 환경 DB 로딩 ////
            if (!Config.LoadDb())
            {
                AppLog.Write(LOG_LEVEL.ERR, "환경DB 읽기를 실패하였습니다");
                return;
            }
            AppLog.LogLevel = Config.LOG_LEVEL;

            AppLog.Write(LOG_LEVEL.MSG, "실행환경 적용 완료");

            //// 쓰레드 객체 생성 ////
            s_WorkerThread = WorkerThread.Instance;

            //// 윈폼 실행 ////
            try
            {
                //// 쓰레드 시작 ////
                Program.Thread_Start();

                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                Application.ThreadException += new ThreadExceptionEventHandler(ApplicationThreadException);
                Application.Run(Program.s_frmMain);

                //// 쓰레드 종료 ////
                Program.Thread_Stop();
            }
            catch (Exception ex)
            {
                //// 쓰레드 종료 ////
                Program.Thread_Stop();

                AppLog.ExceptionLog(ex, "어플리케이션 예외가 발생하였습니다.");
            }

            //// 프로세스 종료 로그 기록 ////
            AppLog.Write(LOG_LEVEL.MSG, "### DCV 프로세스  종료 ###");
        }
        protected override void ThreadEntry()
        {
            AppLog.Write(LOG_LEVEL.MSG, "### DB폴링 쓰레드 시작 ###");
            Thread.Sleep(Config.INITIAL_SLEEP);
            AppLog.Write(LOG_LEVEL.MSG, "### DB폴링 시작 ###");

            int nPolling = 0;

            while (!BtfaxThread.Stop)
            {
                try
                {
                    Thread.Sleep(Config.DB_POLLING_SLEEP);

                    //if (!ExistsFaxStorage())
                    //{
                    //    AppLog.Write(LOG_LEVEL.ERR, string.Format("팩스스토리지를 찾을수 없습니다. 위치:{0}", Config.STG_HOME_PATH));
                    //    continue;
                    //}

                    if (m_lstPostProcessingReqs.Count > 0)
                    {
                        m_lstPostProcessingReqs.Clear();
                    }

                    /// 처리건 조회
                    RESULT ret = DbModule.Instance.PSI_FetchPostProcessingRequest(Config.PROCESS_TYPE,
                                                                                  Config.SYSTEM_PROCESS_ID,
                                                                                  Config.FETCH_CNT,
                                                                                  ref m_lstPostProcessingReqs
                                                                                  );

                    nPolling++;
                    if (nPolling % 10 == 0)
                    {
                        AppLog.Write(LOG_LEVEL.MSG, "DB Polling Check OK.");
                        if (nPolling == 1000)
                        {
                            nPolling = 0;
                        }
                    }

                    switch (ret)
                    {
                    case RESULT.EMPTY:
                    case RESULT.SUCCESS:
                        break;

                    default:
                        AppLog.Write(LOG_LEVEL.ERR, "DB 폴링 중 오류가 발생하였습니다");
                        continue;
                    }

                    if (m_lstPostProcessingReqs.Count <= 0)
                    {
                        continue;
                    }

                    //// 요철건 처리 ////
                    AppLog.Write(LOG_LEVEL.MSG, string.Format("처리건 개수:{0}", m_lstPostProcessingReqs.Count));
                    foreach (DbModule.RECV_FAX_DATA_PSI req in m_lstPostProcessingReqs)
                    {
                        if (req.SPAM_YN == "Y")
                        {
                            AppLog.Write(LOG_LEVEL.MSG, "스팸팩스함으로 분류되었습니다.");
                            continue;
                        }

                        PostProcessingReq(req);
                    }
                }
                catch (Exception ex)
                {
                    AppLog.ExceptionLog(ex, "DB폴링 쓰레드에서 다음과 같은 오류가 발생하였습니다.");
                }
            }

            AppLog.Write(LOG_LEVEL.ERR, "### DB폴링 종료 ###");
        }
        // 페이지수 동일 SPLIT
        public static bool SplitTif(string p_strPath, string p_strSrcFile, int p_nEachPage, string p_strOutFilePrefix, ref List <DbModule.SPLIT_FILE_INFO> p_lstOutFiles)
        {
            bool   bResult;
            Bitmap srcFile  = null;
            string strPages = "";

            if (p_nEachPage <= 0)
            {
                return(false);
            }

            bResult = true;
            try
            {
                srcFile = new Bitmap(p_strPath + '/' + p_strSrcFile);

                int nPageCnt = srcFile.GetFrameCount(FrameDimension.Page);
                if (nPageCnt <= 0)
                {
                    bResult = false;
                }

                // 추출 페이지 포맷 만들기
                if (bResult)
                {
                    for (int i = 1; i <= nPageCnt; i += p_nEachPage)
                    {
                        if (p_nEachPage == 1)
                        {
                            strPages += string.Format("{0},", i);
                        }
                        else
                        {
                            int nPageBegin = i;
                            int nPageEnd   = i + p_nEachPage - 1;

                            if (nPageEnd <= nPageCnt)
                            {
                                strPages += string.Format("{0}-{1}", i, i + p_nEachPage - 1) + ',';
                            }
                            else
                            {
                                strPages += string.Format("{0}-{1}", i, nPageCnt) + ',';
                            }
                        }
                    }
                    strPages = strPages.Remove(strPages.Length - 1);
                }

                // 추출
                if (bResult)
                {
                    if (!SplitTif(p_strPath, srcFile, strPages, p_strOutFilePrefix, ref p_lstOutFiles))
                    {
                        bResult = false;
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, "TIF파일 분리 시, 예외가 발생하였습니다.");
                bResult = false;
            }

            try
            {
                if (srcFile != null)
                {
                    srcFile.Dispose();
                }
            }
            catch { }

            return(bResult);
        }
Exemple #22
0
        protected RESULT Handle_INBOUND_01(XmlDocument p_xml, string p_strMsg, HEADER p_header, out string p_strResponseMsg)
        {
            XmlElement tagRoot, tagHeader, tagBody, tagResult, tag;
            decimal    faxID          = 0;
            string     strSplitMethod = "";
            string     strSplitDetail = "";
            List <DbModule.SPLIT_FILE_INFO> outFileInfos = new List <DbModule.SPLIT_FILE_INFO>();

            p_strResponseMsg = "";

            //// WRH 메세지 파싱
            try
            {
                tagRoot   = p_xml.SelectSingleNode("WRH_MSG") as XmlElement;
                tagHeader = p_xml.SelectSingleNode("WRH_MSG/HEADER") as XmlElement;
                tagBody   = p_xml.SelectSingleNode("WRH_MSG/BODY") as XmlElement;


                tag   = tagBody.SelectSingleNode("FaxId") as XmlElement;
                faxID = Convert.ToDecimal(tag.InnerText);

                tag            = tagBody.SelectSingleNode("SplitMethod") as XmlElement;
                strSplitMethod = tag.InnerText;

                tag            = tagBody.SelectSingleNode("SplitDetail") as XmlElement;
                strSplitDetail = tag.InnerText;
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("[{0}] WRH 메세지 파싱중 예외가 발생하였습니다.[Request={1}]", m_nThreadNo, p_strMsg));
                return(RESULT.F_PARSE_ERROR_BODY);
            }

            //// 요청 처리
            try
            {
                // 수신 건 조회
                DbModule.RECV_INFO recvInfo;

                if (!DbModule.Instance.GetRecvFaxInfo(faxID, out recvInfo))
                {
                    return(RESULT.F_DB_NOTEXIST_FAX);
                }

                string strSrcPath;         // 이미지 파일 디렉토리 전체 경로
                string strSrcFileFullName; // 확장자 포함 파일 이름
                string strSrcFileName;     // 확장자 제외 파일이름

                strSrcPath         = Config.INBOUND_TIF_FULL_PATH + "\\" + recvInfo.strTifFile.Substring(0, recvInfo.strTifFile.LastIndexOf("\\") + 1);
                strSrcFileFullName = recvInfo.strTifFile.Substring(recvInfo.strTifFile.LastIndexOf("\\") + 1);
                strSrcFileName     = strSrcFileFullName.Substring(0, strSrcFileFullName.LastIndexOf('.'));


                // TIF 원본 파일 다운로드
                AppLog.Write(LOG_LEVEL.MSG, string.Format("[{0}][ACT] 파일 다운로드 시작 {1} => {2}",
                                                          m_nThreadNo,
                                                          strSrcPath + "\\" + strSrcFileFullName,
                                                          Config.TIF_MANIPULATE_PATH + "\\" + strSrcFileFullName));
                File.Copy(strSrcPath + "\\" + strSrcFileFullName,
                          Config.TIF_MANIPULATE_PATH + "\\" + strSrcFileFullName,
                          true);
                AppLog.Write(LOG_LEVEL.MSG, string.Format("[{0}][ACT] 파일 다운로드 완료", m_nThreadNo));


                // TIF 원본 파일 분리
                AppLog.Write(LOG_LEVEL.MSG, string.Format("[{0}][ACT] TIF 페이지 분리 시작. Method={1} Detail={2} File={3}",
                                                          m_nThreadNo, strSplitMethod, strSplitDetail, strSrcFileFullName));
                if (strSplitMethod == "A")  // 페이지 수 동일, 분리
                {
                    if (!TifManipulator.SplitTif(Config.TIF_MANIPULATE_PATH,
                                                 strSrcFileFullName,
                                                 Convert.ToInt32(strSplitDetail),
                                                 strSrcFileName,
                                                 ref outFileInfos))
                    {
                        return(RESULT.F_TIFFPROCESS_FAIL_TO_EXTRACT);
                    }
                }
                else if (strSplitMethod == "I") // 페이지수 다르게, 분리
                {
                    if (!TifManipulator.SplitTif(Config.TIF_MANIPULATE_PATH,
                                                 strSrcFileFullName,
                                                 strSplitDetail,
                                                 strSrcFileName,
                                                 ref outFileInfos))
                    {
                        return(RESULT.F_TIFFPROCESS_FAIL_TO_EXTRACT);
                    }
                }
                else
                {
                    return(RESULT.F_PARSE_ERROR_BODY);
                }
                AppLog.Write(LOG_LEVEL.MSG, string.Format("[{0}][ACT] TIF 페이지 분리 완료", m_nThreadNo));


                // 분리 TIF 업로드
                AppLog.Write(LOG_LEVEL.MSG, string.Format("[{0}][ACT] 파일 업로드 시작", m_nThreadNo));
                foreach (DbModule.SPLIT_FILE_INFO fileInfo in outFileInfos)
                {
                    File.Copy(Config.TIF_MANIPULATE_PATH + "\\" + fileInfo.p_strFile,
                              strSrcPath + "\\" + fileInfo.p_strFile,
                              true);
                    File.Delete(Config.TIF_MANIPULATE_PATH + "\\" + fileInfo.p_strFile);
                }
                AppLog.Write(LOG_LEVEL.MSG, string.Format("[{0}][ACT] 파일 업로드 완료", m_nThreadNo));
                File.Delete(Config.TIF_MANIPULATE_PATH + "\\" + strSrcFileFullName);


                // 기존 SPLIT 정보 DB 업데이트
                AppLog.Write(LOG_LEVEL.MSG, string.Format("[{0}][ACT] DB 정보 업데이트 시작", m_nThreadNo));
                if (!DbModule.Instance.DeleteSplitInfos(recvInfo.faxID))
                {
                    return(RESULT.F_DB_ERROR);
                }

                // SPLIT 정보 DB 업데이트

                foreach (DbModule.SPLIT_FILE_INFO fileInfo in outFileInfos)
                {
                    if (!DbModule.Instance.InsertSplitInfo(recvInfo.faxID, fileInfo))
                    {
                        return(RESULT.F_DB_UPDATE_ERROR);
                    }
                }
                if (!DbModule.Instance.UpdateSplitYN(recvInfo.faxID, 'Y'))
                {
                    return(RESULT.F_DB_UPDATE_ERROR);
                }
                AppLog.Write(LOG_LEVEL.MSG, string.Format("[{0}][ACT] DB 정보 업데이트 완료", m_nThreadNo));
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("[{0}] WRH 메세지 요청 처리 중, 예외가 발생하였습니다.[Request={1}]", m_nThreadNo, p_strMsg));
                return(RESULT.F_HANDLE_REQUEST);
            }

            //// 성공 응답 메세지 생성
            try
            {
                tagResult = p_xml.CreateElement("RESULT");
                tagRoot.AppendChild(tagResult);

                tag = p_xml.CreateElement("Result"); tag.InnerText = "S";
                tagResult.AppendChild(tag);

                tag = p_xml.CreateElement("Reason"); tag.InnerText = "H001";
                tagResult.AppendChild(tag);

                tag = p_xml.CreateElement("ReasonName"); tag.InnerText = "SUCCESS";
                tagResult.AppendChild(tag);

                tag           = tagHeader.SelectSingleNode("Command") as XmlElement;
                tag.InnerText = '/' + p_header.Command;

                tag = p_xml.CreateElement("FileCount"); tag.InnerText = outFileInfos.Count().ToString();
                tagBody.AppendChild(tag);

                //  응답 문자열로 변환
                MemoryStream stream = new MemoryStream();
                p_xml.Save(stream);

                stream.Seek(0, SeekOrigin.Begin);
                StreamReader reader = new StreamReader(stream);
                p_strResponseMsg = reader.ReadToEnd();

                reader.Close();
                stream.Close();
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("[{0}] WRH 응답 메세지 생성 중, 예외가 발생하였습니다.[Request={1}]", m_nThreadNo, p_strMsg));
                return(RESULT.F_COMPOSE_ERROR);
            }

            return(RESULT.SUCCESS);
        }
Exemple #23
0
        static void Main(string[] strArgs)
        {
            // 프로세스 아규먼트 처리
            if (strArgs.Length <= 0)
            {
                MessageBox.Show("프로세스 아이디가 입력되지 않았습니다",
                                "실행 오류",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            if (!long.TryParse(strArgs[0], out Config.PROCESS_NO))
            {
                MessageBox.Show("프로세스 아이디가 잘못되었습니다.",
                                "실행 오류",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            //// 환경 파일 로딩 ////
            string iniFile = string.Format("{0}\\..\\Btfax.ini", Application.StartupPath);

            if (!Config.LoadIni(iniFile))
            {
                MessageBox.Show(string.Format("환경파일({0}) 읽기 실패.", iniFile), "실행 오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            CommonMsgBox.IsMsgPopup = false;

            // 윈폼 생성
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Program.s_frmMain = new FrmMain();

            // 초기화
            AppLog.LogDefaultPath = Application.StartupPath + "\\log";
            AppLog.LogPrefix      = string.Format("FAX_{0}_FAS_{1}", Config.SYSTEM_NO, Config.PROCESS_NO);

            // 프로세스 시작
            Config.APP_VER = string.Format("v{0}", Assembly.GetExecutingAssembly().GetName().Version);
            AppLog.Write(LOG_LEVEL.MSG, string.Format("### FAS {0} 프로세스  시작 ###", Config.APP_VER));
#if DEBUG
            AppLog.Write(LOG_LEVEL.MSG, "### This is Debug mode. ###");
#endif
            // DB 접속
            if (!DbModule.Instance.Open(Config.DB_CONNECTION_STRING))
            {
                AppLog.Write(LOG_LEVEL.ERR, "DB 접속에 실패하였습니다");
                return;
            }
            AppLog.Write(LOG_LEVEL.MSG, "DB : 접속 완료");

            // 환경 DB 로딩
            if (!Config.LoadDb())
            {
                AppLog.Write(LOG_LEVEL.ERR, "환경파일 읽기를 실패하였습니다");
                return;
            }
            AppLog.LogLevel = Config.LOG_LEVEL;
            AppLog.Write(LOG_LEVEL.MSG, "실행환경 적용 완료");

            // 쓰레드 객체 생성
            Program.s_TcpSocketListener = TcpSocketThread.Instance;
            Program.s_UdpSocketListener = UdpSocketThread.Instance;

            // 윈폼 실행
            try
            {
                Program.Thread_Start();
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                Application.ThreadException += new ThreadExceptionEventHandler(ApplicationThreadException);
                Application.Run(Program.s_frmMain);
                Program.Thread_Stop();
            }
            catch (Exception ex)
            {
                Program.Thread_Stop();
                AppLog.ExceptionLog(ex, "어플리케이션 예외가 발생하였습니다.");
            }

            // 프로세스 종료 로그 기록
            AppLog.Write(LOG_LEVEL.MSG, "### FAS 프로세스  종료 ###");
        }
Exemple #24
0
 /// <summary>
 /// 쓰레드 예외
 /// </summary>
 private static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
 {
     AppLog.ExceptionLog(e.Exception, string.Format("어플리케이션 쓰레드 에러가 발생했습니다."));
     //throw e.Exception;
 }
Exemple #25
0
        static void Main(string[] strArgs)
        {
            // 프로세스 아규먼트 처리
            if (strArgs.Length <= 0)
            {
                MessageBox.Show("프로세스 아이디가 입력되지 않았습니다",
                                "실행 오류",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            if (!long.TryParse(strArgs[0], out Config.PROCESS_NO))
            {
                MessageBox.Show("프로세스 아이디가 잘못되었습니다.",
                                "실행 오류",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            //// 환경 파일 로딩 ////
            string iniFile = string.Format("{0}\\..\\Btfax.ini", Application.StartupPath);

            if (!Config.LoadIni(iniFile))
            {
                MessageBox.Show(string.Format("환경파일({0}) 읽기 실패.", iniFile), "실행 오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            CommonMsgBox.IsMsgPopup = false;

            //// 윈폼 생성 ////
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Program.s_frmMain = new FrmMain();

            //// 초기화 ////
            AppLog.LogDefaultPath = Application.StartupPath + "\\log";
            AppLog.LogPrefix      = string.Format("FAX_{0}_PSI_{1}", Config.SYSTEM_NO, Config.PROCESS_NO);
            //AppLog.IsDisplay = false;
            //AppLog.DisplayDelegate = Program.s_frmMain.Display_AddLog;
            //Config.DisplayDelegate = Program.s_frmMain.Display_Config;

            //// 프로세스 시작 ////
            Config.APP_VER = string.Format("v{0}", Assembly.GetExecutingAssembly().GetName().Version);
            AppLog.Write(LOG_LEVEL.MSG, string.Format("### PSI {0} 프로세스 시작 ###", Config.APP_VER));
#if DEBUG
            AppLog.Write(LOG_LEVEL.MSG, "### This is DEBUG mode. ###");
#endif

            //// DB 접속 ////
            if (!DbModule.Instance.Open(Config.DB_CONNECTION_STRING))
            {
                AppLog.Write(LOG_LEVEL.ERR, "DB 접속에 실패하였습니다");
                return;
            }
            AppLog.Write(LOG_LEVEL.MSG, "DB : 접속 완료");

            //// 환경 DB 로딩 ////
            if (!Config.LoadDb())
            {
                AppLog.Write(LOG_LEVEL.ERR, "환경DB 읽기를 실패하였습니다");
                return;
            }
            AppLog.LogLevel = Config.LOG_LEVEL;
            AppLog.Write(LOG_LEVEL.MSG, "실행환경 적용 완료");

            ////// 알람API 초기화 ////
            //int alarmRet = AlarmAPI.Instance.Init((uint)Config.SYSTEM_NO
            //                                    , Config.SYSTEM_GROUP
            //                                    , Config.IOA_MODULE_ID
            //                                    , Config.IOA_ALARM_PORT
            //                                    , Config.IOA_ALARM_BASE_CODE
            //                                    , (uint)Config.PROCESS_NO
            //                                    , Config.PROCESS_TYPE.ToString()
            //                                    , 1
            //                                    , AppLog.LogDefaultPath + "\\alarm\\"
            //                                    );
            //if (alarmRet != 0)
            //    AppLog.Write(LOG_LEVEL.WRN, "Alarm API 설정을 실패하였습니다");
            //else
            //    AppLog.Write(LOG_LEVEL.MSG, "Alarm API 로드 완료");

            //// 쓰레드 객체 생성 ////
            s_DbPollingThread = DbPollingThread.Instance;

            /// UDP 소켓 초기화
            UdpSingle.Instance.InitUdpSocket(false);

            //// 윈폼 실행 ////
            try
            {
                //// 쓰레드 시작 ////
                Program.Thread_Start();

                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                Application.ThreadException += new ThreadExceptionEventHandler(ApplicationThreadException);
                Application.Run(Program.s_frmMain);

                //// 쓰레드 종료 ////
                Program.Thread_Start();
            }
            catch (Exception ex)
            {
                //// 쓰레드 종료 ////
                Program.Thread_Start();

                AppLog.ExceptionLog(ex, "어플리케이션 예외가 발생하였습니다.");
            }

            //// 프로세스 종료 로그 기록 ////
            AppLog.Write(LOG_LEVEL.MSG, "### PSI 프로세스  종료 ###");
        }
Exemple #26
0
        protected RESULT Handle_OUTBOUND_01(XmlDocument p_xml, string p_strMsg, HEADER p_header, out string p_strResponseMsg)
        {
            XmlElement tagRoot, tagHeader, tagBody, tagResult, tag;
            decimal    faxID      = 0;
            char       chWaitType = ' ';
            bool       bWait      = false;

            p_strResponseMsg = "";

            //// 요청 메세지 파싱
            try
            {
                tagRoot   = p_xml.SelectSingleNode("WRH_MSG") as XmlElement;
                tagHeader = p_xml.SelectSingleNode("WRH_MSG/HEADER") as XmlElement;
                tagBody   = p_xml.SelectSingleNode("WRH_MSG/BODY") as XmlElement;


                tag   = tagBody.SelectSingleNode("FaxId") as XmlElement;
                faxID = Convert.ToDecimal(tag.InnerText);

                tag        = tagBody.SelectSingleNode("WaitType") as XmlElement;
                chWaitType = Convert.ToChar(tag.InnerText);
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("[{0}] WRH 메세지 파싱 중, 예외가 발생하였습니다.[Request={1}]", m_nThreadNo, p_strMsg));
                return(RESULT.F_PARSE_ERROR_BODY);
            }

            //// 요청 처리
            try
            {
                // 대기 건 조회
                if (WaitListMgr.Instance.IsWaitList(faxID, chWaitType))
                {
                    bWait = true;
                }
                else
                {
                    bWait = false;
                }
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("[{0}] WRH 메세지 요청 처리 중, 예외가 발생하였습니다.[Request={1}]", m_nThreadNo, p_strMsg));
                return(RESULT.F_PARSE_ERROR_BODY);
            }

            //// 응답 메세지 생성
            try
            {
                tagResult = p_xml.CreateElement("RESULT");
                tagRoot.AppendChild(tagResult);

                tag = p_xml.CreateElement("Result"); tag.InnerText = "S";
                tagResult.AppendChild(tag);

                tag = p_xml.CreateElement("Reason"); tag.InnerText = "H001";
                tagResult.AppendChild(tag);

                tag = p_xml.CreateElement("ReasonName"); tag.InnerText = "SUCCESS";
                tagResult.AppendChild(tag);

                tag           = tagHeader.SelectSingleNode("Command") as XmlElement;
                tag.InnerText = '/' + p_header.Command;

                tag = p_xml.CreateElement("WaitYN");
                if (bWait)
                {
                    tag.InnerText = "Y";
                }
                else
                {
                    tag.InnerText = "N";
                }
                tagBody.AppendChild(tag);


                //  응답 문자열로 변환
                MemoryStream stream = new MemoryStream();
                p_xml.Save(stream);

                stream.Seek(0, SeekOrigin.Begin);
                StreamReader reader = new StreamReader(stream);
                p_strResponseMsg = reader.ReadToEnd();

                reader.Close();
                stream.Close();
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("[{0}] WRH 응답 메세지 생성 중, 예외가 발생하였습니다.[Request={1}]", m_nThreadNo, p_strMsg));
                return(RESULT.F_COMPOSE_ERROR);
            }

            return(RESULT.SUCCESS);
        }
        private bool ParseTifFileWithInfoFile(FileInfo fi, DbModule.SendRequestMasterInfo p_reqInfo_mstr, DbModule.SendRequestDetailInfo p_reqInfo_dtl)
        {
            string strSID            = "";
            string strFacsimileFaxNo = "";
            string strDestFaxNo      = "";
            string strTitle          = "";
            string strReqUserName    = "";
            string content           = "";

            string onlyFileName = fi.Name.Substring(0, fi.Name.LastIndexOf(fi.Extension));
            string datFile      = string.Format("{0}{1}", m_ProcessPath, fi.Name);

            /// 포맷 파일 읽기
            try
            {
                content = File.ReadAllText(datFile, Encoding.Default);
            }
            catch (Exception ex)
            {
                /// 에러 파일 -> Exception 폴더로 이동
                FileMoveToException(fi.DirectoryName, fi.Name);

                AppLog.ExceptionLog(ex, string.Format("{0}을 읽는 중 오류가 발생하였습니다.", fi.Name));
                throw ex;
            }

            /// 포맷 파일 분석
            Regex           r       = new Regex(@"(?<key>[\w]+)[%s]*=[%s]*(?<value>[\w\d]+)");
            MatchCollection matches = r.Matches(content);

            string key   = "";
            string value = "";

            foreach (Match m in matches)
            {
                key   = m.Groups["key"].Value;
                value = m.Groups["value"].Value;

                if (key == "DEVICE_ID")
                {
                    strSID = value;
                }
                else if (key == "FACSIMILE_FAXNO")
                {
                    strFacsimileFaxNo = value;
                }
                else if (key == "DEST_FAXNO")
                {
                    strDestFaxNo = value;
                }
                else if (key == "TITLE")
                {
                    strTitle = value;
                }
                else if (key == "REQ_USER_NAME")
                {
                    strReqUserName = value;
                }
            }

            /// 분석된 항목 유효성 검사
            /// 최소 보낼 팩스 번호는 있어야 함.
            if (string.IsNullOrEmpty(strDestFaxNo) == true)
            {
                /// 에러 파일 -> Exception 폴더로 이동
                FileMoveToException(fi.DirectoryName, fi.Name);

                return(false);
            }

            /// 분석된 항목 설정
            p_reqInfo_mstr.DataSetting(strSID, strFacsimileFaxNo, strReqUserName, strTitle);
            //p_reqInfo_dtl.DataSetting(strDestFaxNo, strTitle, string.Format("{0}{1}.{2}", m_RelativePath, onlyFileName, Config.FILE_IMAGE_FILE_EXT));
            p_reqInfo_dtl.DataSetting(strDestFaxNo, strTitle, m_RelativePath);

            return(true);
        }
        private bool FileMove(FileInfo fi, FileMoveLocationEnum location, ref string destFilename)
        {
            int resultCount = 0;

            /// 확인용, 작업용 확장자
            string[] extensions = new string[] { Config.FILE_CHECK_EXT, Config.FILE_WORK_EXT }.Distinct().ToArray();

            string onlyFileName = fi.Name.Substring(0, fi.Name.LastIndexOf(fi.Extension));
            string onlyFileNameAndExt_forSource = "";
            string onlyFileNameAndExt_forDest   = "";
            string sourcePath = "";
            string destPath   = "";
            string sourceFile = "";
            string destFile   = "";
            string appendFilenameForUnique = "";

            if (location == FileMoveLocationEnum.Process)
            {
                sourcePath = m_UploadPath;
                destPath   = m_ProcessPath;
            }
            else if (location == FileMoveLocationEnum.Done)
            {
                //// TIF 가 저장된 오늘일자 경로
                string strTifFullPath = string.Format(@"{0}\{1}", Config.FINISHED_TIF_PATH, m_RelativePath);

                //// 최종 TIFF 일자별 디렉토리 생성 ////
                if (!Directory.Exists(strTifFullPath))
                {
                    Directory.CreateDirectory(strTifFullPath);
                }

                sourcePath = m_ProcessPath;
                destPath   = strTifFullPath;

                appendFilenameForUnique = DateTime.Now.ToString("_yyyyMMddHHmmss.ffffff");
            }
            else if (location == FileMoveLocationEnum.Exception)
            {
                sourcePath = m_UploadPath;
                destPath   = m_ProcessPath;
            }


            try
            {
                foreach (string ext in extensions)
                {
                    onlyFileNameAndExt_forSource = string.Format("{0}.{1}", onlyFileName, ext);
                    sourceFile = string.Format("{0}{1}", sourcePath, onlyFileNameAndExt_forSource);

                    /// FInish 폴더로 이동시에는 unique 하기 위해 파일 이름을 변경
                    onlyFileNameAndExt_forDest = string.Format("{0}{1}.{2}", onlyFileName, appendFilenameForUnique, ext);
                    destFile = string.Format("{0}{1}", destPath, onlyFileNameAndExt_forDest);

                    /// DB 이름을 변경할 변수
                    if (ext == Config.FILE_IMAGE_FILE_EXT)
                    {
                        destFilename = onlyFileNameAndExt_forDest;
                    }

                    /// 파일 이동
                    File.Move(sourceFile, destFile);

                    resultCount++;
                }
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, "파일 이동중 오류가 발생하였습니다.");

                /// Process -> Finish 일때만 Exception 으로 진행
                if (location == FileMoveLocationEnum.Done)
                {
                    FileMoveToException(m_ProcessPath, onlyFileNameAndExt_forSource);
                }
                //throw ex;
            }

            if (Config.FILE_CHECK_TYPE == FILE_CHECK_TYPE_Enum.F2)
            {
                return(resultCount > 1 ? true : false);
            }
            else
            {
                return(resultCount > 0 ? true : false);
            }
            //return Config.FILE_CHECK_TYPE == FILE_CHECK_TYPE_Enum.F1 && resultCount > 0 ? true : false;
        }
Exemple #29
0
        static void Main(string[] strArgs)
        {
            // 프로세스 아규먼트 처리
            if (strArgs.Length <= 0)
            {
                MessageBox.Show("PSO실행시, 프로세스 일련번호가 입력되지 않았습니다",
                                "PSO 실행 오류",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }
            if (!FnString.IsNumber(strArgs[0]))
            {
                MessageBox.Show(string.Format("PSO 실행시,  프로세스 일련번호 ({0}) 가 숫자로 입력되지 않았습니다", strArgs[0]),
                                "PSO 실행 오류",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }
            Config.PROCESS_NO = Convert.ToInt32(strArgs[0]);

            //// 환경 파일 로딩 ////
            string iniFile = string.Format("{0}\\..\\Btfax.ini", Application.StartupPath);

            if (!Config.LoadIni(iniFile))
            {
                MessageBox.Show(string.Format("환경파일({0}) 읽기 실패.", iniFile), "실행 오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //// 윈폼 생성 ////
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Program.s_frmMain = new FrmMain();

            //// 초기화 ////
            AppLog.LogDefaultPath = Application.StartupPath + "\\log\\";
            AppLog.LogPrefix      = string.Format("FAX_{0}_PSO_{1}", Config.SYSTEM_NO, Config.PROCESS_NO);
            //AppLog.DisplayDelegate = Program.s_frmMain.Display_AddLog;
            //Config.DisplayDelegate = Program.s_frmMain.Display_Config;
            CommonMsgBox.IsMsgPopup = false;

            //// 프로세스 시작 ////
            Config.APP_VER = string.Format("v{0}", Assembly.GetExecutingAssembly().GetName().Version);
            AppLog.Write(LOG_LEVEL.MSG, string.Format("### PSO {0} 프로세스 시작 ###", Config.APP_VER));

            //// DB 접속 ////
            if (!DbModule.Instance.Open(Config.DB_CONNECTION_STRING))
            {
                AppLog.Write(LOG_LEVEL.ERR, "DB 접속에 실패하였습니다");
                return;
            }
            AppLog.Write(LOG_LEVEL.MSG, "DB 접속 완료");

            //// 환경 DB 로딩 ////
            if (!Config.LoadDb())
            {
                AppLog.Write(LOG_LEVEL.ERR, "환경파일 읽기를 실패하였습니다");
                return;
            }
            AppLog.LogLevel = Config.LOG_LEVEL;
            AppLog.Write(LOG_LEVEL.MSG, "실행환경 적용 완료");

            //// 쓰레드 객체 생성 ////
            s_WorkerThread = WorkerThread.Instance;

            //// UDP 소켓 초기화
            UdpSingle.Instance.InitUdpSocket(false);

            //// 윈폼 실행 ////
            try
            {
                //// 쓰레드 시작 ////
                Program.Thread_Start();
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                Application.ThreadException += new ThreadExceptionEventHandler(ApplicationThreadException);

                //// 쓰레드 종료 ////
                Program.Thread_Start();
                Application.Run(Program.s_frmMain);
            }
            catch (Exception ex)
            {
                //// 쓰레드 종료 ////
                Program.Thread_Start();
                AppLog.ExceptionLog(ex, "어플리케이션 예외가 발생하였습니다.");
            }

            //// 프로세스 종료 로그 기록 ////
            AppLog.Write(LOG_LEVEL.MSG, "### PSO 프로세스  종료 ###");
        }
        /// <summary>
        /// Name       : PollingLoop_
        /// Parameters : Empty
        /// Content    : 폴링 루프
        /// Return     : Empty
        /// Writer     : 장동훈
        /// Date       : 2012.09.03
        /// </summary>
        private void PollingLoop_()
        {
            POP3_Client mail = new POP3_Client();

            DbModule.SendRequestMasterInfo     reqInfo_mstr     = null;
            DbModule.SendRequestDetailInfo     reqInfo_dtl      = null;
            DbModule.SEND_REQ_SITE             reqInfo_site     = null;
            List <DbModule.SendRequestDocInfo> reqInfo_doc_List = null;
            P_TYPE destProcessType   = P_TYPE.PSC;
            int    retryConnectCount = 0;   // POP3 접속 실패시 3회 재시도
            int    retryLoginCount   = 0;   // POP3 로그인 실패시 3회 재시도

            /// 마지막 실행시간 (Sleep 실행의 기준시간)
            /// 첫 Sleep 실행시 바로 실행 되도록 시간 수정
            DateTime lastExecuteTime = DateTime.Now.AddMilliseconds(Config.EMAIL_POLLING_TIME * -1);

            try
            {
                while (!BtfaxThread.Stop)
                {
                    if (DateTime.Now.Subtract(lastExecuteTime).TotalMilliseconds < Config.EMAIL_POLLING_TIME)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }
                    lastExecuteTime = DateTime.Now;

                    try
                    {
                        if (mail.IsConnected == false &&
                            !mail.Connect(Config.EMAIL_POP_SERVER, Config.EMAIL_POP3_SERVER_PORT))
                        {
                            if (retryConnectCount++ < 3)
                            {
                                AppLog.Write(LOG_LEVEL.ERR, string.Format("IP: {0}, PORT: {1} 로 접속중 오류가 발생하였습니다. ({2} 회 접속 시도)", Config.EMAIL_POP_SERVER, Config.EMAIL_POP3_SERVER_PORT, retryConnectCount));

                                /// 0.5 초 대기
                                for (int i = 0; i < 5; i++)
                                {
                                    Thread.Sleep(100);
                                }

                                mail = new POP3_Client();
                                continue;
                            }
                            else
                            {
                                AppLog.Write(LOG_LEVEL.ERR, "해당 서버로 접속 연결이 되지 않습니다.");
                                throw new Exception("접속 에러");
                            }
                        }
                        if (mail.IsLogin == false &&
                            !mail.Login(Config.EMAIL_ID, Config.EMAIL_PW))
                        {
                            if (retryLoginCount++ < 3)
                            {
                                AppLog.Write(LOG_LEVEL.ERR, string.Format("ID: {0}, PASSWORD: {1} 로 로그인중 오류가 발생하였습니다. ({2} 회 로그인 시도)", Config.EMAIL_ID, string.Empty.PadRight(Config.EMAIL_PW.Length, '*'), retryLoginCount));

                                /// 0.5 초 대기
                                for (int i = 0; i < 5; i++)
                                {
                                    Thread.Sleep(100);
                                }

                                continue;
                            }
                            else
                            {
                                AppLog.Write(LOG_LEVEL.ERR, "해당 서버로 로그인이 되지 않습니다.");
                                throw new Exception("로그인 에러");
                            }
                        }

                        /// 초기화
                        retryConnectCount = 0;
                        retryLoginCount   = 0;

                        int messageCount = mail.GetMailCount();
                        for (int i = 1; i <= messageCount; i++)
                        {
                            POP3_Parsing parseMail = mail.GetMessage(i);

                            if (parseMail.IsParseSuccess == false)
                            {
                                continue;
                            }

                            if (ParseEmailDocument(parseMail,
                                                   ref reqInfo_mstr,
                                                   ref reqInfo_dtl,
                                                   ref reqInfo_site,
                                                   ref reqInfo_doc_List,
                                                   ref destProcessType) != RESULT.SUCCESS)
                            {
                                continue;
                            }

                            /// Master, Detail DB Insert
                            if (InsertToDb(reqInfo_mstr, reqInfo_dtl, reqInfo_site) != RESULT.SUCCESS)
                            {
                                continue;
                            }

                            /// Doc DB Insert
                            if (InsertToDbDoc(reqInfo_mstr.OUT_FAX_ID, reqInfo_doc_List) != RESULT.SUCCESS)
                            {
                                continue;
                            }

                            // FAXBOX Insert - 20130124
                            if (InsertToDbFaxbox(reqInfo_mstr) != RESULT.SUCCESS)
                            {
                                continue;
                            }

                            /// Pass Over
                            if (PassOverSendRequest(destProcessType, reqInfo_mstr, reqInfo_dtl) != RESULT.SUCCESS)
                            {
                                continue;
                            }

                            break;
                        }

                        /// 메일함 Update
                        mail.Disconnect();

                        lastExecuteTime = DateTime.Now;
                    }
                    catch (Exception ex)
                    {
                        lastExecuteTime = DateTime.Now;

                        AppLog.ExceptionLog(ex, string.Format("{0} 쓰레드에서 다음과 같은 오류가 발생하였습니다.-1", m_ThreadName));
                        if (mail.IsConnected == true)
                        {
                            mail.ResetDeleteMessage();
                        }
                        AppLog.ExceptionLog(ex, string.Format("{0} 쓰레드에서 다음과 같은 오류가 발생하였습니다.-2", m_ThreadName));
                        //throw ex;
                    }
                }   // while
            }
            catch (Exception ex)
            {
                AppLog.ExceptionLog(ex, string.Format("{0} 쓰레드에서 다음과 같은 오류가 발생하였습니다. 쓰레드를 종료합니다.-1", m_ThreadName));
                if (mail.IsConnected == true)
                {
                    mail.ResetDeleteMessage();
                }
                AppLog.ExceptionLog(ex, string.Format("{0} 쓰레드에서 다음과 같은 오류가 발생하였습니다. 쓰레드를 종료합니다.-2", m_ThreadName));
                throw ex;
            }
        }