Exemplo n.º 1
0
    //function to run Powershell commands
    public static void RunPowerShell(string psScript, string psParameters)
    {

      try
      {
        var runspaceConfiguration = RunspaceConfiguration.Create();
        var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();
        var pipeline = runspace.CreatePipeline();
        var myCommand = new Command(psScript);
        pipeline.Commands.Add(myCommand);
        if (!string.IsNullOrEmpty(psParameters))
        {
          var aryParameters = psParameters.Split(' ');
          for (var i = 0; i < aryParameters.Count(); i++)
          {
            myCommand.Parameters.Add(aryParameters[i].ToString(CultureInfo.InvariantCulture), aryParameters[i + 1].ToString(CultureInfo.InvariantCulture));
            i++;
          }
        }

        var scriptInvoker = new RunspaceInvoke(runspace);

        // Execute PowerShell script
        Collection<PSObject> results = pipeline.Invoke();
        runspace.Close();
        return;

      }
      catch (Exception e)
      {
        Fido_EventHandler.SendEmail("Fido Error", "Fido Failed: {0} Exception caught running powershell:" + e);
      }
    }
Exemplo n.º 2
0
        protected void BtnExecuteScript_Click(object sender, EventArgs e)
        {
            BtnExecuteScript.Enabled = false;

            Stream str = fileUpload.FileContent;
            StreamReader sr = new StreamReader(str);
            string script = sr.ReadToEnd();

            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            scriptInvoker.Invoke("Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned");

            Pipeline pipe = runspace.CreatePipeline();
            runspace.SessionStateProxy.SetVariable("firstValue", firstValue.Text);
            runspace.SessionStateProxy.SetVariable("secondValue", secondValue.Text);

            pipe.Commands.AddScript(script);
            pipe.Commands.Add("Out-String");
            Collection<PSObject> results = pipe.Invoke();

            runspace.Close();

            // convert the script result into a single string
            StringBuilder stringBuilder = new StringBuilder();

            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }

            String output = stringBuilder.ToString();
            TxtOutput.Text = output;
        }
Exemplo n.º 3
0
        /// <summary>
        ///     Executes a powershell script
        /// </summary>
        /// <param name="folder">Folder where to execute the script</param>
        /// <param name="file">Script to execute</param>
        /// <param name="configuration">Configuration used</param>
        /// <param name="log">Logger to use</param>
        /// <param name="parameters">Parameters for the script</param>
        public static void Execute(string folder, string file, string configuration, ILogger log, Dictionary<string, string> parameters)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(new Host(), runspaceConfiguration);
            runspace.Open();
            runspace.SessionStateProxy.Path.SetLocation(folder);

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
            Pipeline pipeline = runspace.CreatePipeline();

            Command myCommand = new Command(Path.Combine(folder, file));

            foreach (var param in parameters.Keys)
            {
                myCommand.Parameters.Add(new CommandParameter("-" + param, parameters[param]));
            }

            myCommand.Parameters.Add(new CommandParameter("-Verb", "RunAs"));
            pipeline.Commands.Add(myCommand);

            Collection<PSObject> results = new Collection<PSObject>();
            try
            {
                results = pipeline.Invoke();
            }
            catch (RuntimeException e)
            {
                log.Log(String.Join("\r\n", results.Select(x => x.ToString())) + "\r\n" + e.Message.ToString(), true);
                return;
            }

            log.Log(String.Join("\r\n", results.Select(x => x.ToString())), pipeline.Error.Count > 0);
        }
Exemplo n.º 4
0
        protected override void Execute(CodeActivityContext context)
        {
            string scriptPath = ScriptPath.Get(context);
            string scriptContents = null;

            if (!(Path.IsPathRooted(scriptPath)))
                scriptPath = Path.Combine(Directory.GetCurrentDirectory(), scriptPath);

            if (File.Exists(scriptPath))
                scriptContents = File.ReadAllText(scriptPath);
            else
                throw new FileNotFoundException(String.Format("Powershell script file {0} does not exist.", scriptPath));

            Runspace runSpace = RunspaceFactory.CreateRunspace();
            runSpace.Open();

            RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runSpace);

            Pipeline pipeLine = runSpace.CreatePipeline();
            pipeLine.Commands.AddScript(scriptContents);
            pipeLine.Commands.Add("Out-String");

            Collection<PSObject> returnObjects = pipeLine.Invoke();
            runSpace.Close();
        }
Exemplo n.º 5
0
    public static Collection<PSObject> run(string scriptFile, List<string> parameters)
    {
        string paramName;
        string paramValue;
        RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();

        RunspaceInvoke scriptIvoker = new RunspaceInvoke(runspace);
        Pipeline pipeline = runspace.CreatePipeline();

        Command cmd = new Command(scriptFile);
        //CommandParameter param = new CommandParameter("-ComputerName", "Powerhouse");
        //cmd.Parameters.Add(param);
        foreach (string scriptParameter in parameters)
        {
            paramName = scriptParameter.Split(' ')[0];
            paramValue = scriptParameter.Split(' ')[1];
            cmd.Parameters.Add(paramName, paramValue);
        }

        pipeline.Commands.Add(cmd);

        return pipeline.Invoke();
    }
Exemplo n.º 6
0
        public static IEnumerable<string> ExecutePowershellCommand(this Robot robot, string command)
        {
            var host = new MMBotHost(robot);
            using (var runspace = RunspaceFactory.CreateRunspace(host))
            {
                runspace.Open();
                using (var invoker = new RunspaceInvoke(runspace))
                {
                    Collection<PSObject> psObjects = new Collection<PSObject>();
                    try
                    {
                        IList errors;
                        psObjects = invoker.Invoke(command, null, out errors);
                        if (errors.Count > 0)
                        {
                            string errorString = string.Empty;
                            foreach (var error in errors)
                                errorString += error.ToString();

                            psObjects.Add(new PSObject(errorString));
                        }

                    }
                    catch (Exception ex)
                    {
                        psObjects.Add(new PSObject(ex.Message));
                    }

                    foreach (var psObject in psObjects)
                    {
                        yield return psObject.ConvertToString();
                    }
                }
            }
        }
Exemplo n.º 7
0
        public ProjectInstaller()
        {
            //System.Diagnostics.Debugger.Launch();

            var assemblyFileBaseName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
            var assemblyFileDirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var powershellScriptFullPath = assemblyFileDirName + "\\" + assemblyFileBaseName + ".ps1";
            Console.WriteLine(powershellScriptFullPath);

            this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
            this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();

            invoker = new RunspaceInvoke();
            //ポリシー設定(結果は破棄)
            invoker.Invoke(policyScript);
            //スクリプト本体をロード
            Console.WriteLine(String.Format(loadScript, powershellScriptFullPath));
            var result = invoker.Invoke(String.Format(loadScript, powershellScriptFullPath));

            result = invoker.Invoke(serviceScript);
            this.serviceProcessInstaller1 = (ServiceProcessInstaller)result[0].ImmediateBaseObject;
            this.serviceInstaller1 = (ServiceInstaller)result[1].ImmediateBaseObject;

            this.Installers.AddRange(new System.Configuration.Install.Installer[] {
            this.serviceProcessInstaller1,
            this.serviceInstaller1});
        }
 public PowerShellSession()
 {
     this.SessionState = SMA.Runspaces.InitialSessionState.CreateDefault();
     this.RunSpace     = SMA.Runspaces.RunspaceFactory.CreateRunspace(this.SessionState);
     this.RunSpace.Open();
     this.PowerShell          = SMA.PowerShell.Create();
     this.PowerShell.Runspace = this.RunSpace;
     this.Invoker             = new SMA.RunspaceInvoke(this.RunSpace);
 }
        protected void ExecuteCode_Click(object sender, EventArgs e)
        {
            // Clean the Result TextBox
            ResultBox.Text = string.Empty;
            ResultBox.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");

            string str = "";

            // Powershell
            Runspace runSpace = RunspaceFactory.CreateRunspace();
            runSpace.Open();
            Pipeline pipeline = runSpace.CreatePipeline();

            Command invokeScript = new Command("Invoke-Command");
            RunspaceInvoke invoke = new RunspaceInvoke();

            // invoke-command -computername compName -scriptblock { get-process }

            ScriptBlock sb = invoke.Invoke("{"+ PowerShellCodeBox.Text +"}")[0].BaseObject as ScriptBlock;
            invokeScript.Parameters.Add("scriptBlock", sb);
            invokeScript.Parameters.Add("computername", TextBoxServer.Text);

            pipeline.Commands.Add(invokeScript);
            Collection<PSObject> output = pipeline.Invoke();
            foreach (PSObject psObject in output)
            {

                str = str + psObject;
            }
            
            if (str == ""){
                str = "An error may have occured, check to make sure powershell remoting is turned on the remote server";
                str = str + "\r\n \r\n ";
                str = str + "\r\n To get powershell to work with an asp.net web page you must enable the following: ";
                str = str + "\r\n \r\n ";
                str = str + "\r\n 1. Run this > Enable-PSRemoting –force ";
                str = str + "\r\n 2. Add you remote computer to the trusted list >  winrm s winrm/config/client '@{TrustedHosts=``compName``}'";
                str = str + "\r\n 3. *note for windows server 2008 you just need to enable powershell remoting http://searchsystemschannel.techtarget.com/feature/PowerShell-remoting-in-Windows-Server-2008-R2 ";
                str = str + "\r\n 4. **You must have admin access on the remote server you are trying to execute the script on.**";
                str = str + "\r\n 5. ***This does not work on windows server 2003, unless you specifically installed powershell on it***"; 



                ResultBox.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
            }

            ResultBox.Text = str;

        }
Exemplo n.º 10
0
        public PowerShellSession(System.Reflection.Assembly module)
        {
            this.SessionState = SMA.Runspaces.InitialSessionState.CreateDefault();

            // Find the path to the assembly
            var modules = new[] { module.Location };

            this.SessionState.ImportPSModule(modules);

            this.RunSpace = SMA.Runspaces.RunspaceFactory.CreateRunspace(this.SessionState);
            this.RunSpace.Open();
            this.PowerShell          = SMA.PowerShell.Create();
            this.PowerShell.Runspace = this.RunSpace;
            this.Invoker             = new SMA.RunspaceInvoke(this.RunSpace);
        }
Exemplo n.º 11
0
        public void InvokeScriptBlock()
        {
            // Arrange.
            var runspace = new RunspaceInvoke();
            var scriptBlock = (ScriptBlock)
                runspace.Invoke("{$global:sb1=$true;123}")[0].BaseObject;
            var cmdlet = new InvokeTestCmdlet();

            // Act.
            var res = cmdlet.InvokeScriptBlock(scriptBlock);

            // Assert.
            Assert.AreEqual(123, (int)res[0].BaseObject);
            Assert.IsTrue((bool)runspace.Invoke("$sb1")[0].BaseObject);
        }
        private async Task<PSDataCollection<ErrorRecord>> InvokePowerShellScript(Dictionary<string, string> envVars, TraceWriter traceWriter)
        {
            InitialSessionState iss = InitialSessionState.CreateDefault();
            PSDataCollection<ErrorRecord> errors = new PSDataCollection<ErrorRecord>();

            using (Runspace runspace = RunspaceFactory.CreateRunspace(iss))
            {
                runspace.Open();
                SetRunspaceEnvironmentVariables(runspace, envVars);
                RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
                runSpaceInvoker.Invoke("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted");

                using (
                    System.Management.Automation.PowerShell powerShellInstance =
                        System.Management.Automation.PowerShell.Create())
                {
                    powerShellInstance.Runspace = runspace;
                    _moduleFiles = GetModuleFilePaths(_host.ScriptConfig.RootScriptPath, _functionName);
                    if (_moduleFiles.Any())
                    {
                        powerShellInstance.AddCommand("Import-Module").AddArgument(_moduleFiles);
                        LogLoadedModules();
                    }

                    _script = GetScript(_scriptFilePath);
                    powerShellInstance.AddScript(_script, true);

                    PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
                    outputCollection.DataAdded += (sender, e) => OutputCollectionDataAdded(sender, e, traceWriter);

                    powerShellInstance.Streams.Error.DataAdded += (sender, e) => ErrorDataAdded(sender, e, traceWriter);

                    IAsyncResult result = powerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
                    await Task.Factory.FromAsync<PSDataCollection<PSObject>>(result, powerShellInstance.EndInvoke);

                    foreach (ErrorRecord errorRecord in powerShellInstance.Streams.Error)
                    {
                        errors.Add(errorRecord);
                    }
                }

                runspace.Close();
            }

            return errors;
        }
Exemplo n.º 13
0
        public Service1()
        {
            var assemblyFileBaseName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
            var assemblyFileDirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var powershellScriptFullPath = assemblyFileDirName + "\\" + assemblyFileBaseName + ".ps1";
            Console.WriteLine(powershellScriptFullPath);

            invoker = new RunspaceInvoke();

            //ポリシー設定(結果は破棄)
            invoker.Invoke(policyScript);
            //スクリプト本体をロード
            Console.WriteLine(String.Format(loadScript, powershellScriptFullPath));
            invoker.Invoke(String.Format(loadScript, powershellScriptFullPath));

            //InitializeComponent();
            InitilizeFromScript();
        }
Exemplo n.º 14
0
        private static string RunScript(Runspace runspace)
        {
            runspace.Open();
            var pipeline = runspace.CreatePipeline();

            var runspaceInvoke = new RunspaceInvoke(runspace);
            runspaceInvoke.Invoke("Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process -Force");

            pipeline.Commands.AddScript(@"D:\Projekt\EPiServer\SampleCode\CodeSample\ScheduledJobs\SampleScript.ps1");
            pipeline.Commands.Add("Out-String");

            var stringBuilder = new StringBuilder();
            foreach (var psObject in pipeline.Invoke())
            {
                stringBuilder.AppendLine(psObject.ToString());
            }
            return stringBuilder.ToString();
        }
Exemplo n.º 15
0
        public static void ExecutePowershellScript(string scriptPath, string executionPolicy, params string[] parameters)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();

            using (RunspaceInvoke invoker = new RunspaceInvoke())
            {
                invoker.Invoke(String.Format("Set-ExecutionPolicy {0}", executionPolicy));
                Command myCommand = new Command(scriptPath);
                for(int i=0; i < parameters.Length; i++)
                {
                    myCommand.Parameters.Add(new CommandParameter(null, parameters[i]));
                }

                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.Add(myCommand);
                var results = pipeline.Invoke();
            }
        }
Exemplo n.º 16
0
        public void CleanUp()
        {
            // Make sure we cleanup everything
            if (this.PowerShell != null)
            {
                this.PowerShell.Dispose();
                this.PowerShell = null;
            }
            if (this.Invoker != null)
            {
                this.Invoker.Dispose();
                this.Invoker = null;
            }
            if (this.RunSpace != null)
            {
                this.RunSpace.Close();
                this.RunSpace = null;
            }

            this.SessionState = null;
        }
        public void CleanUp()
        {
            // Make sure we cleanup everything
            if (this._powershell != null)
            {
                this._powershell.Dispose();
                this._powershell = null;
            }
            if (this._invoker != null)
            {
                this._invoker.Dispose();
                this._invoker = null;
            }
            if (this._runspace != null)
            {
                this._runspace.Close();
                this._runspace = null;
            }

            this._sessionstate = null;
        }
Exemplo n.º 18
0
        public static void CreateFirewallRules()
        {
            // create Powershell runspace
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();

            RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
            runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

            // create a pipeline and feed it the script text
            Pipeline pipeline = runspace.CreatePipeline();
            Command command = new Command(_scriptPath);
            //foreach (var file in filesToMerge)
            //{
            //    command.Parameters.Add(null, file);
            //}
            //command.Parameters.Add(null, outputFilename);
            pipeline.Commands.Add(command);

            pipeline.Invoke();
            runspace.Close();
        }
Exemplo n.º 19
0
        public Collection<PSObject> RunPsScript(string psScriptPath)
        {
            string psScript = string.Empty;
            if (File.Exists(psScriptPath))
                psScript = File.ReadAllText(psScriptPath);
            else
                throw new FileNotFoundException("Wrong path for the script file");

            Runspace runSpace = RunspaceFactory.CreateRunspace();
            runSpace.Open();

            RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runSpace);
            runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

            Pipeline pipeLine = runSpace.CreatePipeline();
            pipeLine.Commands.AddScript(psScript);
            //pipeLine.Commands.Add("Out-String");

            Collection<PSObject> returnObjects = pipeLine.Invoke();

            if (pipeLine.Error.Count > 0)
            {
                var error = pipeLine.Error.Read() as Collection<ErrorRecord>;
                if (error != null)
                {
                    foreach (ErrorRecord er in error)
                    {
                        Console.WriteLine("[PowerShell]: Error in cmdlet: " + er.Exception.Message);
                    }
                }
            }



            runSpace.Close();

            return returnObjects;
        }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            var runspaceConfiguration = RunspaceConfiguration.Create();
            var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();
            var scriptInvoker = new RunspaceInvoke(runspace);

            var pipeline = runspace.CreatePipeline();

             string path = Directory.GetCurrentDirectory();
            var scriptFilePath = Path.Combine(path, "FindInFiles.ps1");

            if (!File.Exists(scriptFilePath))
            {
                Console.WriteLine("File '{0}' does not exit", scriptFilePath);
                return;
            }

            pipeline.Commands.Add(scriptFilePath);

            // Execute PowerShell script
            pipeline.Invoke();
        }
Exemplo n.º 21
0
        //Based on Jared Atkinson's And Justin Warner's Work
        public static string RunPSCommand(string cmd)
        {
            //Init stuff
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            Pipeline pipeline = runspace.CreatePipeline();

            //Add commands
            pipeline.Commands.AddScript(cmd);

            //Prep PS for string output and invoke
            pipeline.Commands.Add("Out-String");
            Collection<PSObject> results = pipeline.Invoke();
            runspace.Close();

            //Convert records to strings
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.Append(obj);
            }
            return stringBuilder.ToString().Trim();
        }
Exemplo n.º 22
0
        private static string RunPowerShellScript(string command, Dictionary<string,string> parameters)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

            Pipeline pipeline = runspace.CreatePipeline();

            //Here's how you add a new script with arguments
            Command myCommand = new Command(command);

            foreach (KeyValuePair<string, string> parameter in parameters)
            {
                CommandParameter param = new CommandParameter(parameter.Key, parameter.Value);
                myCommand.Parameters.Add(param);
            }

            pipeline.Commands.Add(myCommand);

            // Execute PowerShell script
            var results = pipeline.Invoke();

            // close the runspace

            runspace.Close();

            // convert the script result into a single string

            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }

            string returnText =  stringBuilder.ToString();
            return returnText;
        }
Exemplo n.º 23
0
        internal void RunPowerShellScript(string scriptPath, Dictionary<string, string> arguments)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();
            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            Pipeline pipeline = runspace.CreatePipeline();
            //Here's how you add a new script with arguments            
            Command myCommand = new Command(scriptPath);
            //foreach (var argument in arguments)
            //{
            //    myCommand.Parameters.Add(new CommandParameter(argument.Key, argument.Value));
            //}
            pipeline.Commands.Add(myCommand);
            var results = pipeline.Invoke();
            foreach (var psObject in results)
            {

            }
        }
Exemplo n.º 24
0
        public void Execute()
        {
            RebootNeeded = false;
            var resultPath = this.path + ".result";
            Runspace runSpace = null;
            try
            {
                var plan = JsonConvert.DeserializeObject<ExecutionPlan>(File.ReadAllText(this.path));
                List<ExecutionResult> currentResults = null;
                try
                {
                    currentResults = File.Exists(resultPath) ?
                        JsonConvert.DeserializeObject<List<ExecutionResult>>(File.ReadAllText(resultPath)) :
                        new List<ExecutionResult>();
                }
                catch(Exception exception)
                {
                    Log.WarnException("Cannot deserialize previous execution result", exception);
                    currentResults = new List<ExecutionResult>();
                }

                runSpace = RunspaceFactory.CreateRunspace();
                runSpace.Open();

                var runSpaceInvoker = new RunspaceInvoke(runSpace);
                runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
                if (plan.Scripts != null)
                {
                    var index = 0;
                    foreach (var script in plan.Scripts)
                    {
                        runSpaceInvoker.Invoke(Encoding.UTF8.GetString(Convert.FromBase64String(script)));
                        Log.Debug("Loaded script #{0}", ++index);
                    }
                }

                while (plan.Commands != null && plan.Commands.Any())
                {
                    var command = plan.Commands.First();
                    Log.Debug("Preparing to execute command {0}", command.Name);

                    var pipeline = runSpace.CreatePipeline();
                    var psCommand = new Command(command.Name);
                    if (command.Arguments != null)
                    {
                        foreach (var kvp in command.Arguments)
                        {
                            var value = ConvertArgument(kvp.Value);
                            psCommand.Parameters.Add(kvp.Key, value);
                        }
                    }

                    Log.Info("Executing {0} {1}", command.Name, string.Join(" ",
                        (command.Arguments ?? new Dictionary<string, object>()).Select(
                            t => string.Format("{0}={1}", t.Key, t.Value == null ? "null" : t.Value.ToString()))));

                    pipeline.Commands.Add(psCommand);

                    try
                    {
                        var result = pipeline.Invoke();
                        Log.Debug("Command {0} executed", command.Name);
                        if (result != null)
                        {
                            currentResults.Add(new ExecutionResult {
                                IsException = false,
                                Result = result.Select(SerializePsObject).Where(obj => obj != null).ToList()
                            });
                        }
                    }
                    catch (Exception exception)
                    {
                        object additionInfo = null;
                        if (exception is ActionPreferenceStopException)
                        {
                            var apse = exception as ActionPreferenceStopException;
                            if (apse.ErrorRecord != null)
                            {
                                additionInfo = new {
                                    ScriptStackTrace = apse.ErrorRecord.ScriptStackTrace,
                                    PositionMessage = apse.ErrorRecord.InvocationInfo.PositionMessage
                                };
                                exception = apse.ErrorRecord.Exception;
                            }
                        }

                        Log.WarnException("Exception while executing command " + command.Name, exception);
                        currentResults.Add(new ExecutionResult
                        {
                            IsException = true,
                            Result = new[] {
                                exception.GetType().FullName, exception.Message, command.Name, additionInfo
                            }
                        });
                        break;
                    }
                    finally
                    {
                        plan.Commands.RemoveFirst();
                        File.WriteAllText(path, JsonConvert.SerializeObject(plan));
                        File.WriteAllText(resultPath, JsonConvert.SerializeObject(currentResults));
                    }
                }
                runSpace.Close();
                var executionResult = JsonConvert.SerializeObject(new ExecutionResult {
                    IsException = false,
                    Result = currentResults
                }, Formatting.Indented);

                if (plan.RebootOnCompletion > 0)
                {
                    if (plan.RebootOnCompletion == 1)
                    {
                        RebootNeeded = !currentResults.Any(t => t.IsException);
                    }
                    else
                    {
                        RebootNeeded = true;
                    }
                }
                File.WriteAllText(resultPath, executionResult);
            }
            catch (Exception exception)
            {
                Log.WarnException("Exception while processing execution plan", exception);
                File.WriteAllText(resultPath, JsonConvert.SerializeObject(new ExecutionResult {
                    IsException = true,
                    Result = exception.Message
                }, Formatting.Indented));
            }
            finally
            {
                if (runSpace != null)
                {
                    try
                    {
                        runSpace.Close();
                    }
                    catch
                    {}
                }
                Log.Debug("Finished processing of execution plan");
            }
        }
Exemplo n.º 25
0
        static void de_bug()
        {
            DBManager dbManager = new DBManager(DataProvider.SqlServer);
            Console.WriteLine("debug Start");
            string AutoProvision_WS_url = Create_VM_Service.Properties.Settings.Default.Create_VM_Service_AutoProvision_WS_AutoProvision_WS;

            string IsDelImg = ConfigurationManager.AppSettings["IsDelImg"].ToString();//是否刪除VM
            string db_server = ConfigurationManager.AppSettings["SSM"].ToString();
            string EmailAccount = ConfigurationManager.AppSettings["EmailAccount"].ToString();
            string EmailPassword = ConfigurationManager.AppSettings["EmailPassword"].ToString();
            string smtphost = ConfigurationManager.AppSettings["smtphost"].ToString();
            dbManager.ConnectionString = ConfigurationManager.AppSettings["SSM"].ToString();
            Create_VM_Service.AutoProvision_WS.AutoProvision_WS ws = new Create_VM_Service.AutoProvision_WS.AutoProvision_WS();
            //CPU_Memory_Usage_API.David_API vm_useage = new CPU_Memory_Usage_API.David_API();
            string ftp = ConfigurationManager.AppSettings["FTP_IP"].Replace("ftp://", "").Trim();
            string ftp_user = ConfigurationManager.AppSettings["ftpUsername"].Trim().ToString();
            string ftp_pwd = ConfigurationManager.AppSettings["ftpPassword"].Trim().ToString();
            string ftp_folder = ConfigurationManager.AppSettings["FTP_IP"] + "/" + ConfigurationManager.AppSettings["agentFtpPath"];
            int Max_Create_VM_Num = Convert.ToInt32(ConfigurationManager.AppSettings["Max_Create_VM_Num"].Trim().ToString());
            string vm_account = ConfigurationManager.AppSettings["vm_account"].Trim().ToString();
            string vm_password = ConfigurationManager.AppSettings["vm_password"].Trim().ToString();

            #region //是否有訂單需要刪除
            try//是否有訂單需要刪除
            {
                Create_VM_Service.VMAPI.GCCA_HypervisorAPI vmapi = new GCCA_HypervisorAPI();
                dbManager.Open();
                string sql = "";
                Int32 nCount = 0;
                sql = @"select TOP 1 a.order_audit,a.order_vm_type,a.order_id,order_area,a.company_id,a.temp_id,b.*,c.*
                        from user_vm_order a
                        left outer join config_vm_host b on a.company_id=b.company_id and a.order_vm_type=b.vmtype left outer join order_audit c on a.order_id=c.order_id
                        where c.vm_del='1' and a.order_audit='6'
                        order by a.order_id";
                DataSet ds = dbManager.ExecuteDataSet(CommandType.Text, sql);
                nCount = ds.Tables[0].Rows.Count;
                System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " 是否有訂單需要刪除 : " + nCount + Environment.NewLine);

                if (nCount > 0)
                {
                    string order_id = ds.Tables[0].Rows[0]["order_id"].ToString();
                    string aa = ws.Change_Order_Status(order_id, "8", false);
                    string vmtype = ds.Tables[0].Rows[0]["order_vm_type"].ToString();
                    if (vmtype == "VMware")
                    {
                        string vcenter_url = ds.Tables[0].Rows[0]["vmware_apiurl"].ToString();
                        string vmware_host_account = ds.Tables[0].Rows[0]["vmware_host_account"].ToString();
                        string vmware_host_pwd = CryptoAES.decrypt(ds.Tables[0].Rows[0]["vmware_host_pwd"].ToString(), "GccA@stanchengGg");
                        string vmware_datacenter_name = ds.Tables[0].Rows[0]["vmware_datacenter_name"].ToString();
                        string vmware_host_name = ds.Tables[0].Rows[0]["vmware_host_name"].ToString();
                        string vmware_datastore_name = ds.Tables[0].Rows[0]["vmware_datastore_name"].ToString();
                        string[] guidf0 = vmapi.init(vcenter_url, vmware_host_account, vmware_host_pwd, vmware_datacenter_name, true).Split(':');
                        string[] guidf1 = guidf0[2].Split('\'');
                        string guid = guidf1[1];

                        string VMWare_Power_off_f = vmapi.powerOffVM(guid, vmware_datacenter_name, vmware_host_name, order_id).Split(':')[1].Split(',')[0];
                        try
                        {
                            if (IsDelImg == "true" && VMWare_Power_off_f == "true")
                            {
                                vmapi.removeVM(guid, vmware_datacenter_name, vmware_host_name, order_id, vmware_datastore_name, true);
                                ws.Change_Order_Status(order_id, "7", false);
                            }
                            else if (IsDelImg == "true" && VMWare_Power_off_f == "false")
                            {
                                ws.Inset_Log(order_id, "Power Off Error");
                            }
                            else if (IsDelImg == "false" && VMWare_Power_off_f == "false")
                            {
                                ws.Inset_Log(order_id, "Power Off Error");
                            }
                            else if (IsDelImg == "false" && VMWare_Power_off_f == "true")
                            {
                                ws.Change_Order_Status(order_id, "7", false);
                            }
                            System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " delete order is : " + order_id + Environment.NewLine);

                        }
                        catch (Exception ex)
                        {
                            dbManager.Dispose();
                            ws.Dispose();
                            ws.Inset_Log(order_id, ex.Message);
                            System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " delete order tppe is VMware,and fail order_id is : " + order_id + Environment.NewLine);

                        }
                    }
                    else if (vmtype == "KVM")
                    {
                        string kvm_hostname = ds.Tables[0].Rows[0]["kvm_hostname"].ToString();
                        string kvm_dsname = ds.Tables[0].Rows[0]["kvm_dsname"].ToString();
                        string kvm_account = ds.Tables[0].Rows[0]["kvm_account"].ToString();
                        string kvm_pwd = CryptoAES.decrypt(ds.Tables[0].Rows[0]["kvm_pwd"].ToString(), "GccA@stanchengGg");
                        string[] guidf0 = vmapi.init(kvm_hostname, kvm_dsname, kvm_account, kvm_pwd).Split(':');
                        string[] guidf1 = guidf0[2].Split('\'');
                        string guid = guidf1[1];
                        string VMWare_Power_off_f = vmapi.powerOffVM(guid, "", kvm_hostname, order_id).Split(':')[1].Split(',')[0];
                        try
                        {
                            if (IsDelImg == "true" && VMWare_Power_off_f == "true")
                            {
                                vmapi.removeVM(guid, "", kvm_hostname, order_id, kvm_dsname, true);
                                ws.Change_Order_Status(order_id, "7", false);
                            }
                            else if (IsDelImg == "true" && VMWare_Power_off_f == "false")
                            {
                                ws.Inset_Log(order_id, "Power Off Error");
                            }
                            else if (IsDelImg == "false" && VMWare_Power_off_f == "false")
                            {
                                ws.Inset_Log(order_id, "Power Off Error");
                            }
                            else if (IsDelImg == "false" && VMWare_Power_off_f == "true")
                            {
                                ws.Change_Order_Status(order_id, "7", false);
                            }
                            System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " delete order is : " + order_id + Environment.NewLine);

                        }
                        catch (Exception ex)
                        {
                            dbManager.Dispose();
                            ws.Dispose();
                            ws.Inset_Log(order_id, ex.Message);
                            System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " delete order tppe is KVM,and fail order_id is : " + order_id + Environment.NewLine);

                        }
                    }

                }
            }
            catch (Exception)
            {
                dbManager.Dispose();
                ws.Dispose();
            }
            finally
            {
                dbManager.Dispose();
            }
            #endregion

            #region 是否有訂單完成  vm create ready
            try//是否有訂單完成  vm create ready
            {
                dbManager.Open();
                string sql = "";
                Int32 nCount = 0;
                //
                sql = @"select TOP 1 e.os_type as os,a.order_audit,a.FQDN+'@'+f.domain_name as FQDN,a.order_vm_type,order_id,order_area,a.order_cpu,a.order_ram,a.temp_id,order_vm_type,c.vpath,a.company_id,a.temp_id,a.group_id
                        from user_vm_order a
                        left outer join vm_temp b on a.temp_id=b.temp_id
                        left outer join vm_temp_virus_r c on a.temp_id=c.temp_id and a.order_virus=c.virus
                        left outer join Param e on b.os=e.para_id
                        left outer join c_domain f on a.company_id=f.company_id and a.order_area=f.area_id
                        where a.order_audit='5'
                        order by order_id";
                DataSet ds = dbManager.ExecuteDataSet(CommandType.Text, sql);
                nCount = ds.Tables[0].Rows.Count;
                System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "訂單完成數 : " + nCount + Environment.NewLine);

                if (nCount > 0)
                {
                    System.Threading.Thread.Sleep(18000);
                    string order_id = ds.Tables[0].Rows[0]["order_id"].ToString();
                    string FQDN = ds.Tables[0].Rows[0]["FQDN"].ToString();
                    ws.Send_mail(order_id, FQDN);
                    ws.Inset_Percent(order_id, "100", "");
                    ws.Change_Order_Status(order_id, "1", true);
                    dbManager.CreateParameters(1);
                    dbManager.AddParameters(0, "order_id", order_id);
                    string sql2 = @"update user_vm_order
                                set finish_time=getdate()
                                where order_id=@order_id";
                    DataSet ds2 = dbManager.ExecuteDataSet(CommandType.Text, sql2);
                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "send mail, change order status ok. "  + Environment.NewLine);
                }
            }
            catch (Exception ex)
            {
                dbManager.Dispose();
                ws.Dispose();
                System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "訂單完成產生錯誤 : " + ex.Message + Environment.NewLine);
            }
            finally
            {
                dbManager.Dispose();
            }
            #endregion

            try//是否有訂單需建立 need create
            {
                dbManager.Open();
                string check_order = @"select order_audit
                                   from user_vm_order
                                   where order_audit = '3' ";
                DataSet ds0 = dbManager.ExecuteDataSet(CommandType.Text, check_order);
                Int32 n1 = ds0.Tables[0].Rows.Count;
                System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "craeting VM number is : " + n1 + Environment.NewLine);
                if (n1 <= Max_Create_VM_Num)                                //一次只能建立?筆訂單
                {
                    try
                    {
                        string sql = "";
                        Int32 nCount = 0;
                        Int32 result = 0;
                        sql = @"SELECT TOP 1 e.os_type as os,a.order_audit,a.order_vm_type,order_id,order_area,a.order_cpu,
                                        a.order_ram,a.temp_id,order_vm_type,c.vpath,a.company_id,a.temp_id,a.group_id,a.vlan_id,a.order_nhd
                                FROM user_vm_order a
                                        left outer join vm_temp b on a.temp_id=b.temp_id
                                        left outer join vm_temp_virus_r c on a.temp_id=c.temp_id and a.order_virus=c.virus
                                        left outer join Param e on b.os=e.para_id
                                WHERE a.order_audit='2'
                                ORDER BY order_id";
                        DataSet ds = dbManager.ExecuteDataSet(CommandType.Text, sql);
                        nCount = ds.Tables[0].Rows.Count;
                        Create_VM_Service.VMAPI.GCCA_HypervisorAPI vmapi = new GCCA_HypervisorAPI();
                        string group_id = "";
                        string company_id = "";
                        string order_id = "";
                        string os = "";
                        string vmtype = "";
                        string order_area = "";
                        string temp_id = "";
                        string order_vm_type = "";
                        string vpath = "";
                        string cpu = "";
                        string ram = "";
                        string hdSize = "";
                        Int32 add_nic_num = 0;
                        string[] vlan_id = { };
                        string virNetworkName = "";
                        string[] virNetworkName_m = { };
                        string kvm_account = "";
                        string kvm_dsname = "";
                        string kvm_hostname = "";
                        string kvm_pwd = "";
                        string vmware_apiurl = "";
                        string vmware_datacenter_name = "";
                        string vmware_host_encryp_pwd = "";
                        string vmware_datastore_name = "";
                        string vmware_host_account = "";
                        string vmware_host_name = "";
                        string vmware_host_pwd = "";
                        string create_on_hostname = "";
                        string create_on_datacentername = "";
                        string resource_pool_name = "";
                        string guid = "";
                        bool exist_group_flag = false;
                        bool create_flag = false;

                        #region 是否有訂單需建立 need create vm have group(?)

                        if (nCount == 1)   // 根本一次只能建立一筆xddd
                        {
                            group_id = ds.Tables[0].Rows[0]["group_id"].ToString();
                            company_id = ds.Tables[0].Rows[0]["company_id"].ToString();
                            order_id = ds.Tables[0].Rows[0]["order_id"].ToString();
                            os = ds.Tables[0].Rows[0]["os"].ToString();
                            vmtype = ds.Tables[0].Rows[0]["order_vm_type"].ToString();
                            order_area = ds.Tables[0].Rows[0]["order_area"].ToString();
                            temp_id = ds.Tables[0].Rows[0]["temp_id"].ToString();
                            order_vm_type = ds.Tables[0].Rows[0]["order_vm_type"].ToString();
                            vpath = ds.Tables[0].Rows[0]["vpath"].ToString();
                            cpu = ds.Tables[0].Rows[0]["order_cpu"].ToString();
                            ram = Convert.ToString(Convert.ToInt16(ds.Tables[0].Rows[0]["order_ram"].ToString()) * 1024);
                            add_nic_num = ds.Tables[0].Rows[0]["vlan_id"].ToString().Split(',').Count() - 1;
                            vlan_id = ds.Tables[0].Rows[0]["vlan_id"].ToString().Split(',');
                            hdSize = ds.Tables[0].Rows[0]["order_nhd"].ToString();
                            dbManager.CreateParameters(1);
                            dbManager.AddParameters(0, "order_id", order_id);
                            sql = @"UPDATE user_vm_order
                                         SET order_audit='3',upd_datetime=getdate()
                                         WHERE order_id=@order_id
                                        update user_vm_order
                                        set create_time=getdate()
                                        where order_id=@order_id";
                            result = dbManager.ExecuteNonQuery(CommandType.Text, sql);
                            if (group_id != "")//有群組的話
                            {
                                ws.Inset_Percent(order_id, "10", "");
                                if (vmtype == "KVM")
                                {
                                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "order_id is  : " + order_id + " VMtype is : " + vmtype + Environment.NewLine);

                                    dbManager.CreateParameters(4);
                                    dbManager.AddParameters(0, "@order_area", order_area);
                                    dbManager.AddParameters(1, "@company_id", company_id);
                                    dbManager.AddParameters(2, "@vmtype", vmtype);
                                    dbManager.AddParameters(3, "@temp_id", temp_id);
                                    sql = @"SELECT kvm_account,kvm_dsname,kvm_hostname,kvm_pwd,b.hostname as create_on_hostname
                                            FROM config_vm_host a left outer join vm_temp b on a.vmtype=b.vm_type
                                            WHERE area=@order_area and a.company_id=@company_id and vmtype=@vmtype and temp_id=@temp_id";
                                    ds = dbManager.ExecuteDataSet(CommandType.Text, sql);
                                    nCount = ds.Tables[0].Rows.Count;
                                    if (nCount == 1)//如果KVM只有一台HOST
                                    {
                                        #region assign host
                                        kvm_account = ds.Tables[0].Rows[0]["kvm_account"].ToString();
                                        kvm_dsname = ds.Tables[0].Rows[0]["kvm_dsname"].ToString();
                                        kvm_hostname = ds.Tables[0].Rows[0]["kvm_hostname"].ToString();
                                        create_on_hostname = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();
                                        kvm_pwd = CryptoAES.decrypt(ds.Tables[0].Rows[0]["kvm_pwd"].ToString(), "GccA@stanchengGg");

                                        //string kvm_usage = ws.get_KVM_HOST_Usage(kvm_hostname, kvm_account, kvm_pwd);
                                        //string kvm_vm_usage = ws.get_KVM_VM_Usage(kvm_hostname, kvm_dsname, kvm_account, kvm_pwd);
                                        string[] guidf0 = vmapi.init(kvm_hostname, kvm_dsname, kvm_account, kvm_pwd).Split(':');
                                        string[] guidf1 = guidf0[2].Split('\'');

                                        // TODO: add comment
                                        guid = guidf1[1];

                                        string nic_name1 = vmapi.getHostNetworkList(guid, "", kvm_hostname);
                                        //JToken temp = JObject.Parse(nic_name1);

                                        Int32 kvm_count = Regex.Split(nic_name1, "\"message\":")[1].Split(',').Count() / 2;
                                        for (int kc = 1; kc <= kvm_count; kc++)//判斷定單上Vlan_id有沒有與HOST上VLAN_ID相符合
                                        {
                                            if (vlan_id[kc] != (Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[kc].Split('}')[0].Split(',')[1]).Split('\"')[3])
                                            {
                                                exist_group_flag = false;
                                            }
                                            else
                                            {
                                                virNetworkName = Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[kc].Split('}')[0].Split(',')[0].Split('\"')[3];
                                                exist_group_flag = true;
                                                break;
                                            }
                                        }
                                        #endregion
                                    }

                                    #region assign host
                                    //else if (nCount > 1)//KVM大於一台HOST將所有HOST的資源做比較抓出資源最多之HOST
                                    //{
                                    //    int kvm_memory1 = 0;
                                    //    int kvm_memory2 = 0;
                                    //    int kvm_vm_cpu1 = 0;
                                    //    int kvm_vm_cpu2 = 0;
                                    //    for (int i = 0; i < nCount; i++)
                                    //    {
                                    //        string kvm_vm_usage_memory = "";
                                    //        string kvm_useage = "";
                                    //        string kvm_account2 = "";
                                    //        string kvm_dsname2 = "";
                                    //        string kvm_vm_usage_memory2 = "";
                                    //        string kvm_hostname2 = "";
                                    //        string kvm_pwd2 = "";
                                    //        string kvm_useage2 = "";
                                    //        string create_on_hostname2 = "";
                                    //        string virNetworkName2 = "";

                                    //        if (i == 0 && exist_group_flag == false)
                                    //        {

                                    //            kvm_account = ds.Tables[0].Rows[i]["kvm_account"].ToString();
                                    //            kvm_dsname = ds.Tables[0].Rows[i]["kvm_dsname"].ToString();
                                    //            kvm_hostname = ds.Tables[0].Rows[i]["kvm_hostname"].ToString();
                                    //            kvm_pwd = ds.Tables[0].Rows[i]["kvm_pwd"].ToString();
                                    //            create_on_hostname = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();

                                    //            string[] guidf0 = vmapi.init(kvm_hostname, kvm_dsname, kvm_account, kvm_pwd).Split(':');
                                    //            string[] guidf1 = guidf0[2].Split('\'');

                                    //            guid = guidf1[1];

                                    //            string nic_name1 = vmapi.getHostNetworkList(guid, "", kvm_hostname);
                                    //            Int32 kvm_count = Regex.Split(nic_name1, "\"message\":")[1].Split(',').Count() / 2;
                                    //            for (int kc = 1; kc <= kvm_count; kc++)
                                    //            {
                                    //                if (group_id != (Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[kc].Split('}')[0].Split(',')[1]).Split('\"')[3])
                                    //                {
                                    //                    exist_group_flag = false;
                                    //                }
                                    //                else
                                    //                {
                                    //                    virNetworkName = Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[kc].Split('}')[0].Split(',')[0].Split('\"')[3];
                                    //                    exist_group_flag = true;
                                    //                    create_flag = true;
                                    //                    break;
                                    //                }
                                    //            }
                                    //            if (exist_group_flag == true)
                                    //            {
                                    //                kvm_useage = ws.get_KVM_HOST_Usage(kvm_hostname, kvm_account, kvm_pwd);//KVM_HOST有多少MEMORY
                                    //                kvm_vm_usage_memory = ws.get_KVM_VM_Usage(kvm_hostname, kvm_dsname, kvm_account, kvm_pwd);//在此HOST上VM使用多少MEMORY及
                                    //                string kvm_host_memory = kvm_useage.Split(':')[1].Split(']')[0].Trim();
                                    //                string kvm_vm_cpu = kvm_vm_usage_memory.Split(':')[2].Trim();
                                    //                string kvm_vm_memory = kvm_vm_usage_memory.Split(':')[1].Split(' ')[1].ToString().Trim();
                                    //                kvm_memory1 = (Convert.ToInt32(kvm_host_memory)) - (Convert.ToInt32(kvm_vm_memory));
                                    //                kvm_vm_cpu1 = (Convert.ToInt32(kvm_vm_cpu));
                                    //            }

                                    //        }
                                    //        else if (i > 0 && exist_group_flag == false)
                                    //        {

                                    //            kvm_account = ds.Tables[0].Rows[i]["kvm_account"].ToString();
                                    //            kvm_dsname = ds.Tables[0].Rows[i]["kvm_dsname"].ToString();
                                    //            kvm_hostname = ds.Tables[0].Rows[i]["kvm_hostname"].ToString();
                                    //            kvm_pwd = ds.Tables[0].Rows[i]["kvm_pwd"].ToString();
                                    //            create_on_hostname = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();

                                    //            string[] guidf0 = vmapi.init(kvm_hostname, kvm_dsname, kvm_account, kvm_pwd).Split(':');
                                    //            string[] guidf1 = guidf0[2].Split('\'');

                                    //            guid = guidf1[1];

                                    //            string nic_name1 = vmapi.getHostNetworkList(guid, "", kvm_hostname);
                                    //            Int32 kvm_count = Regex.Split(nic_name1, "\"message\":")[1].Split(',').Count() / 2;
                                    //            for (int kc = 1; kc <= kvm_count; kc++)
                                    //            {
                                    //                if (group_id != (Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[kc].Split('}')[0].Split(',')[1]).Split('\"')[3])
                                    //                {
                                    //                    exist_group_flag = false;
                                    //                }
                                    //                else
                                    //                {
                                    //                    virNetworkName = Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[kc].Split('}')[0].Split(',')[0].Split('\"')[3];
                                    //                    exist_group_flag = true;
                                    //                    create_flag = true;
                                    //                    break;
                                    //                }
                                    //            }
                                    //            if (exist_group_flag == true)
                                    //            {
                                    //                kvm_useage = ws.get_KVM_HOST_Usage(kvm_hostname, kvm_account, kvm_pwd);
                                    //                kvm_vm_usage_memory = ws.get_KVM_VM_Usage(kvm_hostname, kvm_dsname, kvm_account, kvm_pwd);
                                    //                string kvm_host_memory = kvm_useage.Split(':')[1].Split(']')[0].Trim();
                                    //                string kvm_vm_cpu = kvm_vm_usage_memory.Split(':')[2].Trim();
                                    //                string kvm_vm_memory = kvm_vm_usage_memory.Split(':')[1].Split(' ')[1].ToString().Trim();
                                    //                kvm_memory1 = (Convert.ToInt32(kvm_host_memory)) - (Convert.ToInt32(kvm_vm_memory));
                                    //                kvm_vm_cpu1 = (Convert.ToInt32(kvm_vm_cpu));
                                    //            }
                                    //        }
                                    //        else if (i > 0 && exist_group_flag == true)
                                    //        {
                                    //            kvm_account2 = ds.Tables[0].Rows[i]["kvm_account"].ToString();
                                    //            kvm_dsname2 = ds.Tables[0].Rows[i]["kvm_dsname"].ToString();
                                    //            kvm_hostname2 = ds.Tables[0].Rows[i]["kvm_hostname"].ToString();
                                    //            kvm_pwd2 = ds.Tables[0].Rows[i]["kvm_pwd"].ToString();
                                    //            create_on_hostname2 = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();

                                    //            string[] guidf0 = vmapi.init(kvm_hostname2, kvm_dsname2, kvm_account2, kvm_pwd2).Split(':');
                                    //            string[] guidf1 = guidf0[2].Split('\'');

                                    //            guid = guidf1[1];

                                    //            string nic_name1 = vmapi.getHostNetworkList(guid, "", kvm_hostname2);
                                    //            Int32 kvm_count = Regex.Split(nic_name1, "\"message\":")[1].Split(',').Count() / 2;
                                    //            for (int kc = 1; kc <= kvm_count; kc++)
                                    //            {
                                    //                for (int nic_count = 0; nic_count <= add_nic_num; nic_count++)
                                    //                {
                                    //                    if (vlan_id[nic_count] != (Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[kc].Split('}')[0].Split(',')[1]).Split('\"')[3])
                                    //                    {
                                    //                        exist_group_flag = false;
                                    //                    }
                                    //                    else
                                    //                    {
                                    //                        virNetworkName = Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[kc].Split('}')[0].Split(',')[0].Split('\"')[3];
                                    //                        exist_group_flag = true;
                                    //                        create_flag = true;
                                    //                        break;
                                    //                    }
                                    //                }
                                    //            }
                                    //            if (exist_group_flag == true)
                                    //            {
                                    //                kvm_useage2 = ws.get_KVM_HOST_Usage(kvm_hostname2, kvm_account2, kvm_pwd2);
                                    //                kvm_vm_usage_memory2 = ws.get_KVM_VM_Usage(kvm_hostname2, kvm_dsname2, kvm_account2, kvm_pwd2);
                                    //                string kvm_host_memory = kvm_useage2.Split(':')[1].Split(']')[0].Trim();
                                    //                string kvm_vm_cpu = kvm_vm_usage_memory2.Split(':')[2].Trim();
                                    //                string kvm_vm_memory = kvm_vm_usage_memory2.Split(':')[1].Split(' ')[1].ToString().Trim();
                                    //                kvm_memory2 = (Convert.ToInt32(kvm_host_memory)) - (Convert.ToInt32(kvm_vm_memory));
                                    //                kvm_vm_cpu2 = (Convert.ToInt32(kvm_vm_cpu));
                                    //                if (kvm_memory1 < kvm_memory2)
                                    //                {
                                    //                    virNetworkName = virNetworkName2;
                                    //                    kvm_account = kvm_account2;
                                    //                    kvm_dsname = kvm_dsname2;
                                    //                    kvm_hostname = kvm_hostname2;
                                    //                    kvm_pwd = kvm_pwd2;
                                    //                    create_on_hostname = create_on_hostname2;
                                    //                    kvm_memory1 = kvm_memory2;
                                    //                }
                                    //                else if (kvm_memory1 == kvm_memory2)
                                    //                {
                                    //                    if (kvm_vm_cpu1 < kvm_vm_cpu2)
                                    //                    {
                                    //                        virNetworkName = virNetworkName2;
                                    //                        kvm_account = kvm_account2;
                                    //                        kvm_dsname = kvm_dsname2;
                                    //                        kvm_hostname = kvm_hostname2;
                                    //                        kvm_pwd = kvm_pwd2;
                                    //                        create_on_hostname = create_on_hostname2;
                                    //                        kvm_memory1 = kvm_memory2;
                                    //                    }
                                    //                }
                                    //            }
                                    //        }
                                    //    }
                                    //}
                                    //
                                    #endregion
                                }
                                if (vmtype == "VMware")
                                {
                                    dbManager.CreateParameters(4);
                                    dbManager.AddParameters(0, "@order_area", order_area);
                                    dbManager.AddParameters(1, "@company_id", company_id);
                                    dbManager.AddParameters(2, "@vmtype", vmtype);
                                    dbManager.AddParameters(3, "@temp_id", temp_id);
                                    sql = @"SELECT vmware_apiurl,vmware_datacenter_name,vmware_datastore_name,vmware_host_account,vmware_host_name,vmware_host_pwd,b.hostname as create_on_hostname,resource_pool_name,b.datacenter_name as create_on_datacentername,b.temp_id
                                            FROM config_vm_host a left outer join vm_temp b on a.vmtype=b.vm_type
                                            WHERE area=@order_area and a.company_id=@company_id and vmtype=@vmtype and b.temp_id=@temp_id";
                                    ds = dbManager.ExecuteDataSet(CommandType.Text, sql);
                                    nCount = ds.Tables[0].Rows.Count;
                                    if (nCount == 1)//如果只有一台VMWARE HOST
                                    {
                                        System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "order_id is  : " + order_id + " VMtype is : " + vmtype + Environment.NewLine);

                                        #region assign host
                                        vmware_apiurl = ds.Tables[0].Rows[0]["vmware_apiurl"].ToString();
                                        string vmware_vcenter_ip = vmware_apiurl.Split('/')[2];
                                        vmware_datacenter_name = ds.Tables[0].Rows[0]["vmware_datacenter_name"].ToString();
                                        vmware_datastore_name = ds.Tables[0].Rows[0]["vmware_datastore_name"].ToString();
                                        vmware_host_account = ds.Tables[0].Rows[0]["vmware_host_account"].ToString();
                                        vmware_host_name = ds.Tables[0].Rows[0]["vmware_host_name"].ToString();
                                        vmware_host_pwd = CryptoAES.decrypt(ds.Tables[0].Rows[0]["vmware_host_pwd"].ToString(), "GccA@stanchengGg");
                                        vmware_host_encryp_pwd = ds.Tables[0].Rows[0]["vmware_host_pwd"].ToString();
                                        create_on_hostname = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();
                                        create_on_datacentername = ds.Tables[0].Rows[0]["create_on_datacentername"].ToString();
                                        resource_pool_name = Convert.ToString(ds.Tables[0].Rows[0]["resource_pool_name"]);
                                        //string vmware_usage = vm_useage.get_VMware_HOST_Usage(vmware_vcenter_ip, vmware_host_name, vmware_host_account, vmware_host_pwd);
                                        //string vmware_vm_usage = vm_useage.get_VMware_VM_Usage(vmware_apiurl,vmware_host_account,vmware_host_pwd,vmware_datacenter_name,vmware_host_name);
                                        string[] guidf0 = vmapi.init(vmware_apiurl, vmware_host_account, vmware_host_pwd, vmware_datacenter_name, true).Split(':');
                                        string[] guidf1 = guidf0[2].Split('\'');
                                        guid = guidf1[1];
                                        string nic_name1 = vmapi.getHostNetworkList(guid, vmware_datacenter_name, vmware_host_name);
                                        Int32 vm_count = Regex.Split(nic_name1, "\"message\":")[1].Split(',').Count() / 2;
                                        for (int vc = 1; vc <= vm_count; vc++)
                                        {
                                            if (exist_group_flag != true)
                                            {
                                                for (int nic_count = 0; nic_count <= add_nic_num; nic_count++)
                                                {
                                                    if (vlan_id[nic_count] != (Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[vc].Split('}')[0].Split(',')[1]).Split('\"')[3])
                                                    {
                                                        exist_group_flag = false;
                                                    }
                                                    else
                                                    {
                                                        string vlan_id1 = vlan_id[nic_count];
                                                        virNetworkName = Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[vc].Split('}')[0].Split(',')[0].Split('\"')[3];
                                                        virNetworkName_m = Regex.Split(nic_name1, "\"message\":")[1].Replace("\"", "").Replace("{", "").Replace("[", "").Replace("}", "").Replace("]", "").Replace(")", "").Replace(":", ",").Split(',');
                                                        int count = 0;
                                                        virNetworkName_st[] host_nic_and_vlan = new virNetworkName_st[virNetworkName_m.Count() / 4];
                                                        for (int ii = 3; ii <= virNetworkName_m.Count(); ii = ii + 4)
                                                        {
                                                            host_nic_and_vlan[count].vlan_id = virNetworkName_m[ii];
                                                            host_nic_and_vlan[count].network_name = virNetworkName_m[ii - 2];
                                                            count++;
                                                            //if (ii != virNetworkName_m.Count()-1)
                                                            //{
                                                            //    vlan_id2 += "[" + virNetworkName_m[ii] + "," + virNetworkName_m[ii - 2] + "]" + ",";
                                                            //}
                                                            //else
                                                            //{
                                                            //    vlan_id2 += "[" + virNetworkName_m[ii] + "," + virNetworkName_m[ii - 2] + "]";
                                                            //}
                                                        }
                                                        for (int iii = 0; iii < vlan_id.Count(); iii++)
                                                        {
                                                            for (int ii = 0; ii < host_nic_and_vlan.Count(); ii++)
                                                            {
                                                                if (vlan_id[iii] == host_nic_and_vlan[ii].vlan_id)
                                                                {
                                                                    vlan_id[iii] = host_nic_and_vlan[ii].vlan_id;
                                                                }
                                                            }
                                                        }
                                                        exist_group_flag = true;
                                                        create_flag = true;
                                                    }
                                                }
                                            }
                                        }
                                        #endregion
                                    }
                                    //
                                    //else if (nCount > 1)//如果大於一台VMWARE HOST將所有HOST的資源做比較抓出資源最多之HOST
                                    //{
                                    #region assign host

                                    //    int vmware_memory1 = 0;
                                    //    int vmware_memory2 = 0;
                                    //    int vmware_vm_cpu1 = 0;
                                    //    int vmware_vm_cpu2 = 0;
                                    //    for (int i = 0; i < nCount; i++)
                                    //    {
                                    //        string vmware_vm_usage_memory = "";
                                    //        string vmware_useage = "";
                                    //        string vmware_vm_usage_memory2 = "";
                                    //        string vmware_host_account2 = "";
                                    //        string vmware_datastore_name2 = "";
                                    //        string vmware_datacenter_name2 = "";
                                    //        string vmware_apiurl2 = "";
                                    //        string vmware_host_name2 = "";
                                    //        string vmware_host_pwd2 = "";
                                    //        string vmware_useage2 = "";
                                    //        string vmware_host_encryp_pwd2 = "";
                                    //        string create_on_hostname2 = "";
                                    //        string create_on_datacentername2 = "";
                                    //        string resource_pool_name2 = "";
                                    //        string virNetworkName2 = "";
                                    //        if (i == 0 && exist_group_flag == false)
                                    //        {
                                    //            vmware_host_account = ds.Tables[0].Rows[i]["vmware_host_account"].ToString();
                                    //            vmware_datastore_name = ds.Tables[0].Rows[i]["vmware_datastore_name"].ToString();
                                    //            vmware_datacenter_name = ds.Tables[0].Rows[i]["vmware_datacenter_name"].ToString();
                                    //            vmware_apiurl = ds.Tables[0].Rows[i]["vmware_apiurl"].ToString();
                                    //            string vmware_vcenter_ip = vmware_apiurl.Split('/')[2];
                                    //            vmware_host_name = ds.Tables[0].Rows[i]["vmware_host_name"].ToString();
                                    //            vmware_host_pwd = CryptoAES.decrypt(ds.Tables[0].Rows[i]["vmware_host_pwd"].ToString(), "GccA@stanchengGg");
                                    //            vmware_host_encryp_pwd = ds.Tables[0].Rows[i]["vmware_host_pwd"].ToString();
                                    //            create_on_hostname = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();
                                    //            create_on_datacentername = ds.Tables[0].Rows[0]["create_on_datacentername"].ToString();
                                    //            resource_pool_name = Convert.ToString(ds.Tables[0].Rows[0]["resource_pool_name"]);
                                    //            string[] guidf0 = vmapi.init(vmware_apiurl, vmware_host_account, vmware_host_pwd, vmware_datacenter_name, true).Split(':');
                                    //            string[] guidf1 = guidf0[2].Split('\'');
                                    //            guid = guidf1[1];
                                    //            string nic_name1 = vmapi.getHostNetworkList(guid, vmware_datacenter_name, vmware_host_name);
                                    //            Int32 vm_count = Regex.Split(nic_name1, "\"message\":")[1].Split(',').Count() / 2;
                                    //            for (int vc = 1; vc <= vm_count; vc++)
                                    //            {
                                    //                for (int nic_count = 0; nic_count <= add_nic_num; nic_count++)
                                    //                {
                                    //                    if (vlan_id[nic_count] != (Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[vc].Split('}')[0].Split(',')[1]).Split('\"')[3])
                                    //                    {
                                    //                        exist_group_flag = false;
                                    //                    }
                                    //                    else
                                    //                    {
                                    //                        virNetworkName = Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[vc].Split('}')[0].Split(',')[0].Split('\"')[3];
                                    //                        exist_group_flag = true;
                                    //                        create_flag = true;
                                    //                        break;
                                    //                    }
                                    //                }
                                    //            }
                                    //            if (exist_group_flag == true)
                                    //            {
                                    //                vmware_useage = ws.get_VMware_HOST_Usage(vmware_vcenter_ip, vmware_host_name, vmware_host_account, vmware_host_pwd);
                                    //                vmware_vm_usage_memory = ws.get_VMware_VM_Usage(vmware_apiurl, vmware_host_account, vmware_host_pwd, vmware_datacenter_name, vmware_host_name);
                                    //                string vmware_host_memory = vmware_useage.Split(':')[1].Split(']')[0].Trim();
                                    //                string vmware_vm_cpu = vmware_vm_usage_memory.Split(':')[2].Trim();
                                    //                string vmware_vm_memory = vmware_vm_usage_memory.Split(':')[1].Split(' ')[1].Split('G')[0].Trim();
                                    //                vmware_memory1 = (Convert.ToInt32(vmware_host_memory)) - (Convert.ToInt32(vmware_vm_memory));
                                    //                vmware_vm_cpu1 = (Convert.ToInt32(vmware_vm_cpu));
                                    //            }
                                    //        }
                                    //        else if (i > 0 && exist_group_flag == false)
                                    //        {
                                    //            vmware_host_account = ds.Tables[0].Rows[i]["vmware_host_account"].ToString();
                                    //            vmware_datastore_name = ds.Tables[0].Rows[i]["vmware_datastore_name"].ToString();
                                    //            vmware_datacenter_name = ds.Tables[0].Rows[i]["vmware_datacenter_name"].ToString();
                                    //            vmware_apiurl = ds.Tables[0].Rows[i]["vmware_apiurl"].ToString();
                                    //            string vmware_vcenter_ip = vmware_apiurl.Split('/')[2];
                                    //            vmware_host_name = ds.Tables[0].Rows[i]["vmware_host_name"].ToString();
                                    //            vmware_host_pwd = CryptoAES.decrypt(ds.Tables[0].Rows[i]["vmware_host_pwd"].ToString(), "GccA@stanchengGg");
                                    //            vmware_host_encryp_pwd = ds.Tables[0].Rows[i]["vmware_host_pwd"].ToString();
                                    //            create_on_hostname = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();
                                    //            create_on_datacentername = ds.Tables[0].Rows[0]["create_on_datacentername"].ToString();
                                    //            resource_pool_name = Convert.ToString(ds.Tables[0].Rows[0]["resource_pool_name"]);
                                    //            string[] guidf0 = vmapi.init(vmware_apiurl, vmware_host_account, vmware_host_pwd, vmware_datacenter_name, true).Split(':');
                                    //            string[] guidf1 = guidf0[2].Split('\'');
                                    //            guid = guidf1[1];
                                    //            string nic_name1 = vmapi.getHostNetworkList(guid, vmware_datacenter_name, vmware_host_name);
                                    //            Int32 vm_count = Regex.Split(nic_name1, "\"message\":")[1].Split(',').Count() / 2;
                                    //            for (int vc = 1; vc <= vm_count; vc++)
                                    //            {
                                    //                for (int nic_count = 0; nic_count <= add_nic_num; nic_count++)
                                    //                {
                                    //                    if (vlan_id[nic_count] != (Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[vc].Split('}')[0].Split(',')[1]).Split('\"')[3])
                                    //                    {
                                    //                        exist_group_flag = false;
                                    //                    }
                                    //                    else
                                    //                    {
                                    //                        virNetworkName = Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[vc].Split('}')[0].Split(',')[0].Split('\"')[3];
                                    //                        exist_group_flag = true;
                                    //                        create_flag = true;
                                    //                        break;
                                    //                    }
                                    //                }
                                    //            }
                                    //            if (exist_group_flag == true)
                                    //            {
                                    //                vmware_useage = ws.get_VMware_HOST_Usage(vmware_vcenter_ip, vmware_host_name, vmware_host_account, vmware_host_pwd);
                                    //                vmware_vm_usage_memory = ws.get_VMware_VM_Usage(vmware_apiurl, vmware_host_account, vmware_host_pwd, vmware_datacenter_name, vmware_host_name);
                                    //                string vmware_host_memory = vmware_useage.Split(':')[1].Split(']')[0].Trim();
                                    //                string vmware_vm_cpu = vmware_vm_usage_memory.Split(':')[2].Trim();
                                    //                string vmware_vm_memory = vmware_vm_usage_memory.Split(':')[1].Split(' ')[1].Split('G')[0].Trim();
                                    //                vmware_memory1 = (Convert.ToInt32(vmware_host_memory)) - (Convert.ToInt32(vmware_vm_memory));
                                    //                vmware_vm_cpu1 = (Convert.ToInt32(vmware_vm_cpu));
                                    //            }

                                    //        }
                                    //        else if (i > 0 && exist_group_flag == true)
                                    //        {
                                    //            vmware_host_account2 = ds.Tables[0].Rows[i]["vmware_host_account"].ToString();
                                    //            vmware_datastore_name2 = ds.Tables[0].Rows[i]["vmware_datastore_name"].ToString();
                                    //            vmware_datacenter_name2 = ds.Tables[0].Rows[i]["vmware_datacenter_name"].ToString();
                                    //            vmware_apiurl2 = ds.Tables[0].Rows[i]["vmware_apiurl"].ToString();
                                    //            string vmware_vcenter_ip = vmware_apiurl.Split('/')[2];
                                    //            vmware_host_name2 = ds.Tables[0].Rows[i]["vmware_host_name"].ToString();
                                    //            vmware_host_pwd2 = CryptoAES.decrypt(ds.Tables[0].Rows[i]["vmware_host_pwd"].ToString(), "GccA@stanchengGg");
                                    //            vmware_host_encryp_pwd2 = ds.Tables[0].Rows[i]["vmware_host_pwd"].ToString();
                                    //            create_on_hostname2 = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();
                                    //            create_on_datacentername2 = ds.Tables[0].Rows[0]["create_on_datacentername"].ToString();
                                    //            resource_pool_name2 = Convert.ToString(ds.Tables[0].Rows[0]["resource_pool_name"]);

                                    //            string[] guidf0 = vmapi.init(vmware_apiurl, vmware_host_account, vmware_host_pwd, vmware_datacenter_name, true).Split(':');
                                    //            string[] guidf1 = guidf0[2].Split('\'');
                                    //            guid = guidf1[1];
                                    //            string nic_name1 = vmapi.getHostNetworkList(guid, vmware_datacenter_name2, vmware_host_name2);
                                    //            Int32 vm_count = Regex.Split(nic_name1, "\"message\":")[1].Split(',').Count() / 2;
                                    //            for (int vc = 1; vc <= vm_count; vc++)
                                    //            {
                                    //                for (int nic_count = 0; nic_count <= add_nic_num; nic_count++)
                                    //                {
                                    //                    if (vlan_id[nic_count] != (Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[vc].Split('}')[0].Split(',')[1]).Split('\"')[3])
                                    //                    {
                                    //                        exist_group_flag = false;
                                    //                    }
                                    //                    else
                                    //                    {
                                    //                        virNetworkName2 = Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[vc].Split('}')[0].Split(',')[0].Split('\"')[3];
                                    //                        exist_group_flag = true;
                                    //                        create_flag = true;
                                    //                        break;
                                    //                    }
                                    //                }
                                    //            }
                                    //            if (exist_group_flag == true)
                                    //            {
                                    //                vmware_useage2 = ws.get_VMware_HOST_Usage(vmware_vcenter_ip, vmware_host_name2, vmware_host_account2, vmware_host_pwd2);
                                    //                vmware_vm_usage_memory2 = ws.get_VMware_VM_Usage(vmware_apiurl2, vmware_host_account2, vmware_host_pwd2, vmware_datacenter_name2, vmware_host_name2);
                                    //                string vmware_host_memory = vmware_useage2.Split(':')[1].Split(']')[0].Trim();
                                    //                string vmware_vm_cpu = vmware_vm_usage_memory2.Split(':')[2].Trim();
                                    //                string vmware_vm_memory = vmware_vm_usage_memory2.Split(':')[1].Split(' ')[1].Split('G')[0].Trim();
                                    //                vmware_memory2 = (Convert.ToInt32(vmware_host_memory)) - (Convert.ToInt32(vmware_vm_memory));
                                    //                vmware_vm_cpu2 = (Convert.ToInt32(vmware_vm_cpu));
                                    //                if (vmware_memory1 < vmware_memory2)
                                    //                {
                                    //                    virNetworkName = virNetworkName2;
                                    //                    virNetworkName = virNetworkName2;
                                    //                    vmware_host_account = vmware_host_account2;
                                    //                    vmware_datastore_name = vmware_datastore_name2;
                                    //                    vmware_datacenter_name = vmware_datacenter_name2;
                                    //                    vmware_apiurl = vmware_apiurl2;
                                    //                    vmware_host_name = vmware_host_name2;
                                    //                    vmware_host_pwd = vmware_host_pwd2;
                                    //                    vmware_host_encryp_pwd = vmware_host_encryp_pwd2;
                                    //                    create_on_hostname = create_on_hostname2;
                                    //                    create_on_datacentername = create_on_datacentername2;
                                    //                    resource_pool_name = resource_pool_name2;
                                    //                    vmware_memory1 = vmware_memory2;
                                    //                }
                                    //                else if (vmware_memory1 == vmware_memory2)
                                    //                {
                                    //                    if (vmware_vm_cpu1 < vmware_vm_cpu2)
                                    //                    {
                                    //                        virNetworkName = virNetworkName2;
                                    //                        vmware_host_account = vmware_host_account2;
                                    //                        vmware_datastore_name = vmware_datastore_name2;
                                    //                        vmware_datacenter_name = vmware_datacenter_name2;
                                    //                        vmware_apiurl = vmware_apiurl2;
                                    //                        vmware_host_name = vmware_host_name2;
                                    //                        vmware_host_pwd = vmware_host_pwd2;
                                    //                        vmware_host_encryp_pwd = vmware_host_encryp_pwd2;
                                    //                        create_on_hostname = create_on_hostname2;
                                    //                        create_on_datacentername = create_on_datacentername2;
                                    //                        resource_pool_name = resource_pool_name2;
                                    //                        vmware_memory1 = vmware_memory2;
                                    //                    }
                                    //                }
                                    //            }
                                    //        }
                                    //    }
                                    #endregion
                                    //}
                                }

                                ws.Inset_Percent(order_id, "20", "");
                                //建立有GROUP之VM
                                vmapi.Timeout = 10000000;
                                try
                                {

                                    if (vmtype == "VMware")
                                    {
                                        if (create_flag == true)
                                        {
                                            string[] vcenter_ip_sp1 = vmware_apiurl.Split('/');
                                            string vcenter_ip = vcenter_ip_sp1[2];
                                            string[] guidf0 = vmapi.init(vmware_apiurl, vmware_host_account, vmware_host_pwd, vmware_datacenter_name, true).Split(':'); //連線至VMWARE HOST
                                            string[] guidf1 = guidf0[2].Split('\'');
                                            guid = guidf1[1];//取得GUID
                                            // string[] VMWare_VFT_sp0 = vmapi.createVMFromTemplate(guid, vpath, create_on_hostname, create_on_datacentername, order_id, vmware_host_name, vmware_datacenter_name, resource_pool_name, vmware_datastore_name).Split(':');//Create VM From Template
                                            // string[] VMWare_VFT_sp1 = VMWare_VFT_sp0[1].Split(',');
                                            string VMWare_VFT_F = "false";//VMWare_VFT_sp1[0];//Create VM From Template 是否成功
                                            System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "create VM is  : " + VMWare_VFT_F + Environment.NewLine);

                                            if (VMWare_VFT_F == "false")  ////還沒creat vm要改成true
                                            {
                                                //vmapi.powerOffVMAsync(guid, vmware_datacenter_name, vmware_host_name, order_id);//poweroff
                                                //ws.Inset_Percent(order_id, "35", "");
                                                //ws.set_create_on_host(order_id, vmware_host_name); // update order information with host name
                                                //vmapi.configVMCPUNum(guid, vmware_datacenter_name, vmware_host_name, order_id, cpu);//修改CPU數量
                                                //vmapi.configVMMemory(guid, vmware_datacenter_name, vmware_host_name, order_id, ram);//修改RAM大小

                                                //if (hdSize != "") //remove HD and add HD
                                                //{
                                                //    vmapi.removeVMDisk(guid, vmware_datacenter_name, vmware_datastore_name, vmware_datacenter_name, order_id, "1");
                                                //    vmapi.addVMDisk(guid, vmware_datacenter_name, vmware_host_name, vmware_datastore_name, order_id, (int.Parse(hdSize) * 1000).ToString());
                                                //}

                                                //string mac1 = vmapi.getVMNICMacList(guid, vmware_datacenter_name, vmware_host_name, order_id);
                                                //VM_set_adapter(vlan_id, virNetworkName_m, guid, vmware_datacenter_name, vmware_host_name, order_id); //暫時 FOR VMWARE   setting adapter. write by jedi
                                                System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "VM hardware set is Complete : " + order_id + Environment.NewLine);
                                                string[] VMWare_Power_on_sp0 = vmapi.powerOnVM(guid, vmware_datacenter_name, vmware_host_name, order_id).Split(':');//開機
                                                string[] VMWare_Power_on_sp1 = VMWare_Power_on_sp0[1].Split(',');
                                                string VMWare_Power_on_F = VMWare_Power_on_sp1[0];//是否開機成功
                                                if (VMWare_Power_on_F == "true")
                                                {
                                                    ws.set_create_on_host(order_id, vmware_host_name);
                                                    RunspaceInvoke invoker = new RunspaceInvoke();
                                                    invoker.Invoke("Set-ExecutionPolicy Unrestricted");
                                                    System.Threading.Thread.Sleep(1000);
                                                    string[] url0 = vmware_apiurl.Split('/');
                                                    vmware_apiurl = url0[2];
                                                    System.Threading.Thread.Sleep(24000);//開機完成後等待240000毫秒
                                                    string vm_network_name = vmapi.getVMNICNetworkList(guid, vmware_datacenter_name, vmware_host_name, order_id).Split(':')[3].Split('"')[1];//取得此台VM之網路名稱

                                                    string vm_ip = vmapi.getVMIpAndMac(guid, vmware_datacenter_name, vmware_host_name, order_id, vm_network_name).Split(':')[2].Split('"')[1];//取得此台VM之IP
                                                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "VM ip is  : " + vm_ip + Environment.NewLine);

                                                    if (os == "0")//For MicroSoft
                                                    {
                                                        System.Threading.Thread.Sleep(1000);
                                                        invoker.Invoke("Set-Item WSMan:\\localhost\\Client\\TrustedHosts " + vm_ip + " -Concatenate -force");
                                                        // TODO: do not write account/password into the script
                                                        string pingvm = @"$username = ""User""
                                                                      $account = """ + vm_account + @"""
                                                                      $password = ConvertTO-SecureString """ + vm_password + @""" -asplaintext -Force
                                                                      $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $account, $password
                                                                      Invoke-Command -ComputerName " + vm_ip + @" -Authentication default" +
                                                                        @" -credential $cred " +
                                                                        @" -ScriptBlock {" +
                                                                            @"$FileExists = Test-Path ""c:\\AutoProvision"";" +
                                                                            @"If ($FileExists -eq $False){" +
                                                                                @"mkdir ""c:\\AutoProvision"";"
                                                                                + @"echo """ + order_id + " " + group_id + @""" >C:\\AutoProVision\\vmname.txt;"
                                                                                + @"echo ""timeout 30"""
                                                                                + @" `n 'msiexec /forcerestart /i  c:\AutoProVision\VMConfig.msi ALLUSERS=1 DB_Server=""" + db_server + @""" EmailAccount=""" + EmailAccount + "\" EmailPassword=\"" + EmailPassword + "\" smtphost=\"" + smtphost + "\" AutoProvision_WS_url=\"" + AutoProvision_WS_url + "\" /qn'"
                                                                                + @" `n ""timeout 10"" "
                                                                                + @"`n ""restart"" "
                                                                                + @"`n | "
                                                                                + @"Set-Content C:\AutoProVision\vmconfig.bat;"
                                                                                + @"$File = ""c:\AutoProvision\VMConfig.msi"";"
                                                                                + @"$ftp = """ + ftp_folder + "\\VMConfig.msi\";"
                                                                                + @"$File3 = ""c:\AutoProvision\creboot2.exe"";"
                                                                                + @"$ftp3 = """ + ftp_folder + @"\creboot2.exe"";"
                                                                                + @"$File4 = ""c:\AutoProvision\set_ip.exe"";"
                                                                                + @"$ftp4 = """ + ftp_folder + @"\set_ip.exe"";"
                                                                                + @"$webclient = New-Object System.Net.WebClient;"
                                                                                + @"$Username = """ + ConfigurationManager.AppSettings["ftpUsername"] + "\";"
                                                                                + @"$Password = """ + ConfigurationManager.AppSettings["ftpPassword"] + "\";"
                                                                                + @"$webclient = New-Object System.Net.WebClient;"
                                                                                + @"$WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password);"
                                                                                + @"$webclient.DownloadFile($ftp, $File);"
                                                                                + @"$webclient.DownloadFile($ftp3, $File3);"
                                                                                + @"$webclient.DownloadFile($ftp4, $File4);"
                                                                                + @"Start-Sleep -s 10 ; "
                                                                            + @"}"
                                                                            + @"c:\AutoProvision\vmconfig.bat;"
                                                                        + "}";
                                                        //使用POWERSHELL 連至VM並對此台VM下達Create一個vmname.txt內容放入訂單編號及群組ID,下載FTP上之AGENT的檔案安裝完AGENT後並重開機。
                                                        execute(pingvm);

                                                    }
                                                    if (os == "1") //For Linux
                                                    {
                                                        string hostSshUserName = "******";
                                                        string hostSshPassword = "******";
                                                        string agentFolderPath = "/opt/AutoConfigAgent";
                                                        // TODO: retrive url from outside
                                                        string wsUrl = AutoProvision_WS_url;
                                                        string hypervisorIpAddress = vmware_host_name;
                                                        string ftpUsername = ftp_user;
                                                        string ftpPassword = ftp_pwd;
                                                        string agentFtpPath = "/AutoConfigAgent";
                                                        string vmProvisionName = order_id;

                                                        executeLinuxScript(vm_ip, hostSshUserName, hostSshPassword, 22,
                                                        agentFolderPath, wsUrl, hypervisorIpAddress, ftp, ftpUsername, ftpPassword, agentFtpPath, vmProvisionName);
                                                    }
                                                    ws.Inset_Percent(order_id, "50", "");
                                                }
                                            }
                                        }
                                        else if (create_flag == false)
                                        {
                                            ws.Inset_Log(order_id, "No any host have your Vlan_id");
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    System.IO.File.AppendAllText(@"C:\AutoProvision\log.txt", "assign AGent error " + ex.Message + Environment.NewLine);
                                    return;
                                }
                                if (vmtype == "KVM")
                                {
                                    string[] guidf0 = vmapi.init(kvm_hostname, kvm_dsname, kvm_account, kvm_pwd).Split(':');
                                    string[] guidf1 = guidf0[2].Split('\'');
                                    guid = guidf1[1];
                                    //string[] KVM_VFT_sp0 = vmapi.createVMFromTemplate(guid, vpath, create_on_hostname, "", order_id, kvm_hostname, "", "", kvm_dsname).Split(':');
                                    //string[] KVM_VFT_sp1 = KVM_VFT_sp0[1].Split(',');
                                    //string KVM_VFT_F = KVM_VFT_sp1[0];
                                    System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "create VM is  : " + VMWare_VFT_F + Environment.NewLine);
                                    string KVM_VFT_F = "false";
                                    if (KVM_VFT_F == "false")
                                    {
                                        dbManager.Open();
                                        ws.Inset_Percent(order_id, "35", "");
                                        ws.set_create_on_host(order_id, kvm_hostname);
                                        vmapi.configVMCPUNum(guid, "", kvm_hostname, order_id, cpu);
                                        vmapi.configVMMemory(guid, "", kvm_hostname, order_id, ram);
                                        string nic_name1 = vmapi.getHostNetworkList(guid, vmware_datacenter_name, kvm_hostname);
                                        virNetworkName_m = Regex.Split(nic_name1, "\"message\":")[1].Replace("\"", "").Replace("{", "").Replace("[", "").Replace("}", "").Replace("]", "").Replace(")", "").Replace(":", ",").Split(',');
                                        //
                                        //vmapi.powerOffVMAsync(guid, vmware_datacenter_name, vmware_host_name, order_id);//poweroff
                                        //ws.Inset_Percent(order_id, "35", "");
                                        //ws.set_create_on_host(order_id, vmware_host_name); // update order information with host name
                                        //vmapi.configVMCPUNum(guid, vmware_datacenter_name, vmware_host_name, order_id, cpu);//修改CPU數量
                                        //vmapi.configVMMemory(guid, vmware_datacenter_name, vmware_host_name, order_id, ram);//修改RAM大小

                                        //if (hdSize != "") //remove HD and add HD
                                        //{
                                        //    vmapi.removeVMDisk(guid, vmware_datacenter_name, vmware_datastore_name, vmware_datacenter_name, order_id, "1");
                                        //    vmapi.addVMDisk(guid, vmware_datacenter_name, vmware_host_name, vmware_datastore_name, order_id, (int.Parse(hdSize) * 1000).ToString());
                                        //}

                                        //vmapi.adjustVMNIC(guid, "", kvm_hostname, order_id, "Network adapter 1", virNetworkName);

                                        VM_set_adapter(vlan_id, virNetworkName_m, guid, "", kvm_hostname, order_id);
                                        System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "VM hardware set is Complete : " + order_id + Environment.NewLine);

                                        string[] KVM_Power_on_sp0 = vmapi.powerOnVM(guid, kvm_hostname, kvm_hostname, order_id).Split(':');
                                        string[] KVM_Power_on_sp1 = KVM_Power_on_sp0[1].Split(',');
                                        string KVM_Power_on_F = KVM_Power_on_sp1[0];

                                        if (KVM_Power_on_F == "true")
                                        {
                                            ws.set_create_on_host(order_id, kvm_hostname);
                                            RunspaceInvoke invoker = new RunspaceInvoke();
                                            invoker.Invoke("Set-ExecutionPolicy Unrestricted");
                                            System.Threading.Thread.Sleep(240000);
                                            string vm_network_name = vmapi.getVMNICNetworkList(guid, "", kvm_hostname, order_id).Split(':')[3].Split('"')[1];
                                            string vm_ip = vmapi.getVMIpAndMac(guid, "", kvm_hostname, order_id, vm_network_name).Split(':')[2].Split('"')[1];

                                            if (os == "0")//For MicroSoft
                                            {
                                                invoker.Invoke("Set-Item WSMan:\\localhost\\Client\\TrustedHosts " + vm_ip + " -Concatenate -force");
                                                string pingvm = "$username = \"User\" \n" +
                                                                "$account = \"User\" \n" +
                                                                "$password = ConvertTO-SecureString \"Passw0rd\" -asplaintext -Force \n" +
                                                                "$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $account, $password \n" +
                                                                "Invoke-Command -ComputerName " + vm_ip + "  -Authentication default -credential $cred -ScriptBlock {$FileExists = Test-Path \"c:\\AutoProvision\";If ($FileExists -eq $False){mkdir \"c:\\AutoProvision\";echo \"" + order_id + " " + group_id + ">C:\\AutoProVision\\vmname.txt;echo \"timeout 30\" `n 'msiexec /forcerestart /i  c:\\AutoProVision\\VMConfig.msi ALLUSERS=1 DB_Server=\"" + db_server + "\" EmailAccount=\"" + EmailAccount + "\" EmailPassword=\"" + EmailPassword + "\" smtphost=\"" + smtphost + "\" AutoProvision_WS_url=\"" + AutoProvision_WS_url + "\" /qn' `n \"timeout 10\" `n \"restart\" `n | Set-Content C:\\AutoProVision\\vmconfig.bat;$File = \"c:\\AutoProvision\\VMConfig.msi\";$ftp = \"" + ftp_folder + "\\VMConfig.msi\";$File3 = \"c:\\AutoProvision\\creboot2.exe\";$ftp3 = \"" + ftp_folder + "\\creboot2.exe\";$File4 = \"c:\\AutoProvision\\set_ip.exe\";$ftp4 = \"" + ftp_folder + "\\set_ip.exe\";$webclient = New-Object System.Net.WebClient;$Username = \"" + ConfigurationManager.AppSettings["ftpUsername"] + "\";$Password = \"" + ConfigurationManager.AppSettings["ftpPassword"] + "\";$webclient = New-Object System.Net.WebClient;$WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password);$webclient.DownloadFile($ftp, $File);$webclient.DownloadFile($ftp3, $File3);$webclient.DownloadFile($ftp4, $File4);Start-Sleep -s 10 ; }c:\\AutoProvision\\vmconfig.bat;}";

                                                execute(pingvm);
                                            }
                                            if (os == "1") //For Linux
                                            {
                                                string hostSshUserName = "******";
                                                string hostSshPassword = "******";
                                                string agentFolderPath = "/opt/AutoConfigAgent";
                                                // TODO: retrive url from outside
                                                string wsUrl = AutoProvision_WS_url;
                                                string hypervisorIpAddress = kvm_hostname;
                                                string ftpUsername = ftp_user;
                                                string ftpPassword = ftp_pwd;
                                                string agentFtpPath = "/AutoConfigAgent";
                                                string vmProvisionName = order_id;

                                                executeLinuxScript(vm_ip, hostSshUserName, hostSshPassword, 22,
                                                agentFolderPath, wsUrl, hypervisorIpAddress, ftp, ftpUsername, ftpPassword, agentFtpPath, vmProvisionName);
                                            }
                                            ws.Inset_Percent(order_id, "50", "");
                                        }
                                    }
                                }
                            }
                        }
                        #endregion

                        if (group_id == null || group_id == "" || group_id == "0")
                        {
                            #region nonGroup

                            if (nCount == 1)
                            {
                                group_id = ds.Tables[0].Rows[0]["group_id"].ToString();
                                company_id = ds.Tables[0].Rows[0]["company_id"].ToString();
                                order_id = ds.Tables[0].Rows[0]["order_id"].ToString();
                                os = ds.Tables[0].Rows[0]["os"].ToString();
                                vmtype = ds.Tables[0].Rows[0]["order_vm_type"].ToString();
                                order_area = ds.Tables[0].Rows[0]["order_area"].ToString();
                                temp_id = ds.Tables[0].Rows[0]["temp_id"].ToString();
                                order_vm_type = ds.Tables[0].Rows[0]["order_vm_type"].ToString();
                                vpath = ds.Tables[0].Rows[0]["vpath"].ToString();
                                cpu = ds.Tables[0].Rows[0]["order_cpu"].ToString();
                                hdSize = ds.Tables[0].Rows[0]["order_nhd"].ToString();
                                ram = Convert.ToString(Convert.ToInt16(ds.Tables[0].Rows[0]["order_ram"].ToString()) * 1024);
                                add_nic_num = ds.Tables[0].Rows[0]["vlan_id"].ToString().Split(',').Count() - 1;
                                vlan_id = ds.Tables[0].Rows[0]["vlan_id"].ToString().Split(',');
                                dbManager.CreateParameters(1);
                                dbManager.AddParameters(0, "order_id", order_id);
                                sql = @"UPDATE user_vm_order
                                         SET order_audit='3',upd_datetime=getdate()
                                         WHERE order_id=@order_id
                                        update user_vm_order
                                        set create_time=getdate()
                                        where order_id=@order_id";
                                result = dbManager.ExecuteNonQuery(CommandType.Text, sql);

                                ws.Inset_Percent(order_id, "10", "");
                                if (vmtype == "KVM")
                                {
                                    dbManager.CreateParameters(4);
                                    dbManager.AddParameters(0, "@order_area", order_area);
                                    dbManager.AddParameters(1, "@company_id", company_id);
                                    dbManager.AddParameters(2, "@vmtype", vmtype);
                                    dbManager.AddParameters(3, "@temp_id", temp_id);
                                    sql = @"select kvm_account,kvm_dsname,kvm_hostname,kvm_pwd,b.hostname as create_on_hostname
                                from config_vm_host a left outer join vm_temp b on a.vmtype=b.vm_type
                                where area=@order_area and a.company_id=@company_id and vmtype=@vmtype and temp_id=@temp_id";
                                    ds = dbManager.ExecuteDataSet(CommandType.Text, sql);
                                    nCount = ds.Tables[0].Rows.Count;
                                    if (nCount == 1)
                                    {
                                        kvm_account = ds.Tables[0].Rows[0]["kvm_account"].ToString();
                                        kvm_dsname = ds.Tables[0].Rows[0]["kvm_dsname"].ToString();
                                        kvm_hostname = ds.Tables[0].Rows[0]["kvm_hostname"].ToString();
                                        kvm_pwd = CryptoAES.decrypt(ds.Tables[0].Rows[0]["kvm_pwd"].ToString(), "GccA@stanchengGg");
                                        create_on_hostname = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();
                                        //string kvm_usage = vm_useage.get_KVM_HOST_Usage(kvm_hostname, kvm_account, kvm_pwd);
                                        //string kvm_vm_usage = vm_useage.get_KVM_VM_Usage(kvm_hostname, kvm_dsname, kvm_account, kvm_pwd);

                                    }
                                    #region MyRegion
                                    //else if (nCount > 1)
                                    //{
                                    //

                                    //    int kvm_memory1 = 0;
                                    //    int kvm_memory2 = 0;
                                    //    int kvm_vm_cpu1 = 0;
                                    //    int kvm_vm_cpu2 = 0;
                                    //    for (int i = 0; i < nCount; i++)
                                    //    {
                                    //        string kvm_vm_usage_memory = "";
                                    //        string kvm_useage = "";
                                    //        string kvm_account2 = "";
                                    //        string kvm_dsname2 = "";
                                    //        string kvm_vm_usage_memory2 = "";
                                    //        string kvm_hostname2 = "";
                                    //        string kvm_pwd2 = "";
                                    //        string kvm_useage2 = "";
                                    //        string create_on_hostname2 = "";
                                    //        if (i == 0)
                                    //        {
                                    //            kvm_account = ds.Tables[0].Rows[i]["kvm_account"].ToString();
                                    //            kvm_dsname = ds.Tables[0].Rows[i]["kvm_dsname"].ToString();
                                    //            kvm_hostname = ds.Tables[0].Rows[i]["kvm_hostname"].ToString();
                                    //            kvm_pwd = CryptoAES.decrypt(ds.Tables[0].Rows[0]["kvm_pwd"].ToString(), "GccA@stanchengGg");
                                    //            create_on_hostname = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();
                                    //            kvm_useage = ws.get_KVM_HOST_Usage(kvm_hostname, kvm_account, kvm_pwd);
                                    //            kvm_vm_usage_memory = ws.get_KVM_VM_Usage(kvm_hostname, kvm_dsname, kvm_account, kvm_pwd);
                                    //            string kvm_host_memory = kvm_useage.Split(':')[1].Split(']')[0].Trim();
                                    //            string kvm_vm_cpu = kvm_vm_usage_memory.Split(':')[2].Trim();
                                    //            string kvm_vm_memory = kvm_vm_usage_memory.Split(':')[1].Split(' ')[1].ToString().Trim();
                                    //            kvm_memory1 = (Convert.ToInt32(kvm_host_memory)) - (Convert.ToInt32(kvm_vm_memory));
                                    //            kvm_vm_cpu1 = (Convert.ToInt32(kvm_vm_cpu));
                                    //        }
                                    //        else if (i > 0)
                                    //        {
                                    //            kvm_account2 = ds.Tables[0].Rows[i]["kvm_account"].ToString();
                                    //            kvm_dsname2 = ds.Tables[0].Rows[i]["kvm_dsname"].ToString();
                                    //            kvm_hostname2 = ds.Tables[0].Rows[i]["kvm_hostname"].ToString();
                                    //            kvm_pwd2 = CryptoAES.decrypt(ds.Tables[0].Rows[0]["kvm_pwd"].ToString(), "GccA@stanchengGg");
                                    //            create_on_hostname2 = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();
                                    //            kvm_useage2 = ws.get_KVM_HOST_Usage(kvm_hostname2, kvm_account2, kvm_pwd2);
                                    //            kvm_vm_usage_memory2 = ws.get_KVM_VM_Usage(kvm_hostname2, kvm_dsname2, kvm_account2, kvm_pwd2);
                                    //            string kvm_host_memory = kvm_useage2.Split(':')[1].Split(']')[0].Trim();
                                    //            string kvm_vm_cpu = kvm_vm_usage_memory2.Split(':')[2].Trim();
                                    //            string kvm_vm_memory = kvm_vm_usage_memory2.Split(':')[1].Split(' ')[1].ToString().Trim();
                                    //            kvm_memory2 = (Convert.ToInt32(kvm_host_memory)) - (Convert.ToInt32(kvm_vm_memory));
                                    //            kvm_vm_cpu2 = (Convert.ToInt32(kvm_vm_cpu));
                                    //            if (kvm_memory1 < kvm_memory2)
                                    //            {
                                    //                kvm_account = kvm_account2;
                                    //                kvm_dsname = kvm_dsname2;
                                    //                kvm_hostname = kvm_hostname2;
                                    //                kvm_pwd = kvm_pwd2;
                                    //                create_on_hostname = create_on_hostname2;
                                    //                kvm_memory1 = kvm_memory2;
                                    //            }
                                    //            else if (kvm_memory1 == kvm_memory2)
                                    //            {
                                    //                if (kvm_vm_cpu1 < kvm_vm_cpu2)
                                    //                {
                                    //                    kvm_account = kvm_account2;
                                    //                    kvm_dsname = kvm_dsname2;
                                    //                    kvm_hostname = kvm_hostname2;
                                    //                    kvm_pwd = kvm_pwd2;
                                    //                    create_on_hostname = create_on_hostname2;
                                    //                    kvm_memory1 = kvm_memory2;
                                    //                }
                                    //            }
                                    //        }
                                    //    }
                                    //
                                    //}
                                    #endregion
                                }
                                if (vmtype == "VMware")
                                {
                                    dbManager.CreateParameters(4);
                                    dbManager.AddParameters(0, "@order_area", order_area);
                                    dbManager.AddParameters(1, "@company_id", company_id);
                                    dbManager.AddParameters(2, "@vmtype", vmtype);
                                    dbManager.AddParameters(3, "@temp_id", temp_id);
                                    sql = @"select vmware_apiurl,vmware_datacenter_name,vmware_datastore_name,vmware_host_account,vmware_host_name,vmware_host_pwd,b.hostname as create_on_hostname,resource_pool_name,b.datacenter_name as create_on_datacentername,b.temp_id
                                from config_vm_host a left outer join vm_temp b on a.vmtype=b.vm_type
                                where area=@order_area and a.company_id=@company_id and vmtype=@vmtype and b.temp_id=@temp_id";
                                    ds = dbManager.ExecuteDataSet(CommandType.Text, sql);
                                    nCount = ds.Tables[0].Rows.Count;
                                    if (nCount == 1)
                                    {
                                        vmware_apiurl = ds.Tables[0].Rows[0]["vmware_apiurl"].ToString();
                                        string vmware_vcenter_ip = vmware_apiurl.Split('/')[2];
                                        vmware_datacenter_name = ds.Tables[0].Rows[0]["vmware_datacenter_name"].ToString();
                                        vmware_datastore_name = ds.Tables[0].Rows[0]["vmware_datastore_name"].ToString();
                                        vmware_host_account = ds.Tables[0].Rows[0]["vmware_host_account"].ToString();
                                        vmware_host_name = ds.Tables[0].Rows[0]["vmware_host_name"].ToString();
                                        vmware_host_pwd = CryptoAES.decrypt(ds.Tables[0].Rows[0]["vmware_host_pwd"].ToString(), "GccA@stanchengGg");
                                        vmware_host_encryp_pwd = ds.Tables[0].Rows[0]["vmware_host_pwd"].ToString();
                                        create_on_hostname = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();
                                        create_on_datacentername = ds.Tables[0].Rows[0]["create_on_datacentername"].ToString();
                                        resource_pool_name = Convert.ToString(ds.Tables[0].Rows[0]["resource_pool_name"]);
                                        //string vmware_usage = vm_useage.get_VMware_HOST_Usage(vmware_vcenter_ip, vmware_host_name, vmware_host_account, vmware_host_pwd);
                                        //string vmware_vm_usage = vm_useage.get_VMware_VM_Usage(vmware_apiurl,vmware_host_account,vmware_host_pwd,vmware_datacenter_name,vmware_host_name);

                                        /////////06/19  add
                                        string[] guidf0 = vmapi.init(vmware_apiurl, vmware_host_account, vmware_host_pwd, vmware_datacenter_name, true).Split(':');
                                        string[] guidf1 = guidf0[2].Split('\'');
                                        guid = guidf1[1];
                                        string nic_name1 = vmapi.getHostNetworkList(guid, vmware_datacenter_name, vmware_host_name);
                                        Int32 vm_count = Regex.Split(nic_name1, "\"message\":")[1].Split(',').Count() / 2;
                                        for (int vc = 1; vc <= vm_count; vc++)
                                        {
                                            if (exist_group_flag != true)
                                            {
                                                for (int nic_count = 0; nic_count <= add_nic_num; nic_count++)
                                                {
                                                    if (vlan_id[nic_count] != (Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[vc].Split('}')[0].Split(',')[1]).Split('\"')[3])
                                                    {
                                                        exist_group_flag = false;
                                                    }
                                                    else
                                                    {
                                                        string vlan_id1 = vlan_id[nic_count];
                                                        virNetworkName = Regex.Split(nic_name1, "\"message\":")[1].Split('[')[1].Split(']')[0].Split('{')[vc].Split('}')[0].Split(',')[0].Split('\"')[3];
                                                        virNetworkName_m = Regex.Split(nic_name1, "\"message\":")[1].Replace("\"", "").Replace("{", "").Replace("[", "").Replace("}", "").Replace("]", "").Replace(")", "").Replace(":", ",").Split(',');
                                                        int count = 0;
                                                        virNetworkName_st[] host_nic_and_vlan = new virNetworkName_st[virNetworkName_m.Count() / 4];
                                                        for (int ii = 3; ii <= virNetworkName_m.Count(); ii = ii + 4)
                                                        {
                                                            host_nic_and_vlan[count].vlan_id = virNetworkName_m[ii];
                                                            host_nic_and_vlan[count].network_name = virNetworkName_m[ii - 2];

                                                            count++;

                                                            //if (ii != virNetworkName_m.Count()-1)
                                                            //{
                                                            //    vlan_id2 += "[" + virNetworkName_m[ii] + "," + virNetworkName_m[ii - 2] + "]" + ",";
                                                            //}
                                                            //else
                                                            //{
                                                            //    vlan_id2 += "[" + virNetworkName_m[ii] + "," + virNetworkName_m[ii - 2] + "]";
                                                            //}
                                                        }
                                                        for (int iii = 0; iii < vlan_id.Count(); iii++)
                                                        {
                                                            for (int ii = 0; ii < host_nic_and_vlan.Count(); ii++)
                                                            {
                                                                if (vlan_id[iii] == host_nic_and_vlan[ii].vlan_id)
                                                                {
                                                                    vlan_id[iii] = host_nic_and_vlan[ii].vlan_id;
                                                                }
                                                            }
                                                        }
                                                        exist_group_flag = true;
                                                        create_flag = true;
                                                    }
                                                }
                                            }
                                        }
                                        /////////06/19  add
                                    }
                                    //else if (nCount > 1)
                                    //{
                                    //    int vmware_memory1 = 0;
                                    //    int vmware_memory2 = 0;
                                    //    int vmware_vm_cpu1 = 0;
                                    //    int vmware_vm_cpu2 = 0;
                                    //    for (int i = 0; i < nCount; i++)
                                    //    {
                                    //        string vmware_vm_usage_memory = "";
                                    //        string vmware_useage = "";
                                    //        string vmware_vm_usage_memory2 = "";
                                    //        string vmware_host_account2 = "";
                                    //        string vmware_datastore_name2 = "";
                                    //        string vmware_datacenter_name2 = "";
                                    //        string vmware_apiurl2 = "";
                                    //        string vmware_host_name2 = "";
                                    //        string vmware_host_pwd2 = "";
                                    //        string vmware_useage2 = "";
                                    //        string vmware_host_encryp_pwd2 = "";
                                    //        string create_on_hostname2 = "";
                                    //        string create_on_datacentername2 = "";
                                    //        string resource_pool_name2 = "";
                                    //        if (i == 0)
                                    //        {
                                    //            vmware_host_account = ds.Tables[0].Rows[i]["vmware_host_account"].ToString();
                                    //            vmware_datastore_name = ds.Tables[0].Rows[i]["vmware_datastore_name"].ToString();
                                    //            vmware_datacenter_name = ds.Tables[0].Rows[i]["vmware_datacenter_name"].ToString();
                                    //            vmware_apiurl = ds.Tables[0].Rows[i]["vmware_apiurl"].ToString();
                                    //            string vmware_vcenter_ip = vmware_apiurl.Split('/')[2];
                                    //            vmware_host_name = ds.Tables[0].Rows[i]["vmware_host_name"].ToString();
                                    //            vmware_host_pwd = CryptoAES.decrypt(ds.Tables[0].Rows[i]["vmware_host_pwd"].ToString(), "GccA@stanchengGg");
                                    //            vmware_host_encryp_pwd = ds.Tables[0].Rows[i]["vmware_host_pwd"].ToString();
                                    //            create_on_hostname = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();
                                    //            create_on_datacentername = ds.Tables[0].Rows[0]["create_on_datacentername"].ToString();
                                    //            resource_pool_name = Convert.ToString(ds.Tables[0].Rows[0]["resource_pool_name"]);
                                    //            vmware_useage = ws.get_VMware_HOST_Usage(vmware_vcenter_ip, vmware_host_name, vmware_host_account, vmware_host_pwd);
                                    //            vmware_vm_usage_memory = ws.get_VMware_VM_Usage(vmware_apiurl, vmware_host_account, vmware_host_pwd, vmware_datacenter_name, vmware_host_name);
                                    //            string vmware_host_memory = vmware_useage.Split(':')[1].Split(']')[0].Trim();
                                    //            string vmware_vm_cpu = vmware_vm_usage_memory.Split(':')[2].Trim();
                                    //            string vmware_vm_memory = vmware_vm_usage_memory.Split(':')[1].Split(' ')[1].Split('G')[0].Trim();
                                    //            vmware_memory1 = (Convert.ToInt32(vmware_host_memory)) - (Convert.ToInt32(vmware_vm_memory));
                                    //            vmware_vm_cpu1 = (Convert.ToInt32(vmware_vm_cpu));
                                    //        }
                                    //        //else if (i > 0)
                                    //        //{
                                    //        //    vmware_host_account2 = ds.Tables[0].Rows[i]["vmware_host_account"].ToString();
                                    //        //    vmware_datastore_name2 = ds.Tables[0].Rows[i]["vmware_datastore_name"].ToString();
                                    //        //    vmware_datacenter_name2 = ds.Tables[0].Rows[i]["vmware_datacenter_name"].ToString();
                                    //        //    vmware_apiurl2 = ds.Tables[0].Rows[i]["vmware_apiurl"].ToString();
                                    //        //    string vmware_vcenter_ip = vmware_apiurl.Split('/')[2];
                                    //        //    vmware_host_name2 = ds.Tables[0].Rows[i]["vmware_host_name"].ToString();
                                    //        //    vmware_host_pwd2 = CryptoAES.decrypt(ds.Tables[0].Rows[i]["vmware_host_pwd"].ToString(), "GccA@stanchengGg");
                                    //        //    vmware_host_encryp_pwd2 = ds.Tables[0].Rows[i]["vmware_host_pwd"].ToString();
                                    //        //    create_on_hostname2 = ds.Tables[0].Rows[0]["create_on_hostname"].ToString();
                                    //        //    create_on_datacentername2 = ds.Tables[0].Rows[0]["create_on_datacentername"].ToString();
                                    //        //    resource_pool_name2 = Convert.ToString(ds.Tables[0].Rows[0]["resource_pool_name"]);
                                    //        //    vmware_useage2 = ws.get_VMware_HOST_Usage(vmware_vcenter_ip, vmware_host_name2, vmware_host_account2, vmware_host_pwd2);
                                    //        //    vmware_vm_usage_memory2 = ws.get_VMware_VM_Usage(vmware_apiurl2, vmware_host_account2, vmware_host_pwd2, vmware_datacenter_name2, vmware_host_name2);
                                    //        //    string vmware_host_memory = vmware_useage2.Split(':')[1].Split(']')[0].Trim();
                                    //        //    string vmware_vm_cpu = vmware_vm_usage_memory2.Split(':')[2].Trim();
                                    //        //    string vmware_vm_memory = vmware_vm_usage_memory2.Split(':')[1].Split(' ')[1].Split('G')[0].Trim();
                                    //        //    vmware_memory2 = (Convert.ToInt32(vmware_host_memory)) - (Convert.ToInt32(vmware_vm_memory));
                                    //        //    vmware_vm_cpu2 = (Convert.ToInt32(vmware_vm_cpu));
                                    //        //    if (vmware_memory1 < vmware_memory2)
                                    //        //    {
                                    //        //        vmware_host_account = vmware_host_account2;
                                    //        //        vmware_datastore_name = vmware_datastore_name2;
                                    //        //        vmware_datacenter_name = vmware_datacenter_name2;
                                    //        //        vmware_apiurl = vmware_apiurl2;
                                    //        //        vmware_host_name = vmware_host_name2;
                                    //        //        vmware_host_pwd = vmware_host_pwd2;
                                    //        //        vmware_host_encryp_pwd = vmware_host_encryp_pwd2;
                                    //        //        create_on_hostname = create_on_hostname2;
                                    //        //        create_on_datacentername = create_on_datacentername2;
                                    //        //        resource_pool_name = resource_pool_name2;
                                    //        //        vmware_memory1 = vmware_memory2;
                                    //        //    }
                                    //        //    else if (vmware_memory1 == vmware_memory2)
                                    //        //    {
                                    //        //        if (vmware_vm_cpu1 < vmware_vm_cpu2)
                                    //        //        {
                                    //        //            vmware_host_account = vmware_host_account2;
                                    //        //            vmware_datastore_name = vmware_datastore_name2;
                                    //        //            vmware_datacenter_name = vmware_datacenter_name2;
                                    //        //            vmware_apiurl = vmware_apiurl2;
                                    //        //            vmware_host_name = vmware_host_name2;
                                    //        //            vmware_host_pwd = vmware_host_pwd2;
                                    //        //            vmware_host_encryp_pwd = vmware_host_encryp_pwd2;
                                    //        //            create_on_hostname = create_on_hostname2;
                                    //        //            create_on_datacentername = create_on_datacentername2;
                                    //        //            resource_pool_name = resource_pool_name2;
                                    //        //            vmware_memory1 = vmware_memory2;
                                    //        //        }
                                    //        //    }
                                    //        //}
                                    //    }
                                    //}

                                }

                                ws.Inset_Percent(order_id, "20", "");

                                vmapi.Timeout = 10000000;
                                if (vmtype == "VMware")
                                {
                                    string[] vcenter_ip_sp1 = vmware_apiurl.Split('/');
                                    string vcenter_ip = vcenter_ip_sp1[2];
                                    string[] guidf0 = vmapi.init(vmware_apiurl, vmware_host_account, vmware_host_pwd, vmware_datacenter_name, true).Split(':');
                                    string[] guidf1 = guidf0[2].Split('\'');
                                    guid = guidf1[1];
                                    //string[] VMWare_VFT_sp0 = vmapi.createVMFromTemplate(guid, vpath, create_on_hostname, create_on_datacentername, order_id, vmware_host_name, vmware_datacenter_name, resource_pool_name, vmware_datastore_name).Split(':');
                                    //string[] VMWare_VFT_sp1 = VMWare_VFT_sp0[1].Split(',');
                                    string VMWare_VFT_F = "false";// VMWare_VFT_sp1[0];
                                    if (VMWare_VFT_F == "false")
                                    {

                                        //ws.Inset_Percent(order_id, "35", "");
                                        //ws.set_create_on_host(order_id, vmware_host_name);
                                        //vmapi.configVMCPUNum(guid, vmware_datacenter_name, vmware_host_name, order_id, cpu);
                                        ////vmapi.configVMMemory(guid, vmware_datacenter_name, vmware_host_name, order_id, ram);
                                        //if (hdSize != "") //remove HD and add HD
                                        //{
                                        //    vmapi.removeVMDisk(guid, vmware_datacenter_name, vmware_datastore_name, vmware_datacenter_name, order_id, "1");
                                        //    vmapi.addVMDisk(guid, vmware_datacenter_name, vmware_host_name, vmware_datastore_name, order_id, (int.Parse(hdSize) * 1000).ToString());
                                        //}
                                        //VM_set_adapter(vlan_id, virNetworkName_m, guid, vmware_datacenter_name, vmware_host_name, order_id); //暫時 FOR VMWARE   setting adapter. write by jedi

                                        string[] VMWare_Power_on_sp0 = vmapi.powerOnVM(guid, vmware_datacenter_name, vmware_host_name, order_id).Split(':');
                                        string[] VMWare_Power_on_sp1 = VMWare_Power_on_sp0[1].Split(',');
                                        string VMWare_Power_on_F = VMWare_Power_on_sp1[0];
                                        if (VMWare_Power_on_F == "true")
                                        {
                                            ws.set_create_on_host(order_id, vmware_host_name);
                                            RunspaceInvoke invoker = new RunspaceInvoke();
                                            invoker.Invoke("Set-ExecutionPolicy Unrestricted");
                                            System.Threading.Thread.Sleep(1000);
                                            string[] url0 = vmware_apiurl.Split('/');
                                            vmware_apiurl = url0[2];
                                            //System.Threading.Thread.Sleep(240000);
                                            string vm_network_name = vmapi.getVMNICNetworkList(guid, vmware_datacenter_name, vmware_host_name, order_id).Split(':')[3].Split('"')[1];
                                            string vm_ip = vmapi.getVMIpAndMac(guid, vmware_datacenter_name, vmware_host_name, order_id, vm_network_name).Split(':')[2].Split('"')[1];

                                            if (os == "0")//For MicroSoft
                                            {
                                                System.Threading.Thread.Sleep(1000);
                                                invoker.Invoke("Set-Item WSMan:\\localhost\\Client\\TrustedHosts " + vm_ip + " -Concatenate -force");
                                                // TODO: do not write account/password into the script
                                                string pingvm = @"$username = ""User""
                                                                $account = """ + vm_account + @"""
                                                                $password = ConvertTO-SecureString """ + vm_password + @""" -asplaintext -Force
                                                                $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $account, $password
                                                                Invoke-Command -ComputerName " + vm_ip + @" -Authentication default" +
                                                                @" -credential $cred " +
                                                                @" -ScriptBlock {" +
                                                                    @"$FileExists = Test-Path ""c:\\AutoProvision"";" +
                                                                    @"If ($FileExists -eq $False){" +
                                                                        @"mkdir ""c:\\AutoProvision"";"
                                                                        + @"echo """ + order_id + " " + group_id + @""" >C:\\AutoProVision\\vmname.txt;"
                                                                        + @"echo ""timeout 30"""
                                                                        + @" `n 'msiexec /forcerestart /i  c:\AutoProVision\VMConfig.msi ALLUSERS=1 DB_Server=""" + db_server + @""" EmailAccount=""" + EmailAccount + "\" EmailPassword=\"" + EmailPassword + "\" smtphost=\"" + smtphost + "\" AutoProvision_WS_url=\"" + AutoProvision_WS_url + "\" /qn'"
                                                                        + @" `n ""timeout 10"" "
                                                                        + @"`n ""restart"" "
                                                                        + @"`n | "
                                                                        + @"Set-Content C:\AutoProVision\vmconfig.bat;"
                                                                        + @"$File = ""c:\AutoProvision\VMConfig.msi"";"
                                                                        + @"$ftp = """ + ftp_folder + "\\VMConfig.msi\";"
                                                                        + @"$File3 = ""c:\AutoProvision\creboot2.exe"";"
                                                                        + @"$ftp3 = """ + ftp_folder + @"\creboot2.exe"";"
                                                                        + @"$File4 = ""c:\AutoProvision\set_ip.exe"";"
                                                                        + @"$ftp4 = """ + ftp_folder + @"\set_ip.exe"";"
                                                                        + @"$webclient = New-Object System.Net.WebClient;"
                                                                        + @"$Username = """ + ConfigurationManager.AppSettings["ftpUsername"] + "\";"
                                                                        + @"$Password = """ + ConfigurationManager.AppSettings["ftpPassword"] + "\";"
                                                                        + @"$webclient = New-Object System.Net.WebClient;"
                                                                        + @"$WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password);"
                                                                        + @"$webclient.DownloadFile($ftp, $File);"
                                                                        + @"$webclient.DownloadFile($ftp3, $File3);"
                                                                        + @"$webclient.DownloadFile($ftp4, $File4);"
                                                                        + @"Start-Sleep -s 10 ; "
                                                                    + @"}"
                                                                    + @"c:\AutoProvision\vmconfig.bat;"
                                                                + "}";
                                                //使用POWERSHELL 連至VM並對此台VM下達Create一個vmname.txt內容放入訂單編號及群組ID,下載FTP上之AGENT的檔案安裝完AGENT後並重開機。
                                                execute(pingvm);
                                            }
                                            if (os == "1") //For Linux
                                            {
                                                string hostSshUserName = "******";
                                                string hostSshPassword = "******";
                                                string agentFolderPath = "/opt/AutoConfigAgent";
                                                // TODO: retrive url from outside
                                                string wsUrl = AutoProvision_WS_url;
                                                string hypervisorIpAddress = vmware_host_name;
                                                string ftpUsername = ftp_user;
                                                string ftpPassword = ftp_pwd;
                                                string agentFtpPath = "/AutoConfigAgent";
                                                string vmProvisionName = order_id;

                                                executeLinuxScript(vm_ip, hostSshUserName, hostSshPassword, 22,
                                                agentFolderPath, wsUrl, hypervisorIpAddress, ftp, ftpUsername, ftpPassword, agentFtpPath, vmProvisionName);
                                            }
                                            ws.Inset_Percent(order_id, "50", "");
                                        }
                                    }
                                }

                                if (vmtype == "KVM")
                                {
                                    string[] guidf0 = vmapi.init(kvm_hostname, kvm_dsname, kvm_account, kvm_pwd).Split(':');
                                    string[] guidf1 = guidf0[2].Split('\'');
                                    guid = guidf1[1];
                                    string[] KVM_VFT_sp0 = vmapi.createVMFromTemplate(guid, vpath, create_on_hostname, "", order_id, kvm_hostname, "", "", kvm_dsname).Split(':');
                                    string[] KVM_VFT_sp1 = KVM_VFT_sp0[1].Split(',');
                                    string KVM_VFT_F = KVM_VFT_sp1[0];
                                    if (KVM_VFT_F == "true")
                                    {
                                        dbManager.Open();
                                        ws.Inset_Percent(order_id, "35", "");
                                        ws.set_create_on_host(order_id, vmware_host_name);
                                        vmapi.configVMCPUNum(guid, "", kvm_hostname, order_id, cpu);
                                        vmapi.configVMMemory(guid, "", kvm_hostname, order_id, ram);
                                        vmapi.adjustVMNIC(guid, "", kvm_hostname, order_id, "Network adapter 1", virNetworkName);
                                        string[] KVM_Power_on_sp0 = vmapi.powerOnVM(guid, "", kvm_hostname, order_id).Split(':');
                                        string[] KVM_Power_on_sp1 = KVM_Power_on_sp0[1].Split(',');
                                        string KVM_Power_on_F = KVM_Power_on_sp1[0];

                                        if (KVM_Power_on_F == "true")
                                        {
                                            ws.set_create_on_host(order_id, kvm_hostname);
                                            RunspaceInvoke invoker = new RunspaceInvoke();
                                            invoker.Invoke("Set-ExecutionPolicy Unrestricted");
                                            System.Threading.Thread.Sleep(240000);
                                            string vm_network_name = vmapi.getVMNICNetworkList(guid, "", kvm_hostname, order_id).Split(':')[3].Split('"')[1];
                                            string vm_ip = vmapi.getVMIpAndMac(guid, "", kvm_hostname, order_id, vm_network_name).Split(':')[2].Split('"')[1];
                                            if (os == "0")//For MicroSoft
                                            {
                                                invoker.Invoke("Set-Item WSMan:\\localhost\\Client\\TrustedHosts " + vm_ip + " -Concatenate -force");
                                                string pingvm = "$username = \"User\" \n" +
                                                                "$account = \"User\" \n" +
                                                                "$password = ConvertTO-SecureString \"Passw0rd\" -asplaintext -Force \n" +
                                                                "$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $account, $password \n" +
                                                                "Invoke-Command -ComputerName " + vm_ip + "  -Authentication default -credential $cred -ScriptBlock {$FileExists = Test-Path \"c:\\AutoProvision\";If ($FileExists -eq $False){mkdir \"c:\\AutoProvision\";echo \"" + order_id + "\">C:\\AutoProVision\\vmname.txt;echo \"timeout 30\" `n 'msiexec /forcerestart /i  c:\\AutoProVision\\VMConfig.msi ALLUSERS=1 DB_Server=\"" + db_server + "\" EmailAccount=\"" + EmailAccount + "\" EmailPassword=\"" + EmailPassword + "\" smtphost=\"" + smtphost + "\" AutoProvision_WS_url=\"" + AutoProvision_WS_url + "\" /qn' `n \"timeout 10\" `n \"restart\" `n | Set-Content C:\\AutoProVision\\vmconfig.bat;$File = \"c:\\AutoProvision\\VMConfig.msi\";$ftp = \"" + ftp_folder + "\\VMConfig.msi\";$File3 = \"c:\\AutoProvision\\creboot2.exe\";$ftp3 = \"" + ftp_folder + "\\creboot2.exe\";$File4 = \"c:\\AutoProvision\\set_ip.exe\";$ftp4 = \"" + ftp_folder + "\\set_ip.exe\";$webclient = New-Object System.Net.WebClient;$Username = \"" + ConfigurationManager.AppSettings["ftpUsername"] + "\";$Password = \"" + ConfigurationManager.AppSettings["ftpPassword"] + "\";$webclient = New-Object System.Net.WebClient;$WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password);$webclient.DownloadFile($ftp, $File);$webclient.DownloadFile($ftp3, $File3);$webclient.DownloadFile($ftp4, $File4);Start-Sleep -s 10 ; }c:\\AutoProvision\\vmconfig.bat;}";
                                                execute(pingvm);
                                            }
                                            if (os == "1") //For Linux
                                            {
                                                string hostSshUserName = "******";
                                                string hostSshPassword = "******";
                                                string agentFolderPath = "/opt/AutoConfigAgent";
                                                // TODO: retrive url from outside
                                                string wsUrl = AutoProvision_WS_url;
                                                string hypervisorIpAddress = kvm_hostname;
                                                string ftpUsername = ftp_user;
                                                string ftpPassword = ftp_pwd;
                                                string agentFtpPath = "/AutoConfigAgent";
                                                string vmProvisionName = order_id;

                                                executeLinuxScript(vm_ip, hostSshUserName, hostSshPassword, 22,
                                                agentFolderPath, wsUrl, hypervisorIpAddress, ftp, ftpUsername, ftpPassword, agentFtpPath, vmProvisionName);
                                            }
                                            ws.Inset_Percent(order_id, "50", "");
                                        }
                                    }

                                }
                            }
                            #endregion
                        }
                    }
                    catch (Exception)
                    {
                        dbManager.Dispose();
                        ws.Dispose();
                    }
                    finally
                    {
                        dbManager.Dispose();
                        ws.Dispose();
                    }

                }
            }
            catch (Exception)
            {
                dbManager.Dispose();
                ws.Dispose();
            }
            finally
            {
            }
        }
Exemplo n.º 26
0
    protected void Button3_Click(object sender, EventArgs e)
    {
        Button1.Enabled = true;
        commit.Enabled = false;
        rollback.Enabled = false;
        GridView1.DataSource = null;
        GridView1.DataBind();
        msg.Text = "";
        //SqlConnection.ClearAllPools();
        switch (DropDownList1.SelectedItem.Text)
        {
            case "SQL Server":
                string s = "Data Source=localhost;Initial Catalog=master" + "; User ID=sa; Password=***;";
                SqlConnection ProcConn = new SqlConnection(s);

                try
                {
                    ProcConn.Open();
                    SqlCommand cmd = new SqlCommand("spCreateUserDb", ProcConn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(
                            new SqlParameter("@sourceDb", DropDownList2.SelectedItem.Text));
                    cmd.Parameters.Add(
                            new SqlParameter("@destDb", User.Identity.Name + DropDownList2.SelectedItem.Text));
                    cmd.ExecuteNonQuery();
                    //msg.Text += "Database Created: " + User.Identity.Name + DropDownList2.SelectedItem.Text;
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";

                }
                catch (Exception)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database "+ DropDownList2.Text + " creation failed');</script>"));
                }
                finally
                {
                    if (ProcConn != null)
                    {
                        ProcConn.Close();
                    }

                }
                break;
            case "Access":

                RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
                try
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
                    {
                        runspace.Open();
                        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
                        Pipeline pipeline = runspace.CreatePipeline();
                        string scriptfile = "C:\\SourceDatabase\\Access\\powershellCreateDB.ps1";
                        //add a new script with arguments
                        Command myCommand = new Command(scriptfile);
                        CommandParameter SourceParam = new CommandParameter("source", DropDownList2.SelectedItem.Text);
                        CommandParameter TargetParam = new CommandParameter("target", User.Identity.Name);
                        myCommand.Parameters.Add(SourceParam);
                        myCommand.Parameters.Add(TargetParam);
                        pipeline.Commands.Add(myCommand);
                        // Execute PowerShell script; powershell should set-executionpolicy remotesigned.
                        // Otherwise Error: "File C:\SourceDatabase\Access\powershellCreateDB.ps1 cannot be loaded because running scripts is disabled on this system.
                        // For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170."
                        // error "AuthorizationManager check failed" caused by the version of 32bit or 64 bit, solution : resave it.
                        pipeline.Invoke();

                    }
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";
                }
                catch (Exception ex)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " creation failed');</script>"));
                    msg.Text = ex.Message;
                }
                break;
            case "MySQL":
                string str = "server=localhost;Database=" + DropDownList2.SelectedItem.Text + ";Uid=root;Pwd=***;";
                string file = "C:\\SourceDatabase\\MySQL\\" + DropDownList2.SelectedItem.Text + ".sql";
                try
                {
                    using (MySqlConnection conn = new MySqlConnection(str))
                    {
                        using (MySqlCommand cmd = new MySqlCommand())
                        {
                            cmd.CommandText = "DROP DATABASE IF EXISTS " + User.Identity.Name + DropDownList2.SelectedItem.Text;
                            cmd.Connection = conn;
                            conn.Open();
                            cmd.ExecuteNonQuery();
                            using (MySqlBackup mb = new MySqlBackup(cmd))
                            {
                                //cmd.Connection = conn;
                                //conn.Open();
                                mb.ImportInfo.TargetDatabase = User.Identity.Name + DropDownList2.SelectedItem.Text;
                                mb.ImportFromFile(file);
                            }
                        }
                    }
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";
                }
                catch (Exception ex)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " creation failed');</script>"));
                    output.Text = ex.Message;
                }
                break;

            case "PostgreSQL":
                string ps = "Server=127.0.0.1;Port=5432;Database=template1;User Id=postgres; Password=***;Pooling=false;";
                try
                {
                    using (NpgsqlConnection conn = new NpgsqlConnection(ps))
                    {
                        using (NpgsqlCommand cmd = new NpgsqlCommand())
                        {
                            cmd.CommandText = "DROP DATABASE IF EXISTS " + User.Identity.Name + DropDownList2.SelectedItem.Text;
                            cmd.Connection = conn;
                            conn.Open();
                            cmd.ExecuteNonQuery();
                            cmd.CommandText = "CREATE DATABASE " + User.Identity.Name + DropDownList2.SelectedItem.Text + " TEMPLATE " + DropDownList2.SelectedItem.Text;
                            cmd.ExecuteNonQuery();
                        }
                    }
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";
                }
                catch (Exception ex)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " creation failed');</script>"));
                    output.Text = ex.Message;
                }
                break;
            case "SQLite":
                RunspaceConfiguration SQLiterunspaceConfiguration = RunspaceConfiguration.Create();
                try
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(SQLiterunspaceConfiguration))
                    {
                        runspace.Open();
                        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
                        Pipeline pipeline = runspace.CreatePipeline();
                        string scriptfile = "C:\\SourceDatabase\\SQLite\\powershellCreateDB.ps1";
                        //add a new script with arguments
                        Command myCommand = new Command(scriptfile);
                        CommandParameter SourceParam = new CommandParameter("source", DropDownList2.SelectedItem.Text);
                        CommandParameter TargetParam = new CommandParameter("target", User.Identity.Name);
                        myCommand.Parameters.Add(SourceParam);
                        myCommand.Parameters.Add(TargetParam);
                        pipeline.Commands.Add(myCommand);
                        // Execute PowerShell script; powershell should set-executionpolicy remotesigned.
                        // Otherwise Error: "File C:\SourceDatabase\Access\powershellCreateDB.ps1 cannot be loaded because running scripts is disabled on this system.
                        // For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170."
                        // error "AuthorizationManager check failed" caused by the version of 32bit or 64 bit, solution : resave it.
                        pipeline.Invoke();

                    }
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " has been created');</script>"));
                    output.Text = "Database " + DropDownList2.SelectedItem.Text + " has been created";
                }
                catch (Exception ex)
                {
                    Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Database " + DropDownList2.Text + " creation failed');</script>"));
                    msg.Text = ex.Message;
                }
                break;
            case "Oracle":
            case "DB2":
                Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Error\\nDataBase already exists, no need to create.');</script>"));
                break;
            default:
                //msg.Text = "no such database";
                Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Error\\nPlease choose a database');</script>"));
                break;
        }
    }
Exemplo n.º 27
0
        //Based on Jared Atkinson's And Justin Warner's Work
        public static string RunPSCommand(string cmd)
        {
            //Init stuff
            InitialSessionState initial = InitialSessionState.CreateDefault();
            // Replace PSAuthorizationManager with a null manager which ignores execution policy
            initial.AuthorizationManager = new System.Management.Automation.AuthorizationManager("MyShellId");

            Runspace runspace = RunspaceFactory.CreateRunspace(initial);
            runspace.Open();
            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            Pipeline pipeline = runspace.CreatePipeline();

            //Add commands
            if (cmd.IndexOf("Invoke-Shellcode", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_Shellcode());
            }
            if (cmd.IndexOf("Invoke-Mimikatz", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_Mimikatz());
            }
            if (cmd.IndexOf("Invoke-ReflectivePEInjection", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_ReflectivePEInjection());
            }
            if (cmd.IndexOf("Invoke-PsExec", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_PsExec());
            }
            if (cmd.IndexOf("Invoke-TokenManipulation", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_TokenManipulation());
            }
            if (cmd.IndexOf("PowerCat", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.PowerCat());
            }
            if (cmd.IndexOf("Invoke-PsUACme", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_PsUACme());
            }
            if (cmd.IndexOf("Invoke-Encode", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_Encode());
            }

            pipeline.Commands.AddScript(Resources.Invoke_PowerView());
            pipeline.Commands.AddScript(Resources.Invoke_PowerUp());
            pipeline.Commands.AddScript(cmd);

            //Prep PS for string output and invoke
            pipeline.Commands.Add("Out-String");
            Collection<PSObject> results = pipeline.Invoke();
            runspace.Close();

            //Convert records to strings
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.Append(obj);
            }
            return stringBuilder.ToString();
        }
        /// <summary>
        /// main initialisation routine for the <see cref="Runspace"/>
        /// </summary>
        /// <param name="snapin"><see cref="SnapIn"/> to be initialized together with the <see cref="Runspace"/></param>
        private void InitRunSpace(SnapIn snapin)
        {
            const string MethodName = "InitRunSpace";
            Debug.WriteLine(MethodName + "(" + snapin + ")" + ":entry", ClassName);

            // create a new config from scratch
            PSSnapInException snapOutput = null;
            this.runSpaceConfig = RunspaceConfiguration.Create();

            switch (snapin)
            {
                case SnapIn.Exchange:
                    var serverVersion = GetExchangeServerVersion();
                    switch (serverVersion)
                    {
                        case ExchangeVersion.E2007:
                            // used for force load of the exchange dll's
                            AppDomain.CurrentDomain.AssemblyResolve +=
                                             new ResolveEventHandler(ExchangeUtility.AssemblyResolver2007);

                            this.runSpaceConfig.AddPSSnapIn(Exchange2007SnapIn, out snapOutput);
                            break;
                        case ExchangeVersion.E2010:
                            // used for force load of the exchange dll's
                            AppDomain.CurrentDomain.AssemblyResolve +=
                                             new ResolveEventHandler(ExchangeUtility.AssemblyResolver2010);

                            this.runSpaceConfig.AddPSSnapIn(Exchange2010SnapIn, out snapOutput);
                            break;
                    }
                    break;
            }

            // check snapOutput
            if (snapOutput != null)
            {
                throw snapOutput;
            }

            // create the real Runspace and open it for processing
            this.runSpace = RunspaceFactory.CreateRunspace(this.runSpaceConfig);
            this.runSpace.Open();
            this.runSpaceInvoke = new RunspaceInvoke(this.runSpace);

            Debug.WriteLine(MethodName + ":exit", ClassName);
        }
Exemplo n.º 29
0
 /// <summary>
 /// Create powershell runspace with pipeline
 /// </summary>
 /// <param name="iss"></param>
 /// <returns></returns>
 private Pipeline CreateRunspaceWithPipeline( InitialSessionState iss = null)
 {
     Runspace runspace; if (null != iss) runspace = RunspaceFactory.CreateRunspace(iss); else runspace = RunspaceFactory.CreateRunspace(); runspace.Open();  RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); runSpaceInvoker.Invoke("Set-ExecutionPolicy RemoteSigned -Scope Process");  Pipeline pipeline = runspace.CreatePipeline();  return pipeline;
 }
Exemplo n.º 30
0
        internal Collection<PSObject> ExecuteRemoteShellCommand(Runspace runSpace, string hostName, Command cmd, out object[] errors, params string[] moduleImports)
        {
            Command invokeCommand = new Command("Invoke-Command");
            invokeCommand.Parameters.Add("ComputerName", hostName);

            RunspaceInvoke invoke = new RunspaceInvoke();

            string commandString = moduleImports.Any() ? string.Format("import-module {0};", string.Join(",", moduleImports)) : string.Empty;

            commandString += cmd.CommandText;

            if (cmd.Parameters != null && cmd.Parameters.Any())
            {
                commandString += " " +
                                 string.Join(" ",
                                     cmd.Parameters.Select(x => string.Format("-{0} {1}", x.Name, x.Value)).ToArray());
            }

            ScriptBlock sb = invoke.Invoke(string.Format("{{{0}}}", commandString))[0].BaseObject as ScriptBlock;

            invokeCommand.Parameters.Add("ScriptBlock", sb);            

            return ExecuteShellCommand(runSpace, invokeCommand, false, out errors);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Performs the check.
        /// </summary>
        /// <returns>
        ///   <c>true</c> if the check succeeds otherwise, <c>false</c>.
        /// </returns>
        public override bool PerformCheck()
        {
            var runspaceConfiguration = RunspaceConfiguration.Create();

            using (var runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
            {
                runSpace.Open();
                using (var runSpaceInvoker = new RunspaceInvoke(runSpace))
                {
                    runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

                    using (var pipeLine = runSpace.CreatePipeline())
                    {
                        var scriptFileCommand = new Command(Path);

                        if (!string.IsNullOrWhiteSpace(ScriptParameters))
                        {
                            ScriptParameters.Split(' ')
                                            .ToList()
                                            .ForEach(
                                                token =>
                                                scriptFileCommand.Parameters.Add(new CommandParameter(null, token)));
                        }

                        pipeLine.Commands.Add(scriptFileCommand);

                        var results = pipeLine.Invoke();

                        if (results.Count > 0)
                        {
                            try
                            {
                                return (bool) results[0].BaseObject;
                            }
                            catch
                            {
                                return false;
                            }
                        }
                        return false;
                    }
                }
            }
        }
Exemplo n.º 32
0
        public static IEnumerable<string> ExecutePowershellModule(this Robot robot, string moduleCommand)
        {
            var scriptFolder = robot.GetConfigVariable("MMBOT_POWERSHELL_SCRIPTSPATH");

            var commandArgs = moduleCommand.Split(' ');
            var scriptName = commandArgs[0];
            var parameters = string.Empty;
            for (int i = 1; i < commandArgs.Length; i++)
                parameters += commandArgs[i] + " ";

            var scriptPath = Path.Combine(scriptFolder, scriptName + ".psm1");

            if (!File.Exists(scriptPath))
            {
                yield return "Command not found";
            }
            else
            {
                var host = new MMBotHost(robot);
                using (var runspace = RunspaceFactory.CreateRunspace(host))
                {
                    runspace.Open();
                    using (var invoker = new RunspaceInvoke(runspace))
                    {
                        Collection<PSObject> psObjects = new Collection<PSObject>();
                        invoker.Invoke(string.Format("Import-Module {0}", scriptPath));
                        try
                        {
                            IList errors;
                            psObjects = invoker.Invoke(string.Format("{0} {1}", scriptName, parameters), null, out errors);
                            if (errors.Count > 0)
                            {
                                string errorString = string.Empty;
                                foreach (var error in errors)
                                    errorString += error.ToString();

                                psObjects.Add(new PSObject(errorString));
                            }

                        }
                        catch (Exception ex)
                        {
                            psObjects.Add(new PSObject(ex.Message));
                        }

                        foreach (var psObject in psObjects)
                        {
                            yield return psObject.ConvertToString();
                        }
                    }
                }
            }
            
        }
Exemplo n.º 33
0
 public void ProcessMessage(IChatMessage message, IChatResponse response)
 {
     // parse the command so we know what to run
     var command = this.ParseCommand(message.CommandText);
     if (command == null)
     {
         response.Write("Erk! Not sure what to say to that.");
         return;
     }
     // check the script module exists
     var modulePath = this.GetFullModulePath(command.Command);
     if (!File.Exists(modulePath))
     {
         response.Write("Unknown command! Try \"@autobot Get-Help\" instead.");
         return;
     }
     // initialise the host
     var host = new Host.Host(this.Logger);
     // add a handler for OnWrite events so we can bubble them up to the chat session
     var hostUi = (host.UI as UserInterface);
     if (hostUi != null)
     {
         hostUi.OnWrite += (sender, value) => response.Write(value);
     }
     // create a new initial state with the script module loaded
     var state = InitialSessionState.CreateDefault();
     state.ImportPSModule(new string[] { modulePath });
     // run the script inside the host
     using (var runspace = RunspaceFactory.CreateRunspace(host, state))
     {
         runspace.Open();
         using (var invoker = new RunspaceInvoke(runspace))
         {
             try
             {
                 // execute the PowerShell function with the same name as the module
                 IList errors;
                 var psObjects = invoker.Invoke(string.Format("{0} {1}", command.Command, command.Parameters), null, out errors);
                 // handle any errors
                 if ((errors != null) && (errors.Count > 0))
                 {
                     var errorString = new System.Text.StringBuilder();
                     foreach (var error in errors)
                     {
                         errorString.AppendLine(error.ToString());
                     }
                     this.Logger.Error(string.Format("ERROR!: {0}", errorString.ToString()));
                     response.Write(string.Format("OOohhh, I got an error running {0}. It looks like this:", command));
                     response.Write(errorString.ToString());
                     return;
                 }
                 // write the result
                 foreach (var psObject in psObjects)
                 {
                     response.Write(this.SerializePSObject(psObject));
                 }
             }
             catch (Exception ex)
             {
                 this.Logger.Error("ERROR!: ", ex);
                 response.Write(string.Format("Urghhh!, that didn't taste nice!  There's a problem with me running the {0} script.", command));
                 response.Write(string.Format("Check you are calling the script correctly by using \"@autobot get-help {0}\"", command));
                 response.Write("If all else fails ask your administrator for the event/error log entry.");
             }
         }
     }
 }
Exemplo n.º 34
0
        protected Collection<PSObject> ExecuteRemoteScript(Runspace runSpace, string hostName, List<string> scripts, out object[] errors, params string[] moduleImports)
        {
            Command invokeCommand = new Command("Invoke-Command");

            if (!string.IsNullOrEmpty(hostName))
            {
                invokeCommand.Parameters.Add("ComputerName", hostName);
            }

            RunspaceInvoke invoke = new RunspaceInvoke();
            string commandString = moduleImports.Any() ? string.Format("import-module {0};", string.Join(",", moduleImports)) : string.Empty;

            commandString = string.Format("{0};{1}", commandString, string.Join(";", scripts.ToArray()));

            ScriptBlock sb = invoke.Invoke(string.Format("{{{0}}}", commandString))[0].BaseObject as ScriptBlock;

            invokeCommand.Parameters.Add("ScriptBlock", sb);

            return ExecuteShellCommand(runSpace, invokeCommand, false, out errors);
        }