public void tvCommands()
 {
     WOL.WakeOnLan(macAddress);
     if (wsClientKey != "none")
     {
         wsClient.Send("{\"type\":\"request\",\"id\":\"switchinput_" + msgCount + "\",\"uri\":\"ssap://tv/switchInput\",\"payload\":{\"inputId\":\"HDMI_1\"}}");
         _logger.Debug("Requesting Device switch to HDMI1 inside tvcommands Function");
         msgCount++;
     }
     else
     {
         _logger.Debug("wsClientKey is none so sleeping 5 seconds and trying again");
         Thread.Sleep(5000);
         if (wsClientKey != "none")
         {
             _logger.Debug("Requesting Device switch to HDMI1 inside tvcommands Function after pausing for 5 seconds.");
             wsClient.Send("{\"type\":\"request\",\"id\":\"switchinput_" + msgCount + "\",\"uri\":\"ssap://tv/switchInput\",\"payload\":{\"inputId\":\"HDMI_1\"}}");
             msgCount++;
         }
         else
         {
             Thread.Sleep(5000);
         }
     }
 }
Example #2
0
        public async Task <IActionResult> Acorda(string macAddress)
        {
            try
            {
                await WOL.WakeOnLan(macAddress);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
Example #3
0
        public static string CalculatePixels(string widthOrLength, string Measurement)
        {
            double.TryParse(widthOrLength, out double WOL);
            switch (Measurement.ToLower())
            {
            case "cm":
                break;

            case "ft":
                WOL = WOL / 0.032808;
                break;

            case "in":
                WOL = WOL / 12 / 0.032808;
                break;
            }
            WOL *= 1.5;
            return(WOL.ToString());
        }
Example #4
0
        bool ICommand.Run(string MessageText, SlackRTM.Events.Message RawMessage, bool IsTargeted, SlackRTM.Slack Instance)
        {
            /* ****
            * WOL.
            * ****/
            var match = Regex.Match(
                MessageText,
                // TODO: Use IsTargeted
                string.Concat("@", Instance.Self.Name, @":?\s+Wake (?<name>\w+)"),
                RegexOptions.IgnoreCase);

            if (match.Success)
            {
                NetworkData network  = Singleton <NetworkData> .Instance;
                var         LastHost = network.Find(match.Groups["name"].Value);
                Instance.SetLastHost(LastHost);
                Instance.SendMessage(RawMessage.Channel, string.Format("Waking {0}!", LastHost.FriendlyName));
                WOL.WakeOnLan(LastHost.HardwareAddress);
                return(true);
            }
            return(false);
        }
Example #5
0
        public void PsExec_Exec(string trigger, bool sync = false)
        {
            IEnumerable <LV_IP_Item> targets = CSV.Where(x => x.IsChecked == true);

            if (targets.Count() != 0)
            {
                if (trigger == "WOL" || trigger == "PING")
                {
                    ProgressBar.Maximum = targets.Count();
                }
                else
                {
                    ProgressBar.Maximum = targets.Where(x => x.Online == true).Count();
                }
                PsExec     psexec     = new PsExec(fileutils);
                PsShutdown psshutdown = new PsShutdown(fileutils);
                foreach (LV_IP_Item target in targets)
                {
                    if (target.IsChecked)
                    {
                        if (target.Online || trigger == "WOL" || trigger == "PING")
                        {
                            string batch = null;
                            URL_ShutdownAndMouse url_shutdownandmouse = new URL_ShutdownAndMouse(target.IP);
                            URL_Zkplay           url_zkplay;
                            switch (trigger)
                            {
                            case "CMD":
                                LV_UPLOAD.ItemsSource = null;
                                batch = "start \"\" \"" + psexec.version + "\" \\\\" + target.IP + " -u " + target.User + " -p " + target.Passwd + " cmd";
                                break;

                            case "EXEC":
                                batch = "start /MIN \"\" \"" + psexec.version + "\" \\\\" + target.IP + " -u " + target.User + " -p " + target.Passwd + " -d cmd /c \"\"" + TB_Batch_Destination.Text + TB_Batch_ExecBat.Text + "\" \"" + TB_Batch_Destination.Text + "\" " + target.IP + " " + TB_Batch_Other.Text + "\"";
                                break;

                            case "TASKKILL":
                                batch = "start /MIN \"\" \"" + psexec.version + "\" \\\\" + target.IP + " -u " + target.User + " -p " + target.Passwd + " taskkill /F /IM " + TB_Batch_Other.Text;
                                break;

                            case "MSTSC":
                                batch = "mstsc /v:" + target.IP;
                                break;

                            case "PING":
                                batch = "start \"\" ping " + target.IP + " -t";
                                break;

                            case "VNC":
                                VNC vnc = new VNC(fileutils);
                                if (TB_Batch_Other.Text != "baidu.com")
                                {
                                    fileutils.BinaryWrite(vnc.PasswdFilePath, StringExtensions.GetChunks(vnc.EncryptVNC(TB_Batch_Other.Text), 2));
                                }
                                batch = "start \"\" \"" + vnc.SoftPath + "\" -passwd \"" + vnc.PasswdFilePath + "\" " + target.IP;
                                break;

                            case "HTTP_SHUTDOWN":
                                batch = url_shutdownandmouse.shutdown;
                                break;

                            case "HTTP_RESTART":
                                batch = url_shutdownandmouse.restart;
                                break;

                            case "WOL":
                                WOL wol = new WOL(fileutils);
                                batch = "start /MIN \"\" \"" + wol.SoftPath + "\" " + target.Mac.Replace("-", "") + " " + target.IP + " 255.255.255.0 9";
                                break;

                            case "EXPLORER":
                                batch = @"start \\" + target.IP + @"\" + Regex.Replace(TB_Batch_Destination.Text, @":\\(资源管理器)?", @"$");
                                break;

                            case "SHUTDOWN":
                                batch = "start /MIN \"\" \"" + psshutdown.version + "\" -f -t 01 \\\\" + target.IP + " -u " + target.User + " -p " + target.Passwd;
                                break;

                            case "RESTART":
                                batch = "start /MIN \"\" \"" + psshutdown.version + "\" -r \\\\" + target.IP + " -u " + target.User + " -p " + target.Passwd;
                                break;

                            case "EternalBlue":
                                batch = "start /MIN \"\" \"" + fileutils.EquationExploitPath + "files\\Eternalblue-2.2.0.exe\" --InConfig \"" + fileutils.EquationExploitPath + "files\\Eternalblue-2.2.0.xml\" --TargetIp " + target.IP + " --TargetPort " + TB_TargetPort.Text + " --OutConfig \"" + fileutils.EquationExploitPath + @"logs\EB_" + target.IP + "_" + TB_TargetPort.Text + ".xml\"" + " --Target " + TB_TargetOS.Text;
                                break;

                            case "DoublePulsar":
                                batch = "start /MIN \"\" \"" + fileutils.EquationExploitPath + "files\\Doublepulsar-1.3.1.exe\" --InConfig \"" + fileutils.EquationExploitPath + "files\\Doublepulsar-1.3.1.xml\" --TargetIp " + target.IP + " --TargetPort " + TB_TargetPort.Text + " --OutConfig \"" + fileutils.EquationExploitPath + @"logs\DP_" + target.IP + "_" + TB_TargetPort.Text + ".xml\"" + " --Protocol " + TB_protocol.Text + " --Architecture " + TB_architecture.Text + " --Function " + LB_Function.SelectedItem.ToString() + " --DllPayload \"" + fileutils.EquationExploitDllsPath + LB_payloadDllname.SelectedItem.ToString() + "\" --payloadDllOrdinal " + TB_payloadDllOrdinal.Text + " --ProcessName " + LB_ProcessName.SelectedItem.ToString() + " --ProcessCommandLine " + TB_processCommandLine.Text + " --NetworkTimeout " + TB_NetworkTimeout.Text;
                                break;

                            case "HTTP_ZKPLAY_RESTART":
                                url_zkplay = new URL_Zkplay(target.IP);
                                batch      = url_zkplay.restart;
                                break;

                            case "ZKPLAY_UPLOAD":
                                LB_BAT_INNER.SelectedItem = "内容上传";
                                if (!Regex.Match(lv_ip_item.PlusbeZK, "zkplay||内容").Success)
                                {
                                    batch = "未指定Zkplay路径.";
                                }
                                else if (!File.Exists(TB_Batch_Other.Text.Split(';')[0]))
                                {
                                    batch = "未指定上传文件.";
                                }
                                else
                                {
                                    TB_Batch_Destination.Text = TB_Batch_Destination.Text + @"\UploadFiles";
                                    string[]       FileList = target.Other.Split(';');
                                    ZkplayPlayList ZKPList  = new ZkplayPlayList(this, target.IP);
                                    ZKPList.GetConfig();
                                    ZKPList.Add(FileList);
                                    batch = "PsExec_CopyOnly";
                                }
                                break;

                            case "HTTP_ZKPLAY_PLAY":
                                url_zkplay = new URL_Zkplay(target.IP, LV_ZkplayPlayList.SelectedIndex);
                                batch      = url_zkplay.play;
                                break;

                            case "HTTP_ZKPLAY_SETTING":
                                _ZkplaySetting = new ZkplaySetting(this);
                                _ZkplaySetting.Setting.myip = target.IP;
                                url_zkplay = new URL_Zkplay(target.IP, 0, _ZkplaySetting.Setting);
                                batch      = url_zkplay.setting_set;
                                _ZkplaySetting.Close();
                                break;

                            case "PsExec_CopyOnly":
                                batch = "PsExec_CopyOnly";
                                break;
                            }

                            if (sync)
                            {
                                batch = "SYNC_" + batch;
                            }
                            if (!batch.Contains("PsExec"))
                            {
                                LV_UPLOAD.ItemsSource = null;
                            }
                            Thread thread = new Thread(this);
                            thread.Exec(target, batch);
                        }
                    }
                }
            }
        }
Example #6
0
        private async Task ProcessRequestAsync(HttpListenerContext context)
        {
            try
            {
                var    response       = context.Response;
                var    request        = context.Request;
                string responseString = "";
                switch (request.HttpMethod)
                {
                case "POST":
                    using (Stream body = request.InputStream)
                    {
                        using StreamReader reader = new StreamReader(body, request.ContentEncoding);
                        string  value    = reader.ReadToEnd();
                        JObject json     = JObject.Parse(value);
                        string  password = json["password"].Value <string>();
                        int     id       = json["id"].Value <int>();
                        if (!string.IsNullOrEmpty(password) || !string.IsNullOrEmpty(Config.GetPassword()))
                        {
                            if (password != Config.GetPassword())
                            {
                                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                                return;
                            }
                        }
                        var hosts = Config.GetHosts();
                        if (id < 0 || id >= hosts.Count)
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                            return;
                        }
                        await WOL.WakeOnLan(hosts[id].Mac);
                    }
                    break;

                case "GET":

                    if (context.Request.RawUrl == "/")
                    {
                        responseString = File.ReadAllText("html/admin.html").Replace("{{url}}", $"http://{Config.GetAddress()}");
                        StringBuilder items = new StringBuilder();
                        int           i     = 0;
                        foreach (var host in Config.GetHosts())
                        {
                            items.Append($"<a class=\"text-center label\">{host.Name}  {host.Mac}</a> ")
                            .Append($"<button class=\"btn btn-primary \" data-id=\"{i++}\">唤醒</button>")
                            .Append("<p></p>");
                        }
                        responseString = responseString.Replace("{{items}}", items.ToString());
                    }
                    else
                    {
                        responseString = File.ReadAllText("html" + context.Request.RawUrl);
                    }
                    break;
                }

                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine("远程管理服务器错误:" + ex.Message);
            }
            finally
            {
                context.Response.OutputStream.Close();
            }
        }
Example #7
0
            private void Connect()
            {
                try
                {
                    connection.On <string, string>("returnPS", (s1, s2) =>
                    {
                        lock (_locker)
                        {
                            TimeSpan timeout   = new TimeSpan(0, 5, 0); //default timeout = 5min
                            DateTime dStart    = DateTime.Now;
                            TimeSpan dDuration = DateTime.Now - dStart;

                            try
                            {
                                using (PowerShell PowerShellInstance = PowerShell.Create())
                                {
                                    //Console.WriteLine(DateTime.Now.ToString() + "\t run PS... " + s1);
                                    Trace.WriteLine(DateTime.Now.ToString() + "\t run PS... " + s1);
                                    try
                                    {
                                        PowerShellInstance.AddScript(s1);
                                        PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();

                                        outputCollection.DataAdding += OutputCollection_DataAdding;;
                                        //PowerShellInstance.Streams.Error.DataAdding += ConsoleError;

                                        IAsyncResult async = PowerShellInstance.BeginInvoke <PSObject, PSObject>(null, outputCollection);
                                        while (async.IsCompleted == false || dDuration > timeout)
                                        {
                                            //Thread.Sleep(200);
                                            dDuration = DateTime.Now - dStart;
                                            if (tReInit.Interval > 5000)
                                            {
                                                tReInit.Interval = 5000;
                                            }
                                        }

                                        Console.WriteLine(DateTime.Now.ToString() + "\t run PS... " + s1);
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine("There was an error: {0}", ex.Message);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("ERROR: " + ex.Message);
                            }
                        }
                        //Program.MinimizeFootprint();
                    });

                    //New 0.9.0.6
                    connection.On <string, string>("returnPSAsync", (s1, s2) =>
                    {
                        if ((DateTime.Now - tLastPSAsync).TotalSeconds >= 2)
                        {
                            lock (_locker)
                            {
                                //Trace.WriteLine(DateTime.Now.ToString() + "\t run PS async... " + s1);
                                tLastPSAsync = DateTime.Now;
                                var tSWScan  = Task.Run(() =>
                                {
                                    //using (PowerShell PowerShellInstance = PowerShell.Create())
                                    //{
                                    //    try
                                    //    {
                                    //        PowerShellInstance.AddScript(s1);
                                    //        var PSResult = PowerShellInstance.Invoke();
                                    //        if (PSResult.Count() > 0)
                                    //        {
                                    //            string sResult = PSResult.Last().BaseObject.ToString();

                                    //            if (!string.IsNullOrEmpty(sResult)) //Do not return empty results
                                    //            {
                                    //                if (sResult != sScriptResult)
                                    //                {
                                    //                    sScriptResult = sResult;
                                    //                    Random rnd = new Random();
                                    //                    tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max Xs to ReInit
                                    //                }
                                    //            }
                                    //        }
                                    //    }
                                    //    catch (Exception ex)
                                    //    {
                                    //        Console.WriteLine("There was an error: {0}", ex.Message);
                                    //    }
                                    //}

                                    //Program.MinimizeFootprint();
                                });
                            }
                        }
                    });

                    connection.On <string>("init", (s1) =>
                    {
                        try
                        {
                            Trace.Write(DateTime.Now.ToString() + "\t Agent init... ");
                            connection.SendAsync("Init", Hostname).ContinueWith(task1 =>
                            {
                            });
                            Trace.WriteLine(" done.");
                        }
                        catch { }
                        try
                        {
                            foreach (string sGroup in Groups.Split(';'))
                            {
                                connection.SendAsync("JoinGroup", sGroup).ContinueWith(task1 =>
                                {
                                });
                            }
                            //Program.MinimizeFootprint();
                        }
                        catch { }
                    });

                    connection.On <string>("reinit", (s1) =>
                    {
                        try
                        {
                            Random rnd       = new Random();
                            tReInit.Interval = rnd.Next(200, StatusDelay); //wait max 5s to ReInit
                        }
                        catch { }
                    });

                    connection.On <string>("status", (s1) =>
                    {
                        try
                        {
                            lock (_locker) //prevent parallel status
                            {
                                //Trace.Write(DateTime.Now.ToString() + "\t send status...");
                                string sResult = "{}";

                                var host = Dns.GetHostEntry(Dns.GetHostName());

                                JObject jStatus = new JObject();
                                jStatus.Add("Hostname", Environment.MachineName);
                                jStatus.Add("id", Environment.MachineName);
                                jStatus.Add("Internal IP", host.AddressList.FirstOrDefault(t => t.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString());
                                jStatus.Add("Last Reboot", dLastStartup);
                                jStatus.Add("Reboot Pending", false);
                                jStatus.Add("Users Online", true);
                                jStatus.Add("OS", System.Runtime.InteropServices.RuntimeInformation.OSDescription.Split('#')[0]); // Environment.OSVersion.ToString());
                                jStatus.Add("Version", Environment.OSVersion.Version.ToString());
                                jStatus.Add("Arch", System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString()); // Environment.Is64BitProcess ? "64-bit" : "???");
                                jStatus.Add("Lang", Thread.CurrentThread.CurrentCulture.LCID.ToString());
                                jStatus.Add("User", Environment.UserName);
                                jStatus.Add("ScriptResult", sScriptResult);
                                jStatus.Add("Groups", Groups);

                                sResult = jStatus.ToString();

                                //using (PowerShell PowerShellInstance = PowerShell.Create())
                                //{
                                //    try
                                //    {
                                //        PowerShellInstance.AddScript(Properties.Settings.Default.PSStatus);
                                //        var PSResult = PowerShellInstance.Invoke();
                                //        if (PSResult.Count() > 0)
                                //        {
                                //            sResult = PSResult.Last().BaseObject.ToString();
                                //            sResult = sResult.Replace(Environment.MachineName, Hostname);
                                //            JObject jRes = JObject.Parse(sResult);
                                //            jRes.Add("ScriptResult", sScriptResult);
                                //            jRes.Add("Groups", Properties.Settings.Default.Groups);
                                //            sResult = jRes.ToString();
                                //        }
                                //    }
                                //    catch (Exception ex)
                                //    {
                                //        Console.WriteLine(" There was an error: {0}", ex.Message);
                                //    }
                                //}

                                //connection.InvokeAsync("Status", new object[] { Hostname, sResult }).ContinueWith(task1 =>
                                //{
                                //});
                                connection.InvokeAsync("Status", Hostname, sResult).Wait(1000);
                                Trace.WriteLine(" done.");
                                //Program.MinimizeFootprint();
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.Write(DateTime.Now.ToString() + " ERROR: " + ex.Message);
                        }
                    });

                    connection.On <string>("version", (s1) =>
                    {
                        try
                        {
                            lock (_locker)
                            {
                                Trace.Write(DateTime.Now.ToString() + "\t Get Version... ");
                                //Get File-Version
                                sScriptResult = (FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location)).FileVersion.ToString();
                                Trace.WriteLine(sScriptResult);

                                Random rnd       = new Random();
                                tReInit.Interval = rnd.Next(200, StatusDelay); //wait max 5s to ReInit
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.Write(DateTime.Now.ToString() + " ERROR: " + ex.Message);
                        }
                    });

                    connection.On <string>("wol", (s1) =>
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(s1))
                            {
                                foreach (string sMAC in s1.Split(';'))
                                {
                                    try
                                    {
                                        WOL.WakeUp(sMAC); //Send Broadcast

                                        //Send to local Gateway
                                        foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces())
                                        {
                                            if (f.OperationalStatus == OperationalStatus.Up)
                                            {
                                                foreach (GatewayIPAddressInformation d in f.GetIPProperties().GatewayAddresses)
                                                {
                                                    //Only use IPv4
                                                    if (d.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                                                    {
                                                        WOL.WakeUp(d.Address, 9, sMAC);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch { }
                                }
                            }
                        }
                        catch { }
                    });

                    connection.On <string>("setinstance", (s1) =>
                    {
                        Trace.WriteLine(DateTime.Now.ToString() + "\t Set instance: " + s1);
                        try
                        {
                            lock (_locker)
                            {
                            }
                            //if (!string.IsNullOrEmpty(s1))
                            //{
                            //    string sConfig = Assembly.GetExecutingAssembly().Location + ".config";
                            //    XmlDocument doc = new XmlDocument();
                            //    doc.Load(sConfig);
                            //    doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Instance']/value").InnerText = s1;
                            //    doc.Save(sConfig);
                            //    RestartService();

                            //    //Update Advanced Installer Persistent Properties
                            //    RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{54F5CC06-300A-4DD4-94D9-0E18B2BE8DF1}", true);
                            //    if (myKey != null)
                            //    {
                            //        myKey.SetValue("INSTANCE", s1.Trim(), RegistryValueKind.String);
                            //        myKey.Close();
                            //    }
                            //}
                        }
                        catch { }
                    });

                    connection.On <string>("setendpoint", (s1) =>
                    {
                        Trace.WriteLine(DateTime.Now.ToString() + "\t Set Endpoint: " + s1);
                        try
                        {
                            lock (_locker)
                            {
                            }
                            //if (!string.IsNullOrEmpty(s1))
                            //{
                            //    if (s1.StartsWith("https://"))
                            //    {
                            //        string sConfig = Assembly.GetExecutingAssembly().Location + ".config";
                            //        XmlDocument doc = new XmlDocument();
                            //        doc.Load(sConfig);
                            //        doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Endpoint']/value").InnerText = s1;
                            //        doc.Save(sConfig);
                            //        RestartService();

                            //        //Update Advanced Installer Persistent Properties
                            //        RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{54F5CC06-300A-4DD4-94D9-0E18B2BE8DF1}", true);
                            //        if (myKey != null)
                            //        {
                            //            myKey.SetValue("ENDPOINT", s1.Trim(), RegistryValueKind.String);
                            //            myKey.Close();
                            //        }
                            //    }
                            //}
                        }
                        catch { }
                    });

                    connection.On <string>("setgroups", (s1) =>
                    {
                        Trace.WriteLine(DateTime.Now.ToString() + "\t Set Groups: " + s1);
                        try
                        {
                            lock (_locker)
                            {
                            }
                            //if (!string.IsNullOrEmpty(s1))
                            //{
                            //    string sConfig = Assembly.GetExecutingAssembly().Location + ".config";
                            //    XmlDocument doc = new XmlDocument();
                            //    doc.Load(sConfig);
                            //    doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Groups']/value").InnerText = s1;
                            //    doc.Save(sConfig);

                            //    RestartService();

                            //    //Update Advanced Installer Persistent Properties
                            //    RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{54F5CC06-300A-4DD4-94D9-0E18B2BE8DF1}", true);
                            //    if (myKey != null)
                            //    {
                            //        myKey.SetValue("GROUPS", s1.Trim(), RegistryValueKind.String);
                            //        myKey.Close();
                            //    }
                            //}
                        }
                        catch { }
                    });

                    connection.On <string>("getgroups", (s1) =>
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(s1))
                            {
                                sScriptResult = Groups;

                                Random rnd       = new Random();
                                tReInit.Interval = rnd.Next(200, StatusDelay); //wait max 5s to ReInit
                            }
                        }
                        catch { }
                    });

                    connection.On <string>("restartservice", (s1) =>
                    {
                        try
                        {
                            //RestartService();
                            sScriptResult = "restart Agent...";
                        }
                        catch { }
                    });

                    connection.On <string>("rzinstall", (s1) =>
                    {
                        //RZInst(s1);
                    });

                    connection.On <string>("rzupdate", (s1) =>
                    {
                        //var tSWScan = Task.Run(() =>
                        //{
                        //    try
                        //    {
                        //        sScriptResult = "Detecting RZ updates...";
                        //        Random rnd = new Random();
                        //        tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit

                        //        RZUpdater oUpdate = new RZUpdater();
                        //        RZScan oScan = new RZScan(false, false);

                        //        oScan.GetSWRepository().Wait(30000);
                        //        oScan.SWScan().Wait(30000);
                        //        oScan.CheckUpdates(null).Wait(30000);

                        //        if (string.IsNullOrEmpty(s1))
                        //        {
                        //            sScriptResult = oScan.NewSoftwareVersions.Count.ToString() + " RZ updates found";
                        //            rnd = new Random();
                        //            tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit
                        //        }

                        //        List<string> lSW = new List<string>();
                        //        foreach (var oSW in oScan.NewSoftwareVersions)
                        //        {
                        //            if (string.IsNullOrEmpty(s1) || s1 == "HUB")
                        //            {
                        //                RZInst(oSW.Shortname);
                        //            }
                        //            else
                        //            {
                        //                var SWList = s1.Split(';');
                        //                if (SWList.Contains(oSW.Shortname))
                        //                    RZInst(oSW.Shortname);
                        //            }
                        //        }
                        //    }
                        //    catch { }
                        //});
                    });

                    connection.On <string>("rzscan", (s1) =>
                    {
                        //var tSWScan = Task.Run(() =>
                        //{
                        //    try
                        //    {
                        //        sScriptResult = "Detecting updates...";
                        //        Random rnd = new Random();
                        //        tReInit.Interval = rnd.Next(2000, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit

                        //        RZUpdater oUpdate = new RZUpdater();
                        //        RZScan oScan = new RZScan(false, false);

                        //        oScan.GetSWRepository().Wait(30000);
                        //        oScan.SWScan().Wait(30000);
                        //        oScan.CheckUpdates(null).Wait(30000);

                        //        List<string> lSW = new List<string>();
                        //        foreach (var SW in oScan.NewSoftwareVersions)
                        //        {
                        //            lSW.Add(SW.Shortname + " " + SW.ProductVersion + " (old:" + SW.MSIProductID + ")");
                        //        }

                        //        sScriptResult = JsonConvert.SerializeObject(lSW);
                        //        rnd = new Random();
                        //        tReInit.Interval = rnd.Next(2000, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit
                        //    }
                        //    catch { }
                        //});
                    });

                    connection.On <string>("inject", (s1) =>
                    {
                        //var tSWScan = Task.Run(() =>
                        //{
                        //    try
                        //    {
                        //        sScriptResult = "Inject external code...";
                        //        try
                        //        {
                        //            ManagedInjection.Inject(s1);
                        //            sScriptResult = "External code executed.";
                        //        }
                        //        catch (Exception ex)
                        //        {
                        //            sScriptResult = "Injection error:" + ex.Message;
                        //        }
                        //    }
                        //    catch { }
                        //});
                    });

                    connection.On <string, string>("userprocess", (cmd, arg) =>
                    {
                        //var tSWScan = Task.Run(() =>
                        //{
                        //    if (string.IsNullOrEmpty(cmd))
                        //    {
                        //        cmd = Assembly.GetExecutingAssembly().Location;
                        //        arg = Environment.MachineName + ":" + "%USERNAME%";
                        //    }

                        //    try
                        //    {
                        //        if (string.IsNullOrEmpty(arg))
                        //        {
                        //            ProcessExtensions.StartProcessAsCurrentUser(cmd, null, null, false);
                        //        }
                        //        else
                        //        {
                        //            ProcessExtensions.StartProcessAsCurrentUser(null, cmd + " " + arg, null, false);
                        //        }
                        //    }
                        //    catch (Exception ex)
                        //    {
                        //        Console.WriteLine(ex.Message);
                        //    }
                        //});
                    });

                    //connection.InvokeCoreAsync("Init", new object[] { Hostname }).Wait();
                    connection.InvokeAsync("Init", Hostname).ContinueWith(task1 =>
                    {
                        try
                        {
                            if (task1.IsFaulted)
                            {
                                Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException());
                            }
                            else
                            {
                                try
                                {
                                    foreach (string sGroup in Groups.Split(';'))
                                    {
                                        connection.InvokeAsync("JoinGroup", sGroup).ContinueWith(task2 =>
                                        {
                                        });
                                    }
                                    //Program.MinimizeFootprint();
                                }
                                catch { }
                            }
                        }
                        catch { }
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine("There was an error: {0}", ex.Message);
                }
            }
        public void setupClient()
        {
            _logger.Debug("Begining the setupClient function");

            WOL.WakeOnLan(macAddress);

            _logger.Debug("Sending the WOL Packet over to " + this.whichTV);

            wsClient = new WebSocket(this.IP);

            wsClient.OnOpen += (o, e) =>
            {
                _logger.Info("Successfully Connected to " + this.whichTV);
                //wsClient.Send("{\"type\":\"register\",\"id\":\"register_0\",\"payload\":{\"forcePairing\":false,\"pairingType\":\"PROMPT\",\"manifest\":{\"manifestVersion\":1,\"appVersion\":\"1.1\",\"signed\":{\"created\":\"20140509\",\"appId\":\"com.lge.test\",\"vendorId\":\"com.lge\",\"localizedAppNames\":{\"\":\"LG Remote App\",\"ko-KR\":\"??? ?\",\"zxx-XX\":\"?? R??ot? A??\"},\"localizedVendorNames\":{\"\":\"LG Electronics\"},\"permissions\":[\"TEST_SECURE\",\"CONTROL_INPUT_TEXT\",\"CONTROL_MOUSE_AND_KEYBOARD\",\"READ_INSTALLED_APPS\",\"READ_LGE_SDX\",\"READ_NOTIFICATIONS\",\"SEARCH\",\"WRITE_SETTINGS\",\"WRITE_NOTIFICATION_ALERT\",\"CONTROL_POWER\",\"READ_CURRENT_CHANNEL\",\"READ_RUNNING_APPS\",\"READ_UPDATE_INFO\",\"UPDATE_FROM_REMOTE_APP\",\"READ_LGE_TV_INPUT_EVENTS\",\"READ_TV_CURRENT_TIME\"],\"serial\":\"2f930e2d2cfe083771f68e4fe7bb07\"},\"permissions\":[\"LAUNCH\",\"LAUNCH_WEBAPP\",\"APP_TO_APP\",\"CLOSE\",\"TEST_OPEN\",\"TEST_PROTECTED\",\"CONTROL_AUDIO\",\"CONTROL_DISPLAY\",\"CONTROL_INPUT_JOYSTICK\",\"CONTROL_INPUT_MEDIA_RECORDING\",\"CONTROL_INPUT_MEDIA_PLAYBACK\",\"CONTROL_INPUT_TV\",\"CONTROL_POWER\",\"READ_APP_STATUS\",\"READ_CURRENT_CHANNEL\",\"READ_INPUT_DEVICE_LIST\",\"READ_NETWORK_STATE\",\"READ_RUNNING_APPS\",\"READ_TV_CHANNEL_LIST\",\"WRITE_NOTIFICATION_TOAST\",\"READ_POWER_STATE\",\"READ_COUNTRY_INFO\"],\"signatures\":[{\"signatureVersion\":1,\"signature\":\"eyJhbGdvcml0aG0iOiJSU0EtU0hBMjU2Iiwia2V5SWQiOiJ0ZXN0LXNpZ25pbmctY2VydCIsInNpZ25hdHVyZVZlcnNpb24iOjF9.hrVRgjCwXVvE2OOSpDZ58hR+59aFNwYDyjQgKk3auukd7pcegmE2CzPCa0bJ0ZsRAcKkCTJrWo5iDzNhMBWRyaMOv5zWSrthlf7G128qvIlpMT0YNY+n/FaOHE73uLrS/g7swl3/qH/BGFG2Hu4RlL48eb3lLKqTt2xKHdCs6Cd4RMfJPYnzgvI4BNrFUKsjkcu+WD4OO2A27Pq1n50cMchmcaXadJhGrOqH5YmHdOCj5NSHzJYrsW0HPlpuAx/ECMeIZYDh6RMqaFM2DXzdKX9NmmyqzJ3o/0lkk/N97gfVRLW5hA29yeAwaCViZNCP8iC9aO0q9fQojoa7NQnAtw==\"}]}}}");
                isConnected      = true;
                connectionStatus = 2;
            };

            wsClient.OnMessage += (o, e) =>
            {
                _logger.Info("Received a message from the TV Webscokets server. The message is " + e.Data.ToString());
                dynamic recMsg = JsonConvert.DeserializeObject(e.Data.ToString().Replace("-", ""));
                //check if this is the TV passing back the client code
                if (recMsg.type == "registered")
                {
                    this.wsClientKey = recMsg.payload.clientkey;
                    this.isPaired    = true;
                }
                if (recMsg.type == "error")
                {
                    //Error Messages that could be received from the TVs

                    //We are not paired because the TV has prompted the user to accept the pairing.
                    if (recMsg.error == "409 register already in progress")
                    {
                    }

                    if (recMsg.error == "403 cancelled")
                    {
                        this.isPaired = false;
                    }
                }
            };

            wsClient.OnError += (o, e) =>
            {
                Console.WriteLine("There is an error connecting and the message is " + e.Message.ToString());
                _logger.Error("There is an error connecting and the message is " + e.Message.ToString());
                //errorRecvd = true;
            };

            wsClient.OnClose += (sender, e) =>
            {
                //Console.WriteLine("This stupid disconnected");
                _logger.Warn("The websocket connection with " + this.whichTV + " with an ip address of has been lost");
                this.connectionStatus = 0;
            };

            _logger.Info("Trying to Connect");
            try
            {
                this.connectionStatus = 1;
                wsClient.Connect();
            }
            catch (Exception e)
            {
                _logger.Error("There was a failure to connect and the message is " + e.ToString());
            }
        }