using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using System.Net.Mail;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Microsoft.VisualBasic.FileIO;
using System.Data;
using System.ServiceProcess;
using System.Security.Principal;
using System.Threading;


namespace CSV変換ツール
{
    class C02業務共通処理
    {
        ////////////////////////////////////////////////////////////////////////
        // メンバ変数
        ////////////////////////////////////////////////////////////////////////
        #region メンバ変数

        int mProcessID;
        TraceSource mTraceSource;

        //文字列判定処理にて使用する正規表現一覧
        //※enm正規表現と対になる
        public string[] m正規表現配列 = {
            "",
            "^[ -~｡-ﾟ]*$",  /*半角文字*/
            "^[0-9]+$",     /*半角数字*/
            "^[あ-を０-９　]+$",   /*全角平仮名*/
            "^[ァ-ー０-９　]+$",   /*全角カタカナ*/
            @"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,6})+$"   /*メールアドレス*/
            //@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,6})+$"   /*メールアドレス*/
        };

        #endregion

        ////////////////////////////////////////////////////////////////////////
        // 共通メソッド 
        ////////////////////////////////////////////////////////////////////////
        #region 公開 共通メソッド

        //コンストラクタ
        public C02業務共通処理()
        {
            mProcessID = Process.GetCurrentProcess().Id;
            mTraceSource = new TraceSource(System.Windows.Forms.Application.ProductName);
        }

        public bool Chk多重起動()
        {
            if (System.Diagnostics.Process.GetProcessesByName(
                System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length > 1)
            {
                MessageBox.Show(Properties.Resources.MSG_INF_002, "起動エラー", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 正規表現と一致する対象が入力文字列内で見つかったかどうかを示します
        /// </summary>
        public bool IsMatch(string value, enm正規表現 正規表現idx)
        {
            return (Regex.IsMatch(value, m正規表現配列[(int)正規表現idx]));
        }

        /// <summary>
        /// エラーログ出力
        /// </summary>
        /// <param name="pClass">出力元のクラスを指定する</param>
        /// <param name="pCurrentMethod">出力元のメソッド名を指定する</param>
        /// <param name="ex">発生した例外を設定する</param>
        public void ErrorLog(string strクラス名, string strメソッド名, Exception ex)
        {
            DateTime now;

            now = DateTime.Now;

            mTraceSource.TraceEvent(TraceEventType.Error, mProcessID, now.ToString("yyyy/MM/dd HH:mm:ss")
                + " : " + strクラス名 + " : " + strメソッド名);

            if (ex != null)
            {
                mTraceSource.TraceEvent(TraceEventType.Error, mProcessID, now.ToString("yyyy/MM/dd HH:mm:ss")
                    + " : " + ex.Message);
                mTraceSource.TraceEvent(TraceEventType.Error, mProcessID, now.ToString("yyyy/MM/dd HH:mm:ss")
                    + " : " + ex.StackTrace);
            }
            mTraceSource.Flush();

            Program.業務共通処理.ErrMail(strクラス名, strメソッド名, ex);

            MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, "システムエラー", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }

        public void GetException(Exception ex, ref string strBody)
        {
            strBody += "【Exception】\r\n";
            strBody += "ex.Data\r\n";
            strBody += ex.Data + "\r\n\r\n";
            strBody += "ex.HelpLink\r\n";
            strBody += ex.HelpLink + "\r\n\r\n";
            strBody += "ex.Message\r\n";
            strBody += ex.Message + "\r\n\r\n";
            strBody += "ex.Source\r\n";
            strBody += ex.Source + "\r\n\r\n";
            strBody += "ex.StackTrace\r\n";
            strBody += ex.StackTrace + "\r\n\r\n";
            strBody += "ex.TargetSite\r\n";
            strBody += ex.TargetSite + "\r\n\r\n";

        }

        public void GetAssembly(ref string strBody)
        {
            strBody += "\r\n【Assembly】\r\n";
            strBody += "CurrentDirectory：" + Environment.CurrentDirectory + "\r\n";
            strBody += "HasShutdownStarted：" + Environment.HasShutdownStarted + "\r\n";
            strBody += "NewLine：" + Environment.NewLine.ToString() + "\r\n";
            strBody += "OSVersion：" + Environment.OSVersion + "\r\n";
            strBody += "ProcessorCount：" + Environment.ProcessorCount + "\r\n";
            strBody += "StackTrace：" + "\r\n" + Environment.StackTrace + "\r\n";
            strBody += "SystemDirectory：" + Environment.SystemDirectory + "\r\n";
            strBody += "UserInteractive：" + Environment.UserInteractive + "\r\n";
            strBody += "Version：" + Environment.Version + "\r\n";

            strBody += "CommonAppDataPath：" + Application.CommonAppDataPath + "\r\n";
            strBody += "CompanyName：" + Application.CompanyName + "\r\n";
            strBody += "CurrentCulture：" + Application.CurrentCulture + "\r\n";
            strBody += "CurrentInputLanguage.LayoutName：" + Application.CurrentInputLanguage.LayoutName + "\r\n";
            strBody += "ExecutablePath：" + Application.ExecutablePath + "\r\n";
            strBody += "LocalUserAppDataPath：" + Application.LocalUserAppDataPath + "\r\n";
            strBody += "MessageLoop：" + Application.MessageLoop + "\r\n";
            strBody += "OpenForms.Count：" + Application.OpenForms.Count + "\r\n";
            strBody += "ProductName：" + Application.ProductName + "\r\n";
            strBody += "ProductVersion：" + Application.ProductVersion + "\r\n";
            strBody += "RenderWithVisualStyles：" + Application.RenderWithVisualStyles + "\r\n";
            strBody += "SafeTopLevelCaptionFormat：" + Application.SafeTopLevelCaptionFormat + "\r\n";
            strBody += "StartupPath：" + Application.StartupPath + "\r\n";
            strBody += "UserAppDataPath：" + Application.UserAppDataPath + "\r\n";
        }

        public void GetUser(ref string strBody)
        {
            strBody += "\r\n【User】\r\n";
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            WindowsPrincipal princ = (WindowsPrincipal)Thread.CurrentPrincipal;
            strBody += "ユーザー名：" + princ.Identity.Name + "\r\n";
            strBody += "Administrators権限の有無：" + princ.IsInRole(WindowsBuiltInRole.User) + "\r\n";
            strBody += "Users権限の有無：" + princ.IsInRole(WindowsBuiltInRole.User) + "\r\n";

        }

        public bool ChkSQLServer(ref string strBody)
        {
            try
            {
                strBody += "\r\n【SQL Server】\r\n";
                ServiceController controller = new ServiceController();
                controller.MachineName = ".";
#if RELEASE
                controller.ServiceName = "MSSQL$SQLEXPRESS";
#else
                controller.ServiceName = "MSSQLSERVER";
#endif
                strBody += "Status：" + controller.Status.ToString() + "\r\n";

                if (controller.Status.ToString() == "Running")
                {
                    SqlConnection scnMASTER = new SqlConnection(Properties.Settings.Default.MASTER);
                    scnMASTER.Open();

                    String strSQL = " SELECT @@VERSION ";
                    SqlCommand cmd = new SqlCommand(strSQL, scnMASTER);
                    SqlDataReader rdr = cmd.ExecuteReader();
                    rdr.Read();
                    if (rdr[0] != DBNull.Value)
                        strBody += "VERSION：" + rdr[0].ToString() + "\r\n";
                    else
                        strBody += "VERSION：（不明）\r\n";

                    rdr.Close();
                    scnMASTER.Close();
                    return true;
                }
                else
                {
                    strBody += "VERSION：（不明）\r\n";
                    return false;
                }
            }
            catch
            {
                strBody += "Status：（不明）\r\n";
                strBody += "VERSION：（不明）\r\n";
                return false;
            }
        }

        public void ChkDirectory(ref string strBody)
        {
            strBody += "\r\n【Directory】\r\n";
            strBody += Properties.Settings.Default.DataPath + "：" + Directory.Exists(Properties.Settings.Default.DataPath) + "\r\n";
            strBody += Properties.Settings.Default.DataPath + "KB2010.ldf：" + File.Exists(Properties.Settings.Default.DataPath + "\\KB2010.ldf") + "\r\n";
            strBody += Properties.Settings.Default.DataPath + "KB2010.mdf：" + File.Exists(Properties.Settings.Default.DataPath + "\\KB2010.mdf") + "\r\n";

            strBody += "C:\\Program Files\\Microsoft SQL Server" + "：" + Directory.Exists("C:\\Program Files\\Microsoft SQL Server") + "\r\n";

            for (int iCnt = 1; iCnt < 10; iCnt++)
                strBody += "C:\\Program Files\\Microsoft SQL Server\\MSSQL." + iCnt.ToString() + "：" + Directory.Exists("C:\\Program Files\\Microsoft SQL Server\\MSSQL." + iCnt.ToString()) + "\r\n";

            for (int iCnt = 1; iCnt < 10; iCnt++)
                strBody += "C:\\Program Files\\Microsoft SQL Server\\MSSQL." + iCnt.ToString() + "\\MSSQL\\Data" + "：" + Directory.Exists("C:\\Program Files\\Microsoft SQL Server\\MSSQL." + iCnt.ToString() + "\\MSSQL\\Data") + "\r\n";
        }

        public void SendMail(string strTo, string strFrom, string strSubject, string strBody)
        {
            MailMessage msg = new MailMessage(strFrom, strTo, strSubject, strBody);
            SmtpClient sc = new SmtpClient("smtp.e-mail.jp", 587);
            sc.Credentials = new System.Net.NetworkCredential("satouyouhei", "youhei");
            sc.EnableSsl = false;

#if RELEASE
            sc.Send(msg);
#endif
        }

        //依頼者宛にメールを送信する
        public void ErrMail(string strクラス名, string strメソッド名, Exception ex)
        {
            try
            {
                string strSubject;
                string strBody;
                strSubject = "【CSV取込ツール（楽天市場）】システムエラー　User：" + Environment.UserName;
                strBody = strクラス名 + "：" + strメソッド名 + "\r\n\r\n";

                GetException(ex, ref strBody);
                GetUser(ref strBody);
                ChkSQLServer(ref strBody);
                ChkDirectory(ref strBody);
                GetAssembly(ref strBody);

                SendMail("satouyouhei@e-mail.jp", "satouyouhei@e-mail.jp", strSubject, strBody);
            }
            catch (Exception ex2)
            {
                DateTime now = DateTime.Now;

                mTraceSource.TraceEvent(TraceEventType.Error, mProcessID,
                                        now.ToString("yyyy/MM/dd HH:mm:ss") + " : C02業務共通処理 : ErrMail \r\n\r\n" +
                                        ex2.Message + "\r\n" + ex2.StackTrace);

                mTraceSource.Flush();
            }
        }

        public bool IsExistDB()
        {
            bool bExist = true;
            String strSQL;
            SqlConnection scnMASTER = new SqlConnection(Properties.Settings.Default.MASTER);

            try
            {
                strSQL = " if exists(select * from sys.databases where name = 'KB2010') " +
                         "  SELECT 1                                                    " +
                         " else                                                         " +
                         "  SELECT 0                                                    ";

                scnMASTER.Open();

                SqlCommand cmd = new SqlCommand(strSQL, scnMASTER);
                SqlDataReader rdr = cmd.ExecuteReader();
                rdr.Read();
                if (rdr[0].ToString() == "1")
                    bExist = true;
                else
                    bExist = false;


            }
            catch (Exception ex)
            {
                Program.業務共通処理.ErrorLog("C02業務共通処理", "IsExistDB", ex);
                bExist = false;
            }
            finally
            {
                if (scnMASTER.State == ConnectionState.Open)
                    scnMASTER.Close();
            }

            return bExist;
        }

        public bool IsExistSP()
        {
            bool bExist = true;
            String strSQL;
            SqlConnection scnKB = new SqlConnection(Properties.Settings.Default.KB);

            try
            {
                strSQL = " if exists(SELECT * FROM dbo.sysobjects WHERE [ID] = OBJECT_ID('SP_CREATE_TABLE')) " +
                         "  SELECT 1                                                    " +
                         " else                                                         " +
                         "  SELECT 0                                                    ";

                //MessageBox.Show("1:" + Properties.Settings.Default.KB);
                scnKB.Open();

                //MessageBox.Show("2:" + strSQL);

                SqlCommand cmd = new SqlCommand(strSQL, scnKB);
                SqlDataReader rdr = cmd.ExecuteReader();
                rdr.Read();
                if (rdr[0].ToString() == "1")
                    bExist = true;
                else
                    bExist = false;


            }
            catch (System.Exception ex)
            {
                Program.業務共通処理.ErrorLog("C02業務共通処理", "IsExistSP", ex);
                bExist = false;
            }
            finally
            {
                if (scnKB.State == ConnectionState.Open)
                    scnKB.Close();
            }

            return bExist;
        }

        public void 未登録顧客の顧客Noを0にする()
        {
            D03販売履歴TableAdapters.D03販売履歴ta ta = new D03販売履歴TableAdapters.D03販売履歴ta();
            ta.Update未登録顧客の顧客Noを0にする();
        }

        public string NULLを空文字に変換(object str)
        {
            if (str == null)
                return "";
            else
                return (string)str;
        }

        public byte Get性別(string str性別)
        {
            byte bt性別 = 1; // 男性/女性 以外を初期値にする
            if (str性別 == "男")
                bt性別 = 2;
            else if (str性別 == "女")
                bt性別 = 3;
            else
                bt性別 = 1;

            return bt性別;
        }

        public bool IsValidate共通(string value, bool Is必須入力チェックを行う, int maxlength, enm正規表現 正規表現idx, string header, ref string strErrorDetail)
        {
            if (Is必須入力チェックを行う)
            {
                if (value == string.Empty)
                {
                    strErrorDetail = string.Format(Properties.Resources.MSG_INF_075, header);
                    return false;
                }
            }

            if (value.Length > maxlength)
            {
                strErrorDetail = string.Format(Properties.Resources.MSG_INF_033, header, maxlength);
                return false;
            }


            if (value == "") return true;   // データが無ければ、後のチェックを行わない。

            if (!Program.業務共通処理.IsMatch(value, 正規表現idx))
            {
                if (((正規表現idx == enm正規表現.半角数字) || (正規表現idx == enm正規表現.メールアドレス)) &&
                    (value == string.Empty))
                {
                    //半角数字、メールアドレス、IPアドレスの場合で空文字の場合はエラーとしない
                    return true;
                }

                if (正規表現idx == enm正規表現.半角数字)
                {
                    if (header == "商品単価")
                        strErrorDetail = string.Format(Properties.Resources.MSG_INF_100, header, (long)enm最大値.商品単価);
                    else if (header == "販売個数")
                        strErrorDetail = string.Format(Properties.Resources.MSG_INF_100, header, (long)enm最大値.販売個数);
                    else if (header == "年齢")
                        strErrorDetail = string.Format(Properties.Resources.MSG_INF_100, header, (long)enm最大値.年齢);
                }
                else
                {
                    strErrorDetail = string.Format(Properties.Resources.MSG_INF_052, header, 正規表現idx.ToString());
                }

                return false;
            }

            return true;
        }

        #endregion
    
    }
}
