예제 #1
0
        /// <summary>
        /// 打开应用程序
        /// </summary>
        /// <param name="appPath"></param>
        public static void AppStart(string appPath)
        {
            try
            {
                string appStartPath = appPath;
                IntPtr userTokenHandle = IntPtr.Zero;
                ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);

                ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION();
                ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO();
                startInfo.cb = (uint)Marshal.SizeOf(startInfo);

                ApiDefinitions.CreateProcessAsUser(
                    userTokenHandle,
                    appStartPath,
                    "",
                    IntPtr.Zero,
                    IntPtr.Zero,
                    false,
                    0,
                    IntPtr.Zero,
                    null,
                    ref startInfo,
                    out procInfo);

                if (userTokenHandle != IntPtr.Zero)
                    ApiDefinitions.CloseHandle(userTokenHandle);

                int _currentAquariusProcessId = (int)procInfo.dwProcessId;
            }
            catch (Exception ex)
            {
                LogHelpr.Error("打开程序时出错:" + ex.ToString());
            }
        }
예제 #2
0
        private void OpenApp4Service(string appName, string cmdLine)
        {
            try
            {
                //string appStartPath = @"C:\\Deepleo.exe";
                IntPtr userTokenHandle = IntPtr.Zero;
                ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);

                ApiDefinitions.PROCESS_INFORMATION procInfo  = new ApiDefinitions.PROCESS_INFORMATION();
                ApiDefinitions.STARTUPINFO         startInfo = new ApiDefinitions.STARTUPINFO();

                startInfo.cb = (uint)Marshal.SizeOf(startInfo);
                ApiDefinitions.CreateProcessAsUser(userTokenHandle, appName, cmdLine, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref startInfo, out procInfo);
                if (userTokenHandle != IntPtr.Zero)
                {
                    ApiDefinitions.CloseHandle(userTokenHandle);
                }

                //int _currentAquariusProcessId = (int)procInfo.dwProcessId;
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Start Application failed, its path is {0} ,exception: {1}", appName, ex.Message);
            }
        }
예제 #3
0
        public static void StartApp(string strAppPath)
        {
            try
            {
                IntPtr userTokenHandle = IntPtr.Zero;
                ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);

                ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION();
                ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO();
                startInfo.cb = (uint)Marshal.SizeOf(startInfo);

                ApiDefinitions.CreateProcessAsUser(
                    userTokenHandle,
                    strAppPath,
                  "",
                    IntPtr.Zero,
                    IntPtr.Zero,
                    false,
                    0,
                    IntPtr.Zero,
                    null,
                    ref startInfo,
                    out procInfo);

                if (userTokenHandle != IntPtr.Zero)
                    ApiDefinitions.CloseHandle(userTokenHandle);

                var _currentAquariusProcessId = (int)procInfo.dwProcessId;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }
예제 #4
0
        /// <summary>
        /// 切换进程2
        /// </summary>
        /// <param name="killAppName"></param>
        /// <param name="openAppName"></param>
        /// <param name="openAppNamePath"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static void ToggleProcess4UserSession(string killAppName, string openAppName, string openAppNamePath, string args)
        {
            //获得到进程,杀死进程
            if (!string.IsNullOrEmpty(killAppName))
            {
                Process[] processes = Process.GetProcessesByName(killAppName);
                if (processes.Length > 0)
                {
                    _log.Info(string.Format("Kill进程:{0}", killAppName));
                    foreach (Process process in processes)
                    {
                        process.Kill();
                    }
                }
            }

            //判断要开启的进程是否已经开启,已经开启则无需开启
            var startProcess = Process.GetProcessesByName(openAppName);

            if (startProcess.Length == 0)
            {
                if (!string.IsNullOrEmpty(openAppNamePath))
                {
                    //启动进程
                    if (File.Exists(openAppNamePath))
                    {
                        try
                        {
                            IntPtr userTokenHandle = IntPtr.Zero;
                            ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);

                            ApiDefinitions.PROCESS_INFORMATION procInfo  = new ApiDefinitions.PROCESS_INFORMATION();
                            ApiDefinitions.STARTUPINFO         startInfo = new ApiDefinitions.STARTUPINFO();

                            startInfo.cb = (uint)Marshal.SizeOf(startInfo);
                            ApiDefinitions.CreateProcessAsUser(userTokenHandle, openAppNamePath, args, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref startInfo, out procInfo);
                            if (userTokenHandle != IntPtr.Zero)
                            {
                                ApiDefinitions.CloseHandle(userTokenHandle);
                            }

                            //int _currentAquariusProcessId = (int)procInfo.dwProcessId;
                        }
                        catch (Exception ex)
                        {
                            _log.ErrorFormat("Start Application failed, its path is {0} ,exception: {1}", openAppNamePath, ex.Message);
                        }
                    }
                }
            }
        }
예제 #5
0
        /// <summary>
        /// 服务启动程序 显示界面
        /// </summary>
        private void HasUI()
        {
            string appName = "demo-winform";
            string appPath = "G://demo-winform.exe";

            Process[] localByName = Process.GetProcessesByName(appName);
            if (localByName.Length == 0) //如果得到的进程数是0, 那么说明程序未启动,需要启动程序
            {
                try
                {
                    IntPtr userTokenHandle = IntPtr.Zero;
                    ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);

                    ApiDefinitions.PROCESS_INFORMATION procInfo  = new ApiDefinitions.PROCESS_INFORMATION();
                    ApiDefinitions.STARTUPINFO         startInfo = new ApiDefinitions.STARTUPINFO();
                    startInfo.cb = (uint)Marshal.SizeOf(startInfo);

                    ApiDefinitions.CreateProcessAsUser(
                        userTokenHandle,
                        appPath,
                        "",
                        IntPtr.Zero,
                        IntPtr.Zero,
                        false,
                        0,
                        IntPtr.Zero,
                        null,
                        ref startInfo,
                        out procInfo);

                    if (userTokenHandle != IntPtr.Zero)
                    {
                        ApiDefinitions.CloseHandle(userTokenHandle);
                    }

                    int _currentAquariusProcessId = (int)procInfo.dwProcessId;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("启动程序失败!" + ex);
                }
            }
            else
            {
                //如果程序已经启动,则执行这一部分代码
            }
        }
예제 #6
0
        private int OpenForm(string filePath)
        {
            try
            {
                string appStartPath    = filePath;
                IntPtr userTokenHandle = IntPtr.Zero;
                ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);

                ApiDefinitions.PROCESS_INFORMATION procInfo  = new ApiDefinitions.PROCESS_INFORMATION();
                ApiDefinitions.STARTUPINFO         startInfo = new ApiDefinitions.STARTUPINFO();
                startInfo.cb = (uint)System.Runtime.InteropServices.Marshal.SizeOf(startInfo);

                ApiDefinitions.CreateProcessAsUser(
                    userTokenHandle,
                    appStartPath,
                    "",
                    IntPtr.Zero,
                    IntPtr.Zero,
                    false,
                    0,
                    IntPtr.Zero,
                    null,
                    ref startInfo,
                    out procInfo);

                if (userTokenHandle != IntPtr.Zero)
                {
                    ApiDefinitions.CloseHandle(userTokenHandle);
                }

                int processId = (int)procInfo.dwProcessId;
                return(processId);
            }
            catch (Exception ex)
            {
                Logs.Log("", "调用Cjwdev.WindowsApi时出错:" + ex.ToString());
            }
            return(0);
        }
예제 #7
0
        public void AppStart(string appPath)
        {
            try
            {
                string appStartPath    = appPath;
                IntPtr userTokenHandle = IntPtr.Zero;
                ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);

                ApiDefinitions.PROCESS_INFORMATION procInfo  = new ApiDefinitions.PROCESS_INFORMATION();
                ApiDefinitions.STARTUPINFO         startInfo = new ApiDefinitions.STARTUPINFO();
                startInfo.cb = (uint)Marshal.SizeOf(startInfo);

                ApiDefinitions.CreateProcessAsUser(
                    userTokenHandle,
                    appStartPath,
                    "",
                    IntPtr.Zero,
                    IntPtr.Zero,
                    false,
                    0,
                    IntPtr.Zero,
                    null,
                    ref startInfo,
                    out procInfo);

                if (userTokenHandle != IntPtr.Zero)
                {
                    ApiDefinitions.CloseHandle(userTokenHandle);
                }

                int _currentAquariusProcessId = (int)procInfo.dwProcessId;
            }
            catch (Exception ex)
            {
                logger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name);
                logger("AppStart failed! " + ex.ToString());
            }
        }
예제 #8
0
        private void StartF()
        {
            try
            {
                IntPtr userTokenHandle = IntPtr.Zero;
                ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);

                ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION();
                ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO();
                startInfo.cb = (uint)Marshal.SizeOf(startInfo);

                ApiDefinitions.CreateProcessAsUser(
                    userTokenHandle,
                    appStartPath,
                  "",
                    IntPtr.Zero,
                    IntPtr.Zero,
                    false,
                    0,
                    IntPtr.Zero,
                    null,
                    ref startInfo,
                    out procInfo);

                if (userTokenHandle != IntPtr.Zero)
                    ApiDefinitions.CloseHandle(userTokenHandle);

                //_currentAquariusProcessId = (int)procInfo.dwProcessId;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(string.Format("Start Application failed, its path is {0} ,exception: {1}", appStartPath, ex.Message));
            }
        }
예제 #9
0
파일: Class1.cs 프로젝트: jedi0605/GitTeach
                protected override void OnStart(string[] args)
                {
                    string vmname = "";
                    string group_id="";
                    AutoProvision_WS.AutoProvision_WS ws = new AutoProvision_WS.AutoProvision_WS();
                    List<string> mac = getLocalMac();
                    //////檢查 兩個檔案是否存在 利用powershell
                    string check_ip_output = checkFile_ip_reboot();
                    if (check_ip_output == "")
                    return;
                    string step1_output = checkFile_step1();
                    if (step1_output == "")
                    return;
                    string line = "";
                    try
                    {
                    System.IO.StreamReader vmname_load = new System.IO.StreamReader(@"c:\AutoProvision\vmname.txt");
                    string[] get_orderID_groupID = vmname_load.ReadToEnd().Split(' ');
                    vmname = get_orderID_groupID[0];
                    group_id = get_orderID_groupID[1];
                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Read vmname.txt vmname:" + vmname +",group_id:"+group_id+ Environment.NewLine);
                    }
                    catch (Exception ex)
                    {
                    System.IO.File.AppendAllText(@"C:\AutoProvision\error.txt", "Read vmname.txt have ex" + ex.Message + Environment.NewLine);
                    return;
                    }
                    /////end

                    ///兩者皆否  撰寫完成
                    if (step1_output == "False" && check_ip_output == "False")
                    {
                    //AutoProvision_WS.AutoProvision_WS ws = new AutoProvision_WS.AutoProvision_WS();
                    try
                    {
                    ws.Inset_Percent(vmname, "60", ""); //寫入進度60%
                    //string[] info_result = ws.Get_Order_Info(vmname).Split('"');
                    //string company_id = info_result[3];
                    //string area = info_result[7];
                    //string member_id = info_result[11];

                    string info_result = ws.Get_Order_Info(vmname);

                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Get_Order_Info info_result:" + info_result+ Environment.NewLine);

                    JToken info = JObject.Parse(info_result);
                    string company_id = info["company_id"].ToString();
                    string area = info["area"].ToString();
                    string member_id = info["member_id"].ToString();
                    string Get_ComputerName_result = ws.Get_ComputerName(vmname);
                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Get_ComputerName static_ip_result:" + Get_ComputerName_result + Environment.NewLine);
                    string[] static_ip_result = Get_ComputerName_result.Split('"');

                    string FQDN = static_ip_result[5];
                    change_computername(FQDN);

                    IntPtr userTokenHandle = IntPtr.Zero;
                    ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);
                    ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION();
                    ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO();
                    startInfo.cb = (uint)Marshal.SizeOf(startInfo);
                    string restart = "restart-computer -force";
                    System.IO.File.WriteAllText(@"C:\AutoProvision\del_item_sc2.ps1", restart);
                    System.IO.File.WriteAllText(@"C:\AutoProvision\step1.txt", "");
                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "CreateFile step1.txt" + Environment.NewLine);
                    Process p = new Process();
                    p.StartInfo.FileName = @"C:\AutoProvision\creboot2.exe";
                    p.StartInfo.UseShellExecute = true;
                    p.Start();

                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Run creboot.exe" + Environment.NewLine);
                    p.WaitForExit();

                    System.Threading.Thread.Sleep(2000);

                    RunspaceInvoke invoker = new RunspaceInvoke();
                    invoker.Invoke("restart-computer -force");
                    string RebootPath = @"C:\AutoProvision\creboot2.exe";

                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Reboot.exe" + Environment.NewLine);
                    ApiDefinitions.CreateProcessAsUser(userTokenHandle,
                        RebootPath,
                        "",
                        IntPtr.Zero,
                        IntPtr.Zero,
                        false,
                        0,
                        IntPtr.Zero,
                        null,
                        ref startInfo,
                        out procInfo);

                    }
                    catch (Exception ex)
                    {
                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "set computer name have ex" + ex.Message + Environment.NewLine);

                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Line=" + line + "*********" + ex.Message);
                    }
                    finally
                    {
                    ws.Dispose();
                    }
                    }
                    /////end

                    ///// 修改 ip domain rdp  未完成
                    if (step1_output == "True" && check_ip_output == "False")
                    {
                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Set computer name ok" + Environment.NewLine);

                    //string v = ws.test();
                    try
                    {

                    RunspaceInvoke invoker = new RunspaceInvoke();
                    invoker.Invoke("Set-ExecutionPolicy Unrestricted");
                    invoker.Dispose();
                    //公司ID及地區
                    string ip = "";
                    string netmask = "";
                    string d_gateway = "";
                    string d_dns = "";
                    string o_dns = "";
                    string rdp_port = "";
                    string company_id = "";
                    string area = "";
                    List<string> macaddress = getLocalMac();  //temp remark
                    List<JToken> IP_detail = new List<JToken>();
                    string upwd = "!QAZ2wsx"; // pwdGenerator(12, 1);
                    string lines2 = "net user User " + upwd + "";
                    string domain_ip = "";
                    string domain_pwd = "";
                    string domain_account = "";
                    string domain_name = "";
                    string member_id = "";

                    Runspace runspace4 = RunspaceFactory.CreateRunspace();
                    runspace4.Open();
                    Pipeline cpassword = runspace4.CreatePipeline();
                    cpassword.Commands.AddScript(lines2);
                    cpassword.Commands.Add("Out-String");
                    var cpassword2 = cpassword.Invoke();
                    string cpassword2output = cpassword2[0].ToString();
                    cpassword.Dispose();
                    runspace4.Dispose();

                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " cpassword2 : " + cpassword2output + Environment.NewLine);

                    string info_result = ws.Get_Order_Info(vmname);

                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Get_Order_Info : " + info_result + Environment.NewLine);

                    JToken info = JObject.Parse(info_result);
                    company_id = info["company_id"].ToString();
                    area = info["area"].ToString();
                    member_id = info["member_id"].ToString();

                    //company_id = info_result[3];
                    //area = info_result[7];
                    //member_id = info_result[11];

                    ///////////////////////////////  設定 IP   START

                    string Jedi_sql;
                    string temp_vlan = "";
                    int chech_adapter_num = 0;

                    //                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    //                    DBManager dbManager = new DBManager(DataProvider.SqlServer);
                    //                    dbManager.ConnectionString = ConfigurationManager.AppSettings["SSM"].ToString();
                    //                    dbManager.Open();
                    //                    dbManager.CreateParameters(1);
                    //                    dbManager.AddParameters(0, "@order_id", vmname);
                    //                    Jedi_sql = @"SELECT COUNT(order_id)
                    //                                from order_nic_mac_list
                    //                                where order_id=@order_id";
                    //                    chech_adapter_num = System.Convert.ToInt32(dbManager.ExecuteScalar(CommandType.Text, Jedi_sql));
                    //                    if (macaddress.Count != chech_adapter_num)  //檢查網卡數量 是否等於 DB數量
                    //                    {
                    //                        ws.Inset_VM_config_log(vmname, "SET IP", "ERROR", "Network adapter have some problams.");
                    //                        //VM_config_log(vmname, "SET IP", "ERROR", "Network adapter have some problams.");
                    //                        System.IO.File.WriteAllText(@"C:\AutoProvision\logs.txt", "adapter number != order adapter number");
                    //                        return;
                    //                    }
                    try
                    {
                        //get all network configuration
                        string[] dns_t;
                        int ip_result = 0;
                        for (int i = 0; i < macaddress.Count; i++) // get vlanID
                        {

                            //                            dbManager.CreateParameters(2);
                            //                            dbManager.AddParameters(0, "@order_id", vmname);
                            //                            dbManager.AddParameters(1, "@nic_mac", macaddress[i]);
                            //                            Jedi_sql = @"select vlan_id
                            //                                from order_nic_mac_list
                            //                                where order_id=@order_id and nic_mac=@nic_mac";
                            //                            temp_vlan = System.Convert.ToString(dbManager.ExecuteScalar(CommandType.Text, Jedi_sql));
                            temp_vlan = ws.Get_VLAN_ID_Info(vmname, macaddress[i]);

                            System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Get_VLAN_ID_Info : " + temp_vlan + Environment.NewLine);

                            JToken temp_parser = JObject.Parse(temp_vlan);

                            string Jedi_IP = ws.Assign_Network_Configuration(macaddress[i], group_id.Replace("\r\n", ""), vmname, area, company_id, temp_parser["vlan_id"].ToString());
                            System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Assign_Network_Configuration: " + Jedi_IP + Environment.NewLine);

                            if (Jedi_IP == "no free ip")
                            {
                                ws.Insert_VM_config_log(vmname, "Static_ip", "error", Jedi_IP);
                                System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Insert_VM_config_log"+ Environment.NewLine);
                                //VM_config_log(vmname, "Static_ip", "error", Jedi_IP);
                                return;
                            }
                            JToken token;
                            token = JObject.Parse(Jedi_IP.Remove(Jedi_IP.Length - 1).Remove(0, 1).Replace("\\", "\\\\"));
                            IP_detail.Add(token);
                        }
                        //for (int i = 0; i < macaddress.Count; i++) //偵測分配IP錯誤 如有錯誤 將以分配的IP ORDER初始化
                        //{
                        //    if (((Dictionary<string, string>)h[i])["ip"] == "" || h.Count != macaddress.Count)
                        //    {
                        //        System.IO.File.WriteAllText(@"C:\AutoProvision\IP_logs.txt", "static_IP web_service have some problam.");
                        //        ws.Inset_Percent(vmname, "69", "static_IP web_service have some problam.");
                        //    }
                        //    //clean_IP(vmname);  暫時關閉
                        //    //return;
                        //}
                        for (int i = 0; i < macaddress.Count; i++)
                        {
                            //if (i > 1) { break; } // debug用
                            List<string> dns = new List<string>();
                            dns.Add(IP_detail[i].SelectToken("d_dns").ToString());
                            dns.Add(IP_detail[i].SelectToken("o_dns").ToString());
                            dns_t = dns.ToArray();

                            ip_result = ip_result + SetIP(IP_detail[i].SelectToken("used_mac").ToString(), IP_detail[i].SelectToken("ip").ToString(), IP_detail[i].SelectToken("netmask").ToString(), IP_detail[i].SelectToken("d_gateway").ToString(), dns_t);
                        }
                        if (ip_result == 0) //如果更改都成功,更改DB的IP使用狀態
                        {
                            System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Ip set is ok! " + Environment.NewLine);

                            string change_nim = ws.Change_IP_Status(vmname);
                        }
                        else
                        {
                            System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Ip set is ERROR " + Environment.NewLine);

                            ws.Insert_VM_config_log(vmname, "SET IP", "ERROR", "Network configuration fail.");
                            //VM_config_log(vmname, "SET IP", "ERROR", "Network configuration fail.");

                            return;
                        }
                        /////////////////////////////////////設定 IP結束
                    }
                    catch (Exception ex)
                    {
                        System.IO.File.AppendAllText(@"C:\AutoProvision\error.txt", " Ip set is ERROR " +ex.Message+ Environment.NewLine);
                    }
                    finally
                    {
                        //dbManager.Dispose();
                    }
                    ////////////////////////////////
                    ws.Inset_Percent(vmname, "70", "");
                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Inset_Percent" + Environment.NewLine);
                    //                    string sql = @"select vlan_id
                    //                                from user_vm_order
                    //                                where order_id=@order_id";
                    //                    DataSet ds = dbManager.ExecuteDataSet(CommandType.Text, sql);
                    //                    int nic_num = ds.Tables[0].Rows[0]["vlan_id"].ToString().Split(',').Count();
                    //for( int i = 0 ; i < nic_num ; i++ )
                    //ws.Set_VM_pwd(vmname, upwd);
                    string Assign_Network_Configuration = ws.Assign_Network_Configuration(macaddress[0], group_id, vmname, area, company_id, temp_vlan);
                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Assign_Network_Configuration" + Assign_Network_Configuration + Environment.NewLine);
                    string[] static_ip_result = Assign_Network_Configuration.Split('"');
                    //ip = static_ip_result[5];
                    //netmask = static_ip_result[9];
                    //d_gateway = static_ip_result[13];
                    //d_dns = static_ip_result[17];
                    //o_dns = static_ip_result[21];
                    rdp_port = static_ip_result[25];
                    domain_name = static_ip_result[29];
                    domain_ip = static_ip_result[33];
                    domain_account = static_ip_result[37];
                    domain_pwd = CryptoAES.decrypt(static_ip_result[41], "GccA@stanchengGg");
                    if (rdp_port != "3389")
                    {
                        System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Ready Change RDP Port" + Environment.NewLine);
                        string rdp_port_ps1 = "Set-ItemProperty -path 'HKLM:\\System\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp' -name PortNumber -value " + rdp_port;
                        Runspace runspace_rdp_port = RunspaceFactory.CreateRunspace();
                        runspace_rdp_port.Open();
                        Pipeline rdp_port_pipe = runspace_rdp_port.CreatePipeline();
                        rdp_port_pipe.Commands.AddScript(rdp_port_ps1);
                        rdp_port_pipe.Commands.Add("Out-String");
                        var rdp_port_pipe2 = rdp_port_pipe.Invoke();
                        string rdp_port_out = rdp_port_pipe2[0].ToString();
                        runspace_rdp_port.Dispose();
                        System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " RDP PORD have change! " + Environment.NewLine);

                    }
                    ws.Inset_Percent(vmname, "80", "");
                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Inset_Percent" + Environment.NewLine);
                    System.Threading.Thread.Sleep(1000);
                    //IP-Setting & Join Domain
                    //@"$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration | where{$_.IPEnabled -eq ""TRUE""}" + "\n" +
                    //            "$NIC=\"Lan\"\n" +
                    //            "Foreach($NIC in $NICs) {\n" +
                    //            "$NIC.EnableStatic(\"" + ip + "\", \"" + netmask + "\")\n" +
                    //            "$NIC.SetGateways(\"" + d_gateway + "\")\n" +
                    //            "$DNSServers = \"" + d_dns + "\",\"" + o_dns + "\"\n" +
                    //            "$NIC.SetDNSServerSearchOrder($DNSServers)\n" +
                    //            "$NIC.SetDynamicDNSRegistration(\"TRUE\")\n" +
                    //            "} \n" +
                    string ip_set =
                                "Start-Sleep -s 20 \n" +
                                "$domain = " + "\"" + domain_name + "\"" + "\n" +
                                "$password = "******"\"" + domain_pwd + "\"" + " | ConvertTo-SecureString -asPlainText -Force\n" +
                                "$username = "******"\"" + domain_account + "\"" + "\n" +
                                "$credential = New-Object System.Management.Automation.PSCredential($username,$password)\n" +
                                "Add-Computer -DomainName $domain -Cred $credential\n" +
                                "Start-Sleep -s 20\n" +
                                "restart-computer -force\n";
                    System.IO.File.WriteAllText(@"C:\AutoProvision\set_ip.ps1", ip_set);
                    System.IO.File.WriteAllText(@"C:\AutoProvision\check_ip_reboot.txt", domain_name + " " + domain_pwd + " " + domain_account + " " + ip + " " + member_id + " " + vmname);
                    ws.Inset_Percent(vmname, "85", "");

                    IntPtr userTokenHandle = IntPtr.Zero;
                    ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);
                    ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION();
                    ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO();
                    startInfo.cb = (uint)Marshal.SizeOf(startInfo);
                    string RebootPath = @"C:\AutoProvision\set_ip.exe";
                    ApiDefinitions.CreateProcessAsUser(userTokenHandle,
                        RebootPath,
                        "",
                        IntPtr.Zero,
                        IntPtr.Zero,
                        false,
                        0,
                        IntPtr.Zero,
                        null,
                        ref startInfo,
                        out procInfo);
                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Add to domain! " + Environment.NewLine);

                    }
                    catch (Exception ex)
                    {
                    //VM_config_log(vmname, "", "ERROR", "Network adapter have some problams.");
                    System.IO.File.AppendAllText(@"C:\AutoProvision\error.txt", ex.Message);
                    }
                    finally
                    {
                    ws.Dispose();
                    }
                    }
                    if (step1_output == "True" && check_ip_output == "True")
                    {
                    //AutoProvision_WS.AutoProvision_WS ws = new AutoProvision_WS.AutoProvision_WS();
                    try
                    {
                    System.IO.StreamReader check_ip_reboot_f = new System.IO.StreamReader(@"c:\AutoProvision\check_ip_reboot.txt");
                    string[] domain_name0 = check_ip_reboot_f.ReadToEnd().Split(' ');
                    string domain_name = domain_name0[0];
                    string ip = domain_name0[3];
                    string member_id = domain_name + "/" + domain_name0[4];
                    vmname = domain_name0[5];
                    check_ip_reboot_f.Dispose();
                    string join_account = "$user=[ADSI]\"WinNT://" + member_id + "\"\n" +
                                         "$group=[ADSI]\"WinNT://./Remote Desktop Users\"\n" +
                                         "$group.Psbase.Invoke(\"Add\",$user.Psbase.path)";
                    //Runspace Runspace_join_account = RunspaceFactory.CreateRunspace();
                    //Runspace_join_account.Open();
                    //Pipeline join_account_pipe = Runspace_join_account.CreatePipeline();
                    //join_account_pipe.Commands.AddScript(join_account);
                    //join_account_pipe.Invoke();
                    //Runspace_join_account.Dispose();
                    Do_Power_Shell(join_account);
                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " join account  " + member_id + Environment.NewLine);

                    ws.Inset_Percent(vmname, "90", "");

                    string remove_DomainAdminsAccount = "$user=[ADSI]\"WinNT://Domain Admins" + "\"\n" +
                                                        "$group=[ADSI]\"WinNT://./Administrators\"\n" +
                                                        "$group.Psbase.Invoke(\"Remove\",$user.Psbase.path)";
                    Do_Power_Shell(remove_DomainAdminsAccount);

                    string remove_LocalUserAccount = "$ComputerName = $env:COMPUTERNAME" + "\n" +
                                                     "[ADSI]$server=\"WinNT://$ComputerName\"" + "\n" +
                                                     "$removeName=\"user\"" + "\n" +
                                                     "$server.Delete(\"user\",$removeName)";
                    Do_Power_Shell(remove_LocalUserAccount);

                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " remove account !" + Environment.NewLine);

                    //Runspace Runspace_remove_account = RunspaceFactory.CreateRunspace();
                    //Runspace_remove_account.Open();
                    //Pipeline remove_account_pipe = Runspace_remove_account.CreatePipeline();
                    //remove_account_pipe.Commands.AddScript(remove_DomainAdminsAccount);
                    //remove_account_pipe.Invoke();
                    ////remove_account_pipe.Commands.AddScript(remove_LocalUserAccount);
                    ////remove_account_pipe.Invoke();
                    //Runspace_remove_account.Dispose();

                    ws.Inset_Percent(vmname, "95", "");

                    string app_id = @"Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -like ""VMconfig""}|Format-list IdentifyingNumber >c:\\AutoProvision\\app_guid.txt";
                    Runspace Runspace_app_guid = RunspaceFactory.CreateRunspace();
                    Runspace_app_guid.Open();
                    Pipeline app_guid_pipe = Runspace_app_guid.CreatePipeline();
                    app_guid_pipe.Commands.AddScript(app_id);
                    var app_guid_pipe2 = app_guid_pipe.Invoke();
                    Runspace_app_guid.Dispose();
                    System.IO.StreamReader app_guid_pipe_out = new System.IO.StreamReader(@"c:\AutoProvision\app_guid.txt");
                    string[] app = app_guid_pipe_out.ReadToEnd().Split(':');
                    string[] app2 = app[1].Split('\r');
                    string[] app3 = app2[0].Split(' ');
                    string app_guid = app3[1];
                    app_guid_pipe_out.Dispose();

                    string remove_it = @"Remove-Item c:\\AutoProvision -Recurse";
                    Runspace Runspace_remove = RunspaceFactory.CreateRunspace();
                    Runspace_remove.Open();
                    Pipeline remove_it_pipe = Runspace_remove.CreatePipeline();
                    remove_it_pipe.Commands.AddScript(remove_it);
                    var remove_it_pipe2 = remove_it_pipe.Invoke();
                    Runspace_remove.Dispose();

                    ws.Inset_Percent(vmname, "100", "");

                    ws.Change_Order_Status(vmname, "5", false);
                    string del_item_sc = @"MsiExec.exe /norestart /q/x""" + app_guid + "\" REMOVE=ALL";
                    Runspace Runspace_del_item = RunspaceFactory.CreateRunspace();
                    Runspace_del_item.Open();
                    Pipeline del_item_pipe = Runspace_del_item.CreatePipeline();
                    del_item_pipe.Commands.AddScript(del_item_sc);
                    var del_item_pipe2 = del_item_pipe.Invoke();
                    Runspace_del_item.Dispose();
                    }
                    catch (Exception ex)
                    {
                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", ex.ToString());
                    }
                    finally
                    {
                    ws.Dispose();
                    }
                    }
                }