FrmServiceManager.cs 40.0 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
//----------------------------------------------------------------
// Copyright (C) 2000-2003 Shangxin Corporation
// All rights reserved.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.DirectoryServices;
using System.Resources;
using Microsoft.Win32;
using Comm;

namespace ServiceManager
{
    public partial class FrmServiceManager : FrmBase
    {
        private string m_strServiceLocalPath;	//web service 的本地目录
        private string m_strConfigPath;			//web.config 的完全路径
        private string m_strServiceADPath;		//web service 的 AD 目录,可能为虚拟目录
        private string m_strServerADPath;		//web service 所在的站点的 AD 目录
        private Icon IconStop;
        public const string SECRET = "kjhqjherqiheramnxsaskjjkhqewurhbdnbaqjdquermqerjqnerkqelkjdqejhefjqfeqwfrqdjmqjejfndewffheqwkhbgeqwdeqwdxeqwdhbeqwdjqwdkjheqwjfhdjeqwhfbjwfkbeqwhbdvhgftwgdiurbdqliyh";
        private Icon IconStart;
        private Icon IconPause;
        private bool bReadingConfig = false;	//Benjamin 2004-8-17
        private FrmOptionSet frmOptionSet = new FrmOptionSet();
        private FrmAbout frmAbout = new FrmAbout();

        private bool hasInsPDhistory = false;
        private bool isExit = false;

        public FrmServiceManager()
        {
            InitializeComponent();
            this.Menu = mnuMain;
            NotifyIcon_WebService.ContextMenu = mnuNotify;
            frmOptionSet.Owner = this;
            this.mnuNotify.MergeMenu(this.mnuFile);	//Add Menu to ContextMenu
            PrepareIcons();
            GetConfigPath();
            GetServerADPath();
            GetServerState();	//Benjamin 2004-8-17
            GetConfig();//Benjamin 2004-8-17
        }
        /// <summary>
        /// 应用程序的主入口点。参数 /n 表示后台运行,不显示界面
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                //判断同一物理路径下该程序只有当前一个实例运行
                int OpenNum = 0;
                Process[] myProcesses = Process.GetProcessesByName("Contamination ExplorerServer");
                foreach (Process myProcess in myProcesses)
                {
                    if (myProcess.MainModule.FileName == Application.ExecutablePath)
                        OpenNum++;
                }
                if (OpenNum > 1)
                    return;
            }
            catch { }
            FrmServiceManager mainFrm = new FrmServiceManager();
            if (args.Length == 0)
            {
                Application.Run(mainFrm);
            }
            else if (args[0].ToString() == "/n")	//后台运行,不显示界面
            {
                Application.Run();
            }
        }
        
        /// <summary>
        /// 原准备从资源文件中读取三种状态的图标,放入窗体内变量
        /// 后改为利用各窗体存储
        /// </summary>
        private void PrepareIcons()
        {
            try
            {
                IconStart = (new FrmAbout()).Icon;
                IconPause = this.NotifyIcon_WebService.Icon;
                IconStop = this.Icon;
                //this.NotifyIcon_WebService.Icon = IconStart;
                //this.Icon = IconStart;
            }
            catch { }
        }

        /// <summary>
        /// 取得 Web.Config 文件的路径
        /// </summary>
        /// <returns>成功得到路径则返回路径,否则返回空。此处路径返回成功不一定说明 config 文件一定存在</returns>
        private string GetConfigPath()
        {
            m_strServiceLocalPath = Application.ExecutablePath;//先取本程序路径
            try
            {
                do
                {	//从当前路径一级级往上,一直找到 ServiceManager 目录为止
                    m_strServiceLocalPath = Directory.GetParent(m_strServiceLocalPath).ToString();
                    m_strServiceLocalPath = m_strServiceLocalPath.ToLower();
                }
                while (!m_strServiceLocalPath.EndsWith("servicemanager"));
                m_strServiceLocalPath = Directory.GetParent(m_strServiceLocalPath).ToString();
                m_strServiceLocalPath += @"\WebService";
                this.txtServiceLocalPath.Text = m_strServiceLocalPath;	//界面上显示目录 Benjamin 2003-11-27
                m_strConfigPath = m_strServiceLocalPath + @"\web.config";	//最终将路径设为与 ServiceManager 同一级的 WebService 目录下的 web.config
            }
            catch
            {
                m_strServiceLocalPath = "";
                m_strConfigPath = "";
                MessageBox.Show("Contamination Explorer 服务管理器未能找到与 ServiceManager 目录同一级的 WebService 目录下的 Web.config 文件!\n本程序应位于名为 ServiceManager 的目录之下", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            return m_strConfigPath;
        }

        /// <summary>
        /// 读出config 中的相关变量,并显示于界面
        /// </summary>
        /// <returns>有任何错误,则返回 false</returns>
        private bool GetConfig()
        {
            bool bResult = true;
            if (String.IsNullOrEmpty(m_strConfigPath.Trim()))	//config文件路径空,则直接返回
                return false;
            bReadingConfig = true; //Benjamin 2004-8-17  To tell the chkLiveUpdate.CheckedChanged event handler that this is read from config file

            WebConfig m_wc = new WebConfig();
            m_wc.WebConfigPath = m_strConfigPath;
            Configuration.ConnectionString = m_wc.GetWebConfig(WebConfig.MyCMMIConfiguration, "MyCMMI.DataAccess.ConnectionString");
            //txtCurrentDBServer.Text = GetDBServerName(Configuration.ConnectionString);
            txtCurrentClientPath.Text = m_wc.GetWebConfig(WebConfig.MyCMMIConfiguration, "MyCMMI.WebService.ClientPath");
            
            //if (!this.GetLicenceInfo(m_wc.GetWebConfig(WebConfig.MyCMMIConfiguration, "MyCMMI.MyCMMI.LicencePath")))
            //    return false;

            string f_IsUpdate = m_wc.GetWebConfig(WebConfig.MyCMMIConfiguration, @"MyCMMI.MyCMMI.UpdateSwitch");
            if (f_IsUpdate == "True")
            {
                chkLiveUpdate.Checked = true;
            }
            else
            {
                chkLiveUpdate.Checked = false;
            }
            //btnLivaUpdateOK.Enabled = false;  Benjamin 2004-8-17
            tmrManager.Start();
            //bResult = GetLicenceInfo();
            //if (String.IsNullOrEmpty(txtCurrentDBServer.Text.Trim()))
            //    bResult = false;
            bReadingConfig = false;//Benjamin 2004-8-17  To tell the chkLiveUpdate.CheckedChanged event handler that finish reading from config file
            return bResult;
        }

        /// <summary>
        /// 取得对应 WebService 的 IIS 目录
        /// </summary>
        /// <returns>成功得到目录则返回目录,否则返回空。</returns>
        private string GetServerADPath()
        {
            m_strServiceADPath = "";
            if (!String.IsNullOrEmpty(m_strConfigPath.Trim()))
            {
                DirectoryEntry m_de = new DirectoryEntry("IIS://localhost/w3svc");
                m_strServiceADPath = this.FindDirInChildren(m_de, m_strServiceLocalPath);
                m_strServerADPath = GetWebServerName(m_strServiceADPath);
                if (String.IsNullOrEmpty(m_strServerADPath.Trim()))
                    MessageBox.Show("Contamination Explorer 服务管理器未能找到对应 WebService 的 IIS 目录!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            return m_strServerADPath;
        }

        /// <summary>
        /// 递归算法在一个 DirectoryEntry 的 Children 中查找设为指定目录的站点或虚拟目录
        /// </summary>
        /// <param name="objParent">充当容器的 DirectoryEntry </param>
        /// <param name="strDir">指定的本地目录</param>
        /// <returns>返回找到的 DirectoryEntry 的 Path,空字符串表示未找到</returns>
        private string FindDirInChildren(DirectoryEntry objParent, string strDir)
        {
            //遍历所有child
            foreach (DirectoryEntry m_child in objParent.Children)
            {
                //是否当前站点或目录即是目标,是则返回,注意可能包含 \字符,也可能不包含
                try
                {
                    if (m_child.SchemaClassName == "IIsWebServer" || m_child.SchemaClassName == "IIsWebVirtualDir")
                    {
                        string strChildPath = m_child.Properties["Path"][0].ToString().ToLower();
                        strChildPath = strChildPath.EndsWith(@"\") ? strChildPath : strChildPath + @"\";
                        strDir = strDir.EndsWith(@"\") ? strDir : strDir + @"\";

                        if (String.Compare(strChildPath, strDir, true) == 0)
                            return m_child.Path;
                    }
                }
                catch//(Exception ex)
                {

                }
                //如前一步未找到,且目前为站点,则递归其下的虚拟目录
                string strRet = FindDirInChildren(m_child, strDir);
                if (!String.IsNullOrEmpty(strRet.Trim()))
                    return strRet;
            }
            return ""; //以上都无结果,则返回空字符串
        }

        /// <summary>
        /// 向上递归返回一个 DirectoryEntry 的为 IIsWebServer的 Parent 站点
        /// </summary>
        /// <param name="strPath">DirectoryEntry 的 Path</param>
        /// <returns>返回找到的 DirectoryEntry 的 Path,空字符串表示未找到</returns>
        private string GetWebServerName(string strPath)
        {
            if (String.IsNullOrEmpty(strPath.Trim()))
                return "";
            try
            {
                DirectoryEntry m_de = new DirectoryEntry(strPath);
                return GetWebServerName(m_de);
            }
            catch
            { }
            return "";
        }

        /// <summary>
        /// 向上递归返回一个 DirectoryEntry 的类型为 IIsWebServer 的 Parent 站点
        /// </summary>
        /// <param name="objChild">DirectoryEntry</param>
        /// <returns>返回找到的 DirectoryEntry 的 Path,空字符串表示未找到</returns>
        private string GetWebServerName(DirectoryEntry objChild)
        {
            if (objChild.SchemaClassName == "IIsWebServer")
                return objChild.Path;
            else
                return GetWebServerName(objChild.Parent);
        }

        /// <summary>
        /// 取得所管理 WebService 的状态,并显示于界面
        /// </summary>
        /// <returns>有任何错误,则返回 false</returns>
        private bool GetServerState()
        {
            string temp;
            bool bRet = GetServerState(out temp);
            return bRet;
        }

        /// <summary>
        /// 取得所管理 WebService 的状态,并显示于界面
        /// </summary>
        /// <param name="strState">传出参数,指示 Service 当前状态</param>
        /// <returns>有任何错误,则返回 false</returns>
        private bool GetServerState(out string strState)
        {
            bool bResult = true;
            if (String.IsNullOrEmpty(m_strServerADPath.Trim())) //未取到 WebService 的 IIS 路径,则直接返回
            {
                strState = "0";
                return false;
            }
            try
            {
                DirectoryEntry m_de = new DirectoryEntry(m_strServerADPath);
                int i = 0;
                object o = i;
                o = m_de.Invoke("Get", "ServerState");
                switch (o.ToString())
                {
                    case "2":	//运行状态
                        this.NotifyIcon_WebService.Text = "正在运行 - Contamination Explorer Server";
                        this.NotifyIcon_WebService.Icon = IconStart;
                        this.Icon = IconStart;
                        picState.Image = imgList.Images[0];
                        btn_Start.Enabled = false;
                        btn_Pause.Enabled = true;
                        btn_Stop.Enabled = true;
                        break;
                    case "6":	//暂停状态
                        this.NotifyIcon_WebService.Text = "已暂停 - Contamination Explorer Server";
                        this.NotifyIcon_WebService.Icon = IconPause;
                        this.Icon = IconPause;
                        picState.Image = imgList.Images[1];
                        btn_Start.Enabled = true;
                        btn_Pause.Enabled = false;
                        btn_Stop.Enabled = true;
                        break;
                    case "4":	//停止状态
                        this.NotifyIcon_WebService.Text = "已停止 - Contamination Explorer Server";
                        this.NotifyIcon_WebService.Icon = IconStop;
                        this.Icon = IconStop;
                        picState.Image = imgList.Images[2];
                        btn_Start.Enabled = true;
                        btn_Pause.Enabled = false;
                        btn_Stop.Enabled = false;
                        break;
                    default:
                        this.NotifyIcon_WebService.Text = this.Text;
                        this.NotifyIcon_WebService.Icon = IconStop;
                        this.Icon = IconStop;
                        picState.Image = imgList.Images[2];
                        btn_Start.Enabled = false;
                        btn_Pause.Enabled = false;
                        btn_Stop.Enabled = false;
                        break;
                }
                this.txtState.Text = this.NotifyIcon_WebService.Text;	//Benjamin 2003-11-27
                strState = o.ToString();
                m_de.Dispose();	//Benjamin Qin 2004-8-16 15:18
                bResult = true;
            }
            catch//(Exception ex)
            {
                strState = "0";//
                bResult = false;
            }
            return bResult;
        }

        /// <summary>
        /// 改变 WebService 状态
        /// </summary>
        /// <param name="strCommand">命令字符串,可选 Start Pause Stop 等</param>
        /// <returns>失败返回false</returns>
        private bool SetServiceState(string strCommand)
        {
            bool bResult = true;
            try
            {
                DirectoryEntry m_de = new DirectoryEntry(m_strServerADPath);
                m_de.Invoke(strCommand, new object[0]);
                m_de.CommitChanges();
            }
            catch
            {
                bResult = false;
            }
            return bResult;
        }

        /// <summary>
        /// 检查数据库设置各参数是否合法
        /// </summary>
        /// <returns>成功返回 true,失败返回 false</returns>
        //private bool CheckNewDBConfig()
        //{
        //    txtDatabase.Text = txtDatabase.Text.Trim();
        //    txtDBServer.Text = txtDBServer.Text.Trim();
        //    txtUserName.Text = txtUserName.Text.Trim();
        //    if (String.IsNullOrEmpty(txtDBServer.Text.Trim()))
        //    {
        //        MessageBox.Show("数据库服务器不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //        this.txtDBServer.Focus();
        //        return false;
        //    }
        //    if (String.IsNullOrEmpty(txtDatabase.Text.Trim()))
        //    {
        //        MessageBox.Show("数据库名称不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //        this.txtDatabase.Focus();
        //        return false;
        //    }
        //    if (String.IsNullOrEmpty(txtUserName.Text.Trim()))
        //    {
        //        MessageBox.Show("用户名不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //        this.txtUserName.Focus();
        //        return false;
        //    }
        //    return true;
        //}

        /// <summary>
        /// 测试数据库连接
        /// </summary>
        /// <param name="strConnection">未加密的数据库连接字符串</param>
        /// <returns>成功返回 true,失败返回 false</returns>
        private bool TestDBConnection(string strConnection)
        {
            bool bResult = false;
            try
            {
                SqlConnection sqlConnection = new SqlConnection(strConnection);
                sqlConnection.Open();
                if (sqlConnection.State == ConnectionState.Open)
                    bResult = true;
                sqlConnection.Close();
            }
            catch
            {
                bResult = false;
            }
            return bResult;
        }

        /// <summary>
        /// 将数据库连接写入 Config
        /// </summary>
        /// <param name="strConnection">未加密的数据库连接字符串</param>
        /// <returns>成功返回 true,失败返回 false</returns>
        private bool SetDBConnection(string strConnection)
        {
            string strCode = SimpleEncode(strConnection, SECRET);
            WebConfig m_wc = new WebConfig();
            m_wc.WebConfigPath = m_strConfigPath;
            return m_wc.SetWebConfig(WebConfig.MyCMMIConfiguration, "MyCMMI.DataAccess.ConnectionString", strCode);
        }

        /// <summary>
        /// 将客户端目录写入 Config
        /// </summary>
        /// <param name="strClientPath">客户端目录</param>
        /// <returns>成功返回 true,失败返回 false</returns>
        private bool SetClientPath(string strClientPath)
        {
            WebConfig m_wc = new WebConfig();
            m_wc.WebConfigPath = m_strConfigPath;
            return m_wc.SetWebConfig(WebConfig.MyCMMIConfiguration, "MyCMMI.WebService.ClientPath", strClientPath);
        }

        /// <summary>
        /// 根据界面上的输入,生成未加密的数据库字符串
        /// </summary>
        /// <returns>未加密的数据库字符串</returns>
        //private string ComposeConnectionString()
        //{
        //    return "server=" + txtDBServer.Text + ";User ID=" + txtUserName.Text + ";Password=" + txtPassword.Text + ";database=" + txtDatabase.Text + ";Connection Reset=FALSE";
        //}

        /// <summary>
        /// 根据加密后的数据库连接字符串,取出数据库服务器名称
        /// </summary>
        /// <param name="ConnectionString">加密后的数据库连接字符串</param>
        /// <returns>数据库服务器名称字符串</returns>
        private string GetDBServerName(string ConnectionString)
        {
            string strResult = "";
            try
            {
                string sqlConnString = Utility.SimpleDecode(ConnectionString, SECRET);//解密字符串
                int iBegin, iEnd;//服务器名称 DBServerName 包含于数据库连接字符串中,形式为:"server=DBServerName;"
                iBegin = sqlConnString.IndexOf("server=") + "server=".Length;
                iEnd = sqlConnString.IndexOf(";", iBegin);
                strResult = sqlConnString.Substring(iBegin, iEnd - iBegin);
            }
            catch
            {
            }
            return strResult;
        }

        /// <summary>
        /// 设置客户端升级开关
        /// </summary>
        /// <param name="f_IsUpdate">True 为开启,False 为关闭</param>
        /// <returns>成功为True,失败为False</returns>
        private bool SetUpdateSwitch(bool f_IsUpdate)
        {
            string f_WebConfigPath = "";
            f_WebConfigPath = GetConfigPath();
            if (String.IsNullOrEmpty(f_WebConfigPath.Trim()))
            {
                return false;
            }
            WebConfig WC = new WebConfig();
            WC.WebConfigPath = f_WebConfigPath;
            string f_StringUpdate = "";
            if (f_IsUpdate)
            {
                f_StringUpdate = "True";
            }
            else
            {
                f_StringUpdate = "False";
            }
            try
            {
                if (!WC.SetWebConfig(WebConfig.MyCMMIConfiguration, @"MyCMMI.MyCMMI.UpdateSwitch", f_StringUpdate))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取升级设置开关
        /// </summary>
        /// <param name="f_IsUpdate">True为开,False为关</param>
        /// <returns>获取成功为True,失败为False</returns>
        private bool GetUpdateSwitch(out bool f_IsUpdate)
        {
            string f_WebConfigPath = "";
            string f_StringUpdate = "";
            f_IsUpdate = false;
            f_WebConfigPath = GetConfigPath();
            if (String.IsNullOrEmpty(f_WebConfigPath.Trim()))
            {
                return false;
            }
            WebConfig WC = new WebConfig();
            WC.WebConfigPath = f_WebConfigPath;
            try
            {
                f_StringUpdate = WC.GetWebConfig(WebConfig.MyCMMIConfiguration, @"MyCMMI.MyCMMI.UpdateSwitch");
            }
            catch
            {
                return false;
            }
            if (f_StringUpdate == "True")
            {
                f_IsUpdate = true;
                return true;
            }
            if (f_StringUpdate == "False")
            {
                f_IsUpdate = false;
                return true;
            }
            return false;
        }

        private void OpenForm()
        {
            if (this.WindowState == FormWindowState.Minimized)
                this.WindowState = FormWindowState.Normal;
            this.Show();
            this.Activate();
        }

        /// <summary>
        /// 获取许可证信息
        /// </summary>
        /// <returns>成功返回 true ,失败返回 false</returns>
        //private bool GetLicenceInfo(string filePath)
        //{
        //    try
        //    {
        //        //bool f_IsResult = false;
        //        //string f_LicencePath = filePath;
        //        //				f_LicencePath = Application.StartupPath + @"\MyCMMI.lic";

        //        if (String.IsNullOrEmpty(filePath.Trim()))
        //        {
        //            return false;
        //        }
        //        //if (!File.Exists(filePath))
        //        //{
        //        //    return false;
        //        //}

        //        Licence LC = new Licence();

        //        if (!LC.VerifySigned(filePath))
        //        {
        //            return false;
        //        }
        //        else
        //        {
        //            txtCompanyName.Text = LC.GetCompanyNameFromLicence();
        //            txtFromDate.Text = LC.GetFromDateFromLicence();
        //            txtToDate.Text = LC.GetToDateFromLicence();
        //            txtDiskID.Text = LC.GetDiskIDFromLicence();
        //            return true;
        //        }
        //    }
        //    catch
        //    {
        //        return false;
        //    }
        //}

        /// <summary>
        /// 加密函数,在 MyCMMI.Comm中Utility类中实现。此处为复制
        /// </summary>
        /// <param name="strSrc"></param>
        /// <param name="constSecret"></param>
        /// <returns></returns>
        public static string SimpleEncode(string strSrc, string constSecret)
        {
            char[] cnB = constSecret.ToCharArray(0, constSecret.Length);
            char[] show = strSrc.ToCharArray(0, strSrc.Length);
            string str = "";
            for (int i = 0; i < show.Length; i++)
            {
                int sum = Convert.ToInt16(cnB[i]) + Convert.ToInt16(show[i]);
                string s = "";
                if (sum < 100 && sum >= 10)
                    s = "0" + sum.ToString();
                else if (sum < 10)
                    s = "00" + sum.ToString();
                else s = sum.ToString();
                str = str + s;
            }
            return str;
        }

        /// <summary>
        /// 解密函数,在 MyCMMI.Comm中Utility类中实现。此处为复制
        /// </summary>
        /// <param name="strSrc"></param>
        /// <param name="constSecret"></param>
        /// <returns></returns>
        //public static string SimpleDecode(string result, string constSecret)
        //{
        //    char[] cnB = constSecret.ToCharArray(0, constSecret.Length);
        //    char[] rB = result.ToCharArray(0, result.Length);
        //    string str = "";
        //    for (int i = 0; i < rB.Length; i += 3)
        //    {
        //        string s2 = result.Substring(i, 3);
        //        int sum = Convert.ToInt16(s2);
        //        char src = Convert.ToChar(sum - Convert.ToInt16(cnB[i / 3]));
        //        string s = src.ToString();
        //        str = str + s;
        //    }
        //    return str;
        //}

        private void btn_Start_Click(object sender, System.EventArgs e)
        {
            //鼠标等待
            Cursor.Current = Cursors.WaitCursor;
            string strState;
            GetServerState(out strState);
            switch (strState)
            {
                case "4"://停止状态
                    SetServiceState("Start");
                    break;
                case "6"://暂停状态
                    SetServiceState("Continue");
                    break;
                default:
                    break;
            }
            //鼠标恢复
            Cursor.Current = Cursors.Default;
        }

        private void btn_Pause_Click(object sender, System.EventArgs e)
        {
            if (MessageBox.Show("确实要暂停 Contamination Explorer 服务吗?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //鼠标等待
                Cursor.Current = Cursors.WaitCursor;
                SetServiceState("Pause");
                //鼠标恢复
                Cursor.Current = Cursors.Default;
            }
        }

        private void btn_Stop_Click(object sender, System.EventArgs e)
        {
            if (MessageBox.Show("确实要停止 Contamination Explorer 服务吗?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //鼠标等待
                Cursor.Current = Cursors.WaitCursor;
                SetServiceState("Stop");
                //鼠标恢复
                Cursor.Current = Cursors.Default;
            }
        }

        private void NotifyIcon_WebService_DoubleClick(object sender, System.EventArgs e)
        {
            OpenForm();
        }

        //private void FrmServiceManager_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        //{
        //    this.Visible = false;
        //    e.Cancel = true;
        //}     

        //private void btnTestConnect_Click(object sender, System.EventArgs e)
        //{
        //    //鼠标等待
        //    Cursor.Current = Cursors.WaitCursor;
        //    if (CheckNewDBConfig())
        //    {
        //        bool bResult = TestDBConnection(ComposeConnectionString());
        //        if (bResult)
        //            MessageBox.Show("数据库连接成功!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        //        else
        //            MessageBox.Show("数据库连接失败!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //    }
        //    //鼠标恢复
        //    Cursor.Current = Cursors.Default;
        //}

        //private void btnOK_Click(object sender, System.EventArgs e)
        //{
        //    //鼠标等待
        //    Cursor.Current = Cursors.WaitCursor;
        //    if (CheckNewDBConfig())
        //    {
        //        if (SetDBConnection(ComposeConnectionString()))
        //        {
        //            MessageBox.Show("数据库设置成功!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        //            txtDBServer.Text = "";
        //            txtDatabase.Text = "";
        //            txtUserName.Text = "";
        //            txtPassword.Text = "";
        //        }
        //        else
        //            MessageBox.Show("数据库设置失败!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //    }
        //    //鼠标恢复
        //    Cursor.Current = Cursors.Default;
        //}

        private void tmrManager_Tick(object sender, System.EventArgs e)
        {
            GetServerState();//定期取最新  Service 状态
            //每当 Visible ==true 时
            if (this.Visible)
                if (!GetConfig())//定期取最新 Config
                {
                    isExit = true;
                    Application.Exit();
                }

            if (DateTime.Now.DayOfWeek != DayOfWeek.Saturday)
                hasInsPDhistory = false;

            if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday && !hasInsPDhistory)
            {
                hasInsPDhistory = true;
            }
        }

        //private void txtDatabase_Leave(object sender, System.EventArgs e)
        //{
        //    txtDatabase.Text = txtDatabase.Text.Trim();
        //}

        //private void txtDBServer_Leave(object sender, System.EventArgs e)
        //{
        //    txtDBServer.Text = txtDBServer.Text.Trim();
        //}

        //private void txtUserName_Leave(object sender, System.EventArgs e)
        //{
        //    txtUserName.Text = txtUserName.Text.Trim();
        //}

        private void btnBrowser_Click(object sender, System.EventArgs e)
        {
            BrowseForFolderClass mybff = new BrowseForFolderClass();
            string strPath = mybff.BrowseForFolder("请指定客户端目录");

            if (!String.IsNullOrEmpty(strPath.Trim()))
                txtClientPath.Text = strPath;
        }

        private void btnLivaUpdateOK_Click(object sender, System.EventArgs e)
        {
            txtClientPath.Text = txtClientPath.Text.Trim();
            //			if(txtClientPath.Text .Trim()== "")
            //			{
            //				MessageBox.Show("请指定要设置的客户端目录!",this.Text,MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            //				txtClientPath.Focus();
            //				return;
            //			}
            //鼠标等待
            Cursor.Current = Cursors.WaitCursor;

            if (!String.IsNullOrEmpty(txtClientPath.Text.Trim()))
            {
                if (SetClientPath(txtClientPath.Text))
                {
                    txtClientPath.Text = "";
                    MessageBox.Show("客户端更新设置成功!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btnLivaUpdateOK.Enabled = false;
                }
                else
                {
                    MessageBox.Show("客户端更新设置失败!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            else
            {
                MessageBox.Show("请指定要设置的客户端目录!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtClientPath.Focus();
            }

            //鼠标恢复
            Cursor.Current = Cursors.Default;
        }

        private void btnTestCurrentDB_Click(object sender, System.EventArgs e)
        {
            //鼠标等待
            Cursor.Current = Cursors.WaitCursor;
            WebConfig m_wc = new WebConfig();
            m_wc.WebConfigPath = m_strConfigPath;
            string strConn = Utility.SimpleDecode(m_wc.GetWebConfig(WebConfig.MyCMMIConfiguration, "MyCMMI.DataAccess.ConnectionString"), SECRET);
            if (TestDBConnection(strConn))
                MessageBox.Show("当前数据库连接成功!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show("当前数据库连接失败!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            //鼠标恢复
            Cursor.Current = Cursors.Default;
        }

        private void btnTestWebConfig_Click(object sender, System.EventArgs e)
        {
            //鼠标等待
            Cursor.Current = Cursors.WaitCursor;
            GetConfigPath();
            if (!String.IsNullOrEmpty(m_strConfigPath.Trim()))	//若找到该文件,则报路径信息 
            {
                if (GetConfig())
                    MessageBox.Show("读取 Config 文件成功!\n文件位于 " + m_strConfigPath, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                    MessageBox.Show("读取 Config 文件失败,请检查该文件是否存在或设置是否正确!\n文件应位于 " + m_strConfigPath, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            //鼠标恢复
            Cursor.Current = Cursors.Default;
        }

        private void btnTestWebService_Click(object sender, System.EventArgs e)
        {
            //鼠标等待
            Cursor.Current = Cursors.WaitCursor;
            GetServerADPath();
            if (!String.IsNullOrEmpty(m_strServerADPath.Trim()))
                MessageBox.Show("MyCMMI 服务管理器成功找到 Web 服务!\nWebService 的目录 " + m_strServiceADPath + "\n所属站点为 " + m_strServerADPath, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //鼠标恢复
            Cursor.Current = Cursors.Default;
        }       

        private void txtClientPath_TextChanged(object sender, System.EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtClientPath.Text.Trim()))
            {
                btnLivaUpdateOK.Enabled = true;
            }
        }

        private void chkLiveUpdate_CheckedChanged(object sender, System.EventArgs e)
        {
            btnLivaUpdateOK.Enabled = chkLiveUpdate.Checked;
            txtClientPath.Enabled = chkLiveUpdate.Checked;
            btnBrowser.Enabled = chkLiveUpdate.Checked;
            if (!bReadingConfig) //Benjamin 2004-8-17 If program is reading config file,handler does nothing. Else it supposes CheckedChanged is triggered by User,will do something below:
            {
                if (SetUpdateSwitch(chkLiveUpdate.Checked))
                    MessageBox.Show("客户端更新设置成功!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                    MessageBox.Show("客户端更新设置失败!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        //private void btnBrowser2_Click(object sender, System.EventArgs e)
        //{
        //    OpenFileDialog dlgOpenFile = new OpenFileDialog();
        //    dlgOpenFile.Multiselect = false;
        //    dlgOpenFile.Title = "指定许可证文件";
        //    dlgOpenFile.Filter = "许可证文件(*.lic)|*.lic";
        //    dlgOpenFile.FilterIndex = 1;
        //    dlgOpenFile.RestoreDirectory = true;

        //    if (dlgOpenFile.ShowDialog(this) == DialogResult.OK)
        //    {
        //        txtLicenseFile.Text = dlgOpenFile.FileName;
        //    }
        //}

        //private void btnImport_Click(object sender, System.EventArgs e)
        //{
        //    Cursor.Current = Cursors.WaitCursor;
        //    string f_WebConfigPath = "";
        //    txtLicenseFile.Text = txtLicenseFile.Text.Trim();
        //    if (String.IsNullOrEmpty(txtLicenseFile.Text.Trim()))
        //    {
        //        MessageBox.Show("请指定要导入的新许可证文件!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //        txtLicenseFile.Focus();
        //        return;
        //    }
        //    else
        //    {	//导入许可证的代码
        //        f_WebConfigPath = GetConfigPath();
        //        if (String.IsNullOrEmpty(f_WebConfigPath))
        //        {
        //            MessageBox.Show("设置 Config 失败!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //            txtLicenseFile.Focus();
        //            return;
        //        }
        //        WebConfig WC = new WebConfig();
        //        WC.WebConfigPath = f_WebConfigPath;
        //        if (!WC.SetWebConfig(WebConfig.MyCMMIConfiguration, "MyCMMI.MyCMMI.LicencePath", txtLicenseFile.Text))
        //        {
        //            MessageBox.Show("许可证设置失败!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //            txtLicenseFile.Focus();
        //            return;
        //        }
        //        if (GetLicenceInfo(this.txtLicenseFile.Text.Trim()))
        //        {
        //            MessageBox.Show("许可证导入成功!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        //            txtLicenseFile.Text = "";
        //            return;
        //        }
        //        else
        //        {
        //            MessageBox.Show("许可证导入失败!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //            txtLicenseFile.Focus();
        //            return;
        //        }
        //    }
        //}

        private void FrmServiceManager_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isExit)
                return;

            this.Visible = false;
            e.Cancel = true;
        }

        private void mnuNotify_Popup(object sender, EventArgs e)
        {
            if (frmOptionSet.Modal)		//Benjamin 2004-8-16
                frmOptionSet.Activate();
        }

        private void mnuOpen_Click(object sender, EventArgs e)
        {
            OpenForm();
        }

        private void mnuStop_Click(object sender, EventArgs e)
        {
            btn_Stop_Click(null, null);
        }

        private void mnuPause_Click(object sender, EventArgs e)
        {
            btn_Pause_Click(null, null);
        }

        private void mnuStart_Click(object sender, EventArgs e)
        {
            btn_Start_Click(null, null);
        }

        private void mnuOption_Click(object sender, EventArgs e)
        {
            frmOptionSet.ShowInTaskbar = false;
            if (frmOptionSet.Modal)			//Benjamin 2004-8-16 :
                frmOptionSet.Activate();
            else
                frmOptionSet.ShowDialog(this);
        }

        private void mnuAbout_Click(object sender, EventArgs e)
        {
            try
            {
                frmAbout.Show();
                frmAbout.Activate();
            }
            catch
            {
                frmAbout = new FrmAbout();
                frmAbout.ShowInTaskbar = false;
                frmAbout.Show();
            }
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            this.NotifyIcon_WebService.Visible = false;	//隐藏图标
            this.isExit = true;
            Application.Exit();				//程序退出
        }

        private void txtLicenseFile_TextChanged(object sender, EventArgs e)
        {

        }

        private void label8_Click(object sender, EventArgs e)
        {

        }

        private void txtDiskID_TextChanged(object sender, EventArgs e)
        {

        }

        private void label7_Click(object sender, EventArgs e)
        {

        }

        private void txtToDate_TextChanged(object sender, EventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void txtFromDate_TextChanged(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void txtCompanyName_TextChanged(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }
    }
}