Exemple #1
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    //if (rdpClient != null)
                    //{
                    //    if(rdpClient.isConnected) rdpClient.Disconnect();
                    //    rdpClient.Dispose();
                    //}
                    //rdpClient = null;
                    if (rdp != null)
                    {
                        if (rdp.Connected)
                        {
                            rdp.Disconnect();
                        }
                        rdp.Dispose();
                    }
                    rdp = null;
                    cancellationTokenSource.Cancel();

                    if (connection != null)
                    {
                        if (connection.IsConnected)
                        {
                            connection.Close();
                        }
                        connection = null;
                    }
                }
                disposedValue = true;
            }
        }
Exemple #2
0
 private static async void Pipe_ClientMessage(NamedPipeWrapper.NamedPipeConnection <RPAMessage, RPAMessage> connection, RPAMessage message)
 {
     if (message.command == "pong")
     {
         return;
     }
     if (message.command == "hello")
     {
         var windowsusername = message.windowsusername.ToLower();
         var session         = sessions.Where(x => x.client.windowsusername == windowsusername).FirstOrDefault();
         if (session == null)
         {
             //Log.Information("Adding new unattendedclient for " + windowsusername);
             string computername = NativeMethods.GetHostName().ToLower();
             string computerfqdn = NativeMethods.GetFQDN().ToLower();
             var    client       = new unattendedclient()
             {
                 computername = computername, computerfqdn = computerfqdn, windowsusername = windowsusername, name = computername + " " + windowsusername, openrpapath = message.openrpapath
             };
             // client = await global.webSocketClient.InsertOne("openrpa", 1, false, client);
             session = new RobotUserSession(client);
             sessions.Add(session);
         }
         if (session.client != null)
         {
             session.client.openrpapath = message.openrpapath;
             session.AddConnection(connection);
         }
     }
     if (message.command == "reloadconfig")
     {
         await ReloadConfig();
     }
 }
Exemple #3
0
        private void Pipe_Connected(NamedPipeWrapper.NamedPipeConnection <RPAMessage, RPAMessage> connection)
        {
            Log.Debug("OpenRPA connected to OpenRPA Windows Service");
            var asm  = System.Reflection.Assembly.GetEntryAssembly();
            var path = asm.CodeBase.Replace("file:///", "");

            pipe.PushMessage(new RPAMessage("hello", NativeMethods.GetProcessUserName(), global.webSocketClient.user, path));
        }
Exemple #4
0
 private void Pipe_ServerMessage(NamedPipeWrapper.NamedPipeConnection <RPAMessage, RPAMessage> connection, RPAMessage message)
 {
     if (message.command == "ping")
     {
         connection.PushMessage(new RPAMessage("pong"));
         return;
     }
     Console.WriteLine("OpenRPA Windows Service: " + message.command);
 }
Exemple #5
0
 private void Connection_ReceiveMessage(NamedPipeWrapper.NamedPipeConnection <RPAMessage, RPAMessage> connection, RPAMessage message)
 {
     if (message.command == "pong")
     {
         lastheartbeat = DateTime.Now;
         return;
     }
     Log.Debug(message.command.ToString());
 }
Exemple #6
0
 public void AddConnection(NamedPipeWrapper.NamedPipeConnection <RPAMessage, RPAMessage> connection)
 {
     if (this.connection != null)
     {
         this.connection.ReceiveMessage -= Connection_ReceiveMessage;
     }
     this.connection = connection;
     this.connection.ReceiveMessage += Connection_ReceiveMessage;
 }
Exemple #7
0
 public void disconnect()
 {
     disconnectrdp();
     if (connection != null)
     {
         if (connection.IsConnected)
         {
             connection.Close();
         }
         connection = null;
     }
 }
Exemple #8
0
 private void Pipe_ServerMessage(NamedPipeWrapper.NamedPipeConnection <RPAMessage, RPAMessage> connection, RPAMessage message)
 {
     if (message.command == "ping")
     {
         connection.PushMessage(new RPAMessage("pong"));
         return;
     }
     if (message.command == "signout")
     {
         NativeMethods.ExitWindowsEx((uint)NativeMethods.ExitWindows.LogOff, (uint)(NativeMethods.ShutdownReason.MajorOther | NativeMethods.ShutdownReason.MinorOther));
     }
     Console.WriteLine("OpenRPA Windows Service: " + message.command);
 }
Exemple #9
0
 public void AddConnection(NamedPipeWrapper.NamedPipeConnection <RPAMessage, RPAMessage> connection)
 {
     try
     {
         if (this.connection != null)
         {
             this.connection.ReceiveMessage -= Connection_ReceiveMessage;
         }
         this.connection = connection;
         this.connection.ReceiveMessage += Connection_ReceiveMessage;
     }
     catch (Exception ex)
     {
         Log.Error(ex.ToString());
     }
 }
Exemple #10
0
 private void Connection_ReceiveMessage(NamedPipeWrapper.NamedPipeConnection <RPAMessage, RPAMessage> connection, RPAMessage message)
 {
     try
     {
         if (message.command == "pong")
         {
             lastheartbeat = DateTime.Now;
             return;
         }
         Log.Information(message.command.ToString());
     }
     catch (Exception ex)
     {
         Log.Error(ex.ToString());
     }
 }
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    if (freerdp != null)
                    {
                        if (freerdp.Connected)
                        {
                            freerdp.Disconnect();
                        }
                        freerdp.Dispose();
                    }
                    freerdp = null;
                    if (rdp != null)
                    {
                        if (rdp.Connected)
                        {
                            rdp.Disconnect();
                        }
                        rdp.Dispose();
                    }
                    rdp = null;
                    cancellationTokenSource.Cancel();

                    if (connection != null)
                    {
                        if (connection.IsConnected)
                        {
                            connection.Close();
                        }
                        connection = null;
                    }
                }
                disposedValue = true;
            }
        }
Exemple #12
0
 private void Pipe_Disconnected(NamedPipeWrapper.NamedPipeConnection <RPAMessage, RPAMessage> connection)
 {
     Log.Debug("OpenRPA disconnected from OpenRPA Windows Service");
 }
Exemple #13
0
        public void DoWork()
        {
            if (client == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(client._id))
            {
                return;                                   // Dummy client, ignore
            }
            if (connection != null && connection.IsConnected == false)
            {
                connection = null; created = DateTime.Now;
            }
            // Is OpenRPA connected for this user ?
            if (connection != null)
            {
                connection.PushMessage(new RPAMessage("ping"));
                created = DateTime.Now;
                return;
            }
            if ((DateTime.Now - created).TotalSeconds < 5)
            {
                return;
            }
            // Is user signed in ?
            // ownerexplorer = null;
            //if (ownerexplorer == null)
            if (rdp == null || rdp.Connected == false)
            {
                if (rdp == null)
                {
                    Console.WriteLine("rdp is null");
                }
                else
                {
                    //Console.WriteLine("rdp.Connected: " + rdp.Connected + " rdp.Connecting: " + rdp.Connecting);
                    //if (rdp.Connecting) return;
                }


                // if((DateTime.Now - lastrdp) < client.autorestart) return;
                if (string.IsNullOrEmpty(client.windowspassword))
                {
                    return;
                }
                lastrdp = DateTime.Now;
                if (rdp != null)
                {
                    //if (rdp.Connected)
                    //{
                    //    Log.Information("Disconnecting RDP connection for " + client.windowsusername);
                    //    rdp.Disconnect();
                    //    rdp.Dispose();
                    //    rdp = null;
                    //}
                }
                //if (rdpClient!=null)
                //{
                //    if(rdpClient.isConnected)
                //    {
                //        Log.Information("Disconnecting RDP connection for " + client.windowsusername) ;
                //        rdpClient.Disconnect();
                //        rdpClient.Dispose();
                //        rdpClient = null;
                //    }
                //}
                // https://social.msdn.microsoft.com/Forums/vstudio/en-US/2daeecb3-778b-478e-b379-102b790777c2/c-remote-desktop-over-the-same-computer?forum=csharpgeneral

                // https://github.com/terminals-Origin/Terminals
                // https://www.codeproject.com/Articles/43705/Remote-Desktop-using-C-NET
                // https://www.codeproject.com/Articles/16374/How-to-Write-a-Terminal-Services-Add-in-in-Pure-C
                // https://stackoverflow.com/questions/52801093/create-windows-session-programmatically-from-console-or-windows-service

                try
                {
                    // https://stackoverflow.com/questions/46807645/passing-a-struct-pointer-in-c-sharp-interop-results-in-null

                    //var thread = new System.Threading.Thread(() =>
                    //{
                    //    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
                    //    {
                    //        if(rdp==null) rdp = new Client();
                    //        //if(NativeMethods.GetProcessUserName)
                    //        var hostname = NativeMethods.GetHostName().ToLower();
                    //        if (client.windowsusername.StartsWith(hostname + @"\"))
                    //        {
                    //            Log.Information("Connecting RDP connection for " + client.windowsusername.Substring(hostname.Length + 1));
                    //            rdp.CreateRdpConnectionasync("127.0.0.2", "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword);
                    //        }
                    //        else
                    //        {
                    //            Log.Information("Connecting RDP connection for " + client.windowsusername);
                    //            rdp.CreateRdpConnectionasync("127.0.0.2", "", client.windowsusername, client.windowspassword);
                    //        }
                    //        created = DateTime.Now;

                    //    }));

                    //    Dispatcher.Run();
                    //});
                    //thread.SetApartmentState(System.Threading.ApartmentState.STA);
                    //thread.Start();
                    //thread.Join();



                    //var thread = new System.Threading.Thread(() =>
                    //{
                    //    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
                    //    {
                    //        //rdpClient = new RdpClient();
                    //        //rdpClient.Connect("127.0.0.2", "", client.windowsusername, client.windowspassword);
                    //        rdp = new FreeRDP.Core.RDP();
                    //        rdp.Connect("127.0.0.2", "", client.windowsusername, client.windowspassword);
                    //    }));

                    //    Dispatcher.Run();
                    //});

                    //thread.SetApartmentState(System.Threading.ApartmentState.STA);
                    //thread.Start();
                    //thread.Join();

                    if (rdp == null)
                    {
                        rdp = new FreeRDP.Core.RDP();
                    }
                    //if(NativeMethods.GetProcessUserName)
                    var hostname = NativeMethods.GetHostName().ToLower();
                    if (client.windowsusername.StartsWith(hostname + @"\"))
                    {
                        var windowsusername = client.windowsusername.Substring(hostname.Length + 1);
                        Log.Information("Connecting RDP connection for " + windowsusername);
                        // rdp.CreateRdpConnectionasync("127.0.0.2", "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword);
                        rdp.Connect("127.0.0.2", "", windowsusername, client.windowspassword);
                    }
                    else
                    {
                        Log.Information("Connecting RDP connection for " + client.windowsusername);
                        // rdp.CreateRdpConnectionasync("127.0.0.2", "", client.windowsusername, client.windowspassword);
                        rdp.Connect("127.0.0.2", "", client.windowsusername, client.windowspassword);
                    }
                    created = DateTime.Now;
                }
                catch (Exception ex)
                {
                    Log.Error(ex.ToString());
                }
                return;
            }
            if (rdp == null)
            {
                Console.WriteLine("rdp is null");
            }
            else
            {
                // Console.WriteLine("rdp.Connected: " + rdp.Connected + " rdp.Connecting: " + rdp.Connecting);
                Console.WriteLine("rdp.Connected: " + rdp.Connected);
            }
            if (rdp == null || rdp.Connected == false)
            {
                return;
            }

            try
            {
                var procs = Process.GetProcessesByName("explorer");
                System.Diagnostics.Process ownerexplorer = null;
                foreach (var explorer in procs)
                {
                    try
                    {
                        var owner = NativeMethods.GetProcessUserName(explorer).ToLower();
                        if (owner == client.windowsusername)
                        {
                            ownerexplorer = explorer;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.ToString());
                        created = DateTime.Now;
                        return;
                    }
                }
                if (ownerexplorer == null)
                {
                    return;
                }
                System.Diagnostics.Process ownerrpa = null;
                procs = Process.GetProcessesByName("openrpa");
                foreach (var rpa in procs)
                {
                    try
                    {
                        var owner = NativeMethods.GetProcessUserName(rpa).ToLower();
                        if (owner == client.windowsusername)
                        {
                            ownerrpa = rpa;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.ToString());
                        created = DateTime.Now;
                        return;
                    }
                }
                if (ownerrpa != null)
                {
                    //if(client.autorestart != TimeSpan.Zero && (DateTime.Now - lastheartbeat) > client.autorestart )
                    //{
                    //    try
                    //    {
                    //        lastheartbeat = DateTime.Now;
                    //        ownerrpa.Kill();
                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        Log.Error(ex.ToString());
                    //    }
                    //}
                    return;
                }
                if (string.IsNullOrEmpty(client.openrpapath))
                {
                    return;
                }
                if (!System.IO.File.Exists(client.openrpapath))
                {
                    return;
                }
                var path = System.IO.Path.GetDirectoryName(client.openrpapath);
                if (!Program.isService)
                {
                    Log.Information("Not running as service, so just launching openrpa here");
                    Log.Information(client.openrpapath);
                    created = DateTime.Now;
                    Process.Start(new ProcessStartInfo(client.openrpapath)
                    {
                        WorkingDirectory = path
                    });
                    return;
                }
                Log.Information("Attaching to user explorer and launching robot in session");
                Log.Information(client.openrpapath);
                created = DateTime.Now;
                if (!NativeMethods.Launch(ownerexplorer, path, @"c:\windows\system32\cmd.exe /C " + "\"" + client.openrpapath + "\""))
                {
                    Log.Error("Failed launching robot in session");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                created = DateTime.Now;
            }
        }
Exemple #14
0
 private static void Pipe_ClientConnected(NamedPipeWrapper.NamedPipeConnection <RPAMessage, RPAMessage> connection)
 {
     Log.Information("Client connected!");
 }
Exemple #15
0
        public void DoWork()
        {
            try
            {
                if (client == null)
                {
                    Log.Information("client is null");
                    return;
                }
                if (string.IsNullOrEmpty(client._id))
                {
                    // Log.Information("client._id is null, Dummy client, ignore");
                    return; // Dummy client, ignore
                }
                if (connection != null && connection.IsConnected == false)
                {
                    connection = null; created = DateTime.Now;
                }
                // Is OpenRPA connected for this user ?
                if (connection != null)
                {
                    connection.PushMessage(new RPAMessage("ping"));
                    // created = DateTime.Now;
                    // return;
                }
                if ((DateTime.Now - created).TotalSeconds < 5)
                {
                    return;
                }
                // Is user signed in ?
                // ownerexplorer = null;
                //if (ownerexplorer == null)
                var rdpip = "127.0.0.2";
                // if ((ConnectionAttempts % 2) == 1) rdpip = "127.0.0.1";
                if (PluginConfig.usefreerdp && !skiprdp)
                {
                    if (freerdp == null || freerdp.Connected == false)
                    {
                        if (freerdp == null)
                        {
                            Console.WriteLine("rdp is null");
                        }
                        if (string.IsNullOrEmpty(client.windowspassword))
                        {
                            return;
                        }
                        lastrdp = DateTime.Now;
                    }
                    if (freerdp == null)
                    {
                        freerdp = new FreeRDP.Core.RDP();
                    }
                    if (!freerdp.Connected)
                    {
                        var hostname = NativeMethods.GetHostName().ToLower();
                        try
                        {
                            Log.Information("Tesing connection to " + rdpip + " port 3389");
                            using (var tcpClient = new System.Net.Sockets.TcpClient())
                            {
                                var ipAddress  = System.Net.IPAddress.Parse(rdpip);
                                var ipEndPoint = new System.Net.IPEndPoint(ipAddress, 3389);
                                tcpClient.Connect(ipEndPoint);
                            }
                            Log.Information("Success");
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.ToString());
                            return;
                        }

                        var windowsusername = client.windowsusername.Substring(client.windowsusername.IndexOf("\\") + 1);
                        var windowsdomain   = client.windowsusername.Substring(0, client.windowsusername.IndexOf("\\"));

                        using (var imp = new Impersonator(windowsusername, windowsdomain, client.windowspassword))
                        {
                            ConnectionAttempts++;
                            if (client.windowsusername.StartsWith(hostname + @"\"))
                            {
                                // var windowsusername = client.windowsusername.Substring(hostname.Length + 1);
                                Log.Information("Connecting RDP connection to " + rdpip + " for " + windowsusername);
                                freerdp.Connect(rdpip, "", windowsusername, client.windowspassword);
                            }
                            else
                            {
                                Log.Information("Connecting RDP connection to " + rdpip + " for " + client.windowsusername);
                                freerdp.Connect(rdpip, "", client.windowsusername, client.windowspassword);
                            }
                        }
                        created = DateTime.Now;
                        return;
                    }
                    if (freerdp == null || freerdp.Connected == false)
                    {
                        return;
                    }
                }
                else if (!skiprdp)
                {
                    if (rdp == null || rdp.Connected == false)
                    {
                        if (rdp == null)
                        {
                            Console.WriteLine("rdp is null");
                        }
                        if (string.IsNullOrEmpty(client.windowspassword))
                        {
                            return;
                        }
                        lastrdp = DateTime.Now;
                    }
                    if (rdp == null)
                    {
                        rdp = new Client();
                    }
                    if (rdp.Connecting)
                    {
                        return;
                    }
                    if (!rdp.Connected)
                    {
                        try
                        {
                            Log.Information("Tesing connection to " + rdpip + " port 3389");
                            using (var tcpClient = new System.Net.Sockets.TcpClient())
                            {
                                var ipAddress  = System.Net.IPAddress.Parse(rdpip);
                                var ipEndPoint = new System.Net.IPEndPoint(ipAddress, 3389);
                                tcpClient.Connect(ipEndPoint);
                            }
                            Log.Information("Success");
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.ToString());
                            return;
                        }

                        ConnectionAttempts++;
                        var hostname = NativeMethods.GetHostName().ToLower();
                        if (client.windowsusername.StartsWith(hostname + @"\"))
                        {
                            var windowsusername = client.windowsusername.Substring(hostname.Length + 1);
                            Log.Information("Connecting RDP connection to " + rdpip + " for " + windowsusername);
                            // Task.Run(()=>rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword));
                            rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword);
                            Log.Information("Connection initialized");
                        }
                        else
                        {
                            Log.Information("Connecting RDP connection to " + rdpip + " for " + client.windowsusername);
                            // Task.Run(() => rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername, client.windowspassword));
                            rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername, client.windowspassword);
                            Log.Information("Connection initialized");
                        }
                        created = DateTime.Now;
                    }
                    if (rdp == null || rdp.Connected == false)
                    {
                        return;
                    }
                }

                try
                {
                    var procs = Process.GetProcessesByName("explorer");
                    System.Diagnostics.Process ownerexplorer = null;
                    foreach (var explorer in procs)
                    {
                        try
                        {
                            var owner = NativeMethods.GetProcessUserName(explorer).ToLower();
                            if (owner == client.windowsusername)
                            {
                                ownerexplorer = explorer;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.ToString());
                            created = DateTime.Now;
                            return;
                        }
                    }
                    if (ownerexplorer == null)
                    {
                        return;
                    }
                    System.Diagnostics.Process ownerrpa = null;
                    procs = Process.GetProcessesByName("openrpa");
                    foreach (var rpa in procs)
                    {
                        try
                        {
                            var owner = NativeMethods.GetProcessUserName(rpa).ToLower();
                            if (owner == client.windowsusername)
                            {
                                ownerrpa = rpa;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.ToString());
                            created = DateTime.Now;
                            return;
                        }
                    }
                    if (ownerrpa != null)
                    {
                        //if(client.autorestart != TimeSpan.Zero && (DateTime.Now - lastheartbeat) > client.autorestart )
                        //{
                        //    try
                        //    {
                        //        lastheartbeat = DateTime.Now;
                        //        ownerrpa.Kill();
                        //    }
                        //    catch (Exception ex)
                        //    {
                        //        Log.Error(ex.ToString());
                        //    }
                        //}
                        return;
                    }
                    if (string.IsNullOrEmpty(client.openrpapath))
                    {
                        return;
                    }
                    if (!System.IO.File.Exists(client.openrpapath))
                    {
                        return;
                    }
                    var path = System.IO.Path.GetDirectoryName(client.openrpapath);
                    //if (!Program.isService)
                    //{
                    //    Log.Information("Not running as service, so just launching openrpa here");
                    //    Log.Information(client.openrpapath);
                    //    created = DateTime.Now;
                    //    Process.Start(new ProcessStartInfo(client.openrpapath) { WorkingDirectory = path });
                    //    return;
                    //}
                    Log.Information("Attaching to user explorer and launching robot in session");
                    Log.Information(client.openrpapath);
                    created = DateTime.Now;
                    // IntPtr hSessionToken = IntPtr.Zero;
                    // SessionFinder sf = new SessionFinder();
                    // hSessionToken = sf.GetLocalInteractiveSession();
                    //var windowsusername = client.windowsusername.Substring(client.windowsusername.IndexOf("\\") + 1);
                    //var windowsdomain = client.windowsusername.Substring(0, client.windowsusername.IndexOf("\\") );
                    //// hSessionToken = sf.GetSessionByUser(windowsdomain, windowsusername);
                    //Impersonation.ExecuteAppAsLoggedOnUser(client.openrpapath, null, System.IO.Path.GetDirectoryName(client.openrpapath));
                    //var runner = new InteractiveProcessRunner(client.openrpapath, hSessionToken);
                    //var p = runner.Run();

                    //if (!NativeMethods.Launch(ownerexplorer, path, @"c:\windows\system32\cmd.exe /C " + "\"" + client.openrpapath + "\""))
                    if (!NativeMethods.Launch(ownerexplorer, path, client.openrpapath))
                    {
                        Log.Error("Failed launching robot in session");
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex.ToString());
                    created = DateTime.Now;
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                created = DateTime.Now;
            }
        }
 private void clientDisconnected(NamedPipeWrapper.NamedPipeConnection <BaseMessage, BaseMessage> conn)
 {
     conn.Disconnected -= clientDisconnected;
     ClientDisconnected?.Invoke(this);
 }
Exemple #17
0
        public void DoWork()
        {
            try
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    skiprdp = true;
                }
                if (client == null)
                {
                    Log.Information("client is null");
                    return;
                }
                if (string.IsNullOrEmpty(client._id))
                {
                    // Log.Information("client._id is null, Dummy client, ignore");
                    return; // Dummy client, ignore
                }
                if (connection != null && connection.IsConnected == false)
                {
                    connection = null; created = DateTime.Now;
                }
                // Is OpenRPA connected for this user ?
                if (connection != null)
                {
                    connection.PushMessage(new RPAMessage("ping"));
                    // created = DateTime.Now;
                    // return;
                }
                if ((DateTime.Now - created).TotalSeconds < 5)
                {
                    return;
                }
                // Is user signed in ?
                // ownerexplorer = null;
                //if (ownerexplorer == null)
                var rdpip = "127.0.0.2";
                // if ((ConnectionAttempts % 2) == 1) rdpip = "127.0.0.1";
                if (PluginConfig.usefreerdp && !skiprdp)
                {
                    if (freerdp == null || freerdp.Connected == false)
                    {
                        if (freerdp == null)
                        {
                            Console.WriteLine("rdp is null");
                        }
                        if (string.IsNullOrEmpty(client.windowspassword))
                        {
                            return;
                        }
                        lastrdp = DateTime.Now;
                    }
                    if (freerdp == null)
                    {
                        freerdp = new FreeRDP.Core.RDP();
                    }
                    if (!freerdp.Connected)
                    {
                        var hostname = NativeMethods.GetHostName().ToLower();
                        try
                        {
                            Log.Information("Tesing connection to " + rdpip + " port 3389");
                            using (var tcpClient = new System.Net.Sockets.TcpClient())
                            {
                                var ipAddress  = System.Net.IPAddress.Parse(rdpip);
                                var ipEndPoint = new System.Net.IPEndPoint(ipAddress, 3389);
                                tcpClient.Connect(ipEndPoint);
                            }
                            Log.Information("Success");
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.ToString());
                            return;
                        }

                        var windowsusername = client.windowsusername.Substring(client.windowsusername.IndexOf("\\") + 1);
                        var windowsdomain   = client.windowsusername.Substring(0, client.windowsusername.IndexOf("\\"));

                        using (var imp = new Impersonator(windowsusername, windowsdomain, client.windowspassword))
                        {
                            ConnectionAttempts++;
                            if (client.windowsusername.StartsWith(hostname + @"\"))
                            {
                                // var windowsusername = client.windowsusername.Substring(hostname.Length + 1);
                                Log.Information("Connecting RDP connection to " + rdpip + " for " + windowsusername);
                                freerdp.Connect(rdpip, "", windowsusername, client.windowspassword);
                            }
                            else
                            {
                                Log.Information("Connecting RDP connection to " + rdpip + " for " + client.windowsusername);
                                freerdp.Connect(rdpip, "", client.windowsusername, client.windowspassword);
                            }
                        }
                        created = DateTime.Now;
                        return;
                    }
                    if (freerdp == null || freerdp.Connected == false)
                    {
                        return;
                    }
                }
                else if (!skiprdp)
                {
                    if (rdp == null || rdp.Connected == false)
                    {
                        if (rdp == null)
                        {
                            Console.WriteLine("rdp is null");
                        }
                        if (string.IsNullOrEmpty(client.windowspassword))
                        {
                            return;
                        }
                        lastrdp = DateTime.Now;
                    }
                    if (rdp == null)
                    {
                        rdp = new Client();
                    }
                    if (rdp.Connecting)
                    {
                        return;
                    }
                    if (!rdp.Connected)
                    {
                        try
                        {
                            Log.Information("Tesing connection to " + rdpip + " port 3389");
                            using (var tcpClient = new System.Net.Sockets.TcpClient())
                            {
                                var ipAddress  = System.Net.IPAddress.Parse(rdpip);
                                var ipEndPoint = new System.Net.IPEndPoint(ipAddress, 3389);
                                tcpClient.Connect(ipEndPoint);
                            }
                            Log.Information("Success");
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.ToString());
                            return;
                        }

                        ConnectionAttempts++;
                        var hostname = NativeMethods.GetHostName().ToLower();
                        if (client.windowsusername.StartsWith(hostname + @"\"))
                        {
                            var windowsusername = client.windowsusername.Substring(hostname.Length + 1);
                            Log.Information("Connecting RDP connection to " + rdpip + " for " + windowsusername);
                            // Task.Run(()=>rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword));
                            rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword);
                            Log.Information("Connection initialized");
                        }
                        else
                        {
                            Log.Information("Connecting RDP connection to " + rdpip + " for " + client.windowsusername);
                            // Task.Run(() => rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername, client.windowspassword));
                            rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername, client.windowspassword);
                            Log.Information("Connection initialized");
                        }
                        created = DateTime.Now;
                    }
                    if (rdp == null || rdp.Connected == false)
                    {
                        return;
                    }
                }

                NativeMethods.EnableDisablePrivilege(NativeMethods.GetSecurityEntityValue(NativeMethods.SecurityEntity.SE_ASSIGNPRIMARYTOKEN_NAME), true);
                NativeMethods.EnableDisablePrivilege(NativeMethods.GetSecurityEntityValue(NativeMethods.SecurityEntity.SE_BACKUP_NAME), true);
                NativeMethods.EnableDisablePrivilege(NativeMethods.GetSecurityEntityValue(NativeMethods.SecurityEntity.SE_DEBUG_NAME), true);
                NativeMethods.EnableDisablePrivilege(NativeMethods.GetSecurityEntityValue(NativeMethods.SecurityEntity.SE_LOAD_DRIVER_NAME), true);
                NativeMethods.EnableDisablePrivilege(NativeMethods.GetSecurityEntityValue(NativeMethods.SecurityEntity.SE_TCB_NAME), true);

                try
                {
                    var procs = Process.GetProcessesByName("explorer");
                    System.Diagnostics.Process ownerexplorer = null;
                    foreach (var explorer in procs)
                    {
                        try
                        {
                            var owner = NativeMethods.GetProcessUserName(explorer.Id).ToLower();
                            if (owner == client.windowsusername)
                            {
                                ownerexplorer = explorer;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.ToString());
                            created = DateTime.Now;
                            return;
                        }
                    }
                    if (ownerexplorer == null)
                    {
                        return;
                    }
                    System.Diagnostics.Process ownerrpa = null;
                    procs = Process.GetProcessesByName("openrpa");
                    foreach (var rpa in procs)
                    {
                        try
                        {
                            var owner = NativeMethods.GetProcessUserName(rpa.Id).ToLower();
                            if (owner == client.windowsusername)
                            {
                                ownerrpa = rpa;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.ToString());
                            created = DateTime.Now;
                            return;
                        }
                    }
                    if (ownerrpa != null)
                    {
                        //if(client.autorestart != TimeSpan.Zero && (DateTime.Now - lastheartbeat) > client.autorestart )
                        //{
                        //    try
                        //    {
                        //        lastheartbeat = DateTime.Now;
                        //        ownerrpa.Kill();
                        //    }
                        //    catch (Exception ex)
                        //    {
                        //        Log.Error(ex.ToString());
                        //    }
                        //}
                        return;
                    }
                    if (string.IsNullOrEmpty(client.openrpapath))
                    {
                        return;
                    }
                    if (!System.IO.File.Exists(client.openrpapath))
                    {
                        return;
                    }
                    var path = System.IO.Path.GetDirectoryName(client.openrpapath);
                    //if (!Program.isService)
                    //{
                    //    Log.Information("Not running as service, so just launching openrpa here");
                    //    Log.Information(client.openrpapath);
                    //    created = DateTime.Now;
                    //    Process.Start(new ProcessStartInfo(client.openrpapath) { WorkingDirectory = path });
                    //    return;
                    //}
                    // IntPtr hSessionToken = IntPtr.Zero;
                    // SessionFinder sf = new SessionFinder();
                    // hSessionToken = sf.GetLocalInteractiveSession();
                    //var windowsusername = client.windowsusername.Substring(client.windowsusername.IndexOf("\\") + 1);
                    //var windowsdomain = client.windowsusername.Substring(0, client.windowsusername.IndexOf("\\") );
                    //// hSessionToken = sf.GetSessionByUser(windowsdomain, windowsusername);
                    //Impersonation.ExecuteAppAsLoggedOnUser(client.openrpapath, null, System.IO.Path.GetDirectoryName(client.openrpapath));
                    //var runner = new InteractiveProcessRunner(client.openrpapath, hSessionToken);
                    //var p = runner.Run();

                    //if (!NativeMethods.Launch(ownerexplorer, path, @"c:\windows\system32\cmd.exe /C " + "\"" + client.openrpapath + "\""))


                    //var me = System.Security.Principal.WindowsIdentity.GetCurrent();
                    ////var mep = new System.Security.Principal.WindowsPrincipal(me);
                    //var acct = new System.Security.Principal.NTAccount(me.Name);
                    //var rule = new ProcessAccessRule(acct, ProcessAccessRights.PROCESS_ALL_ACCESS, false, System.Security.AccessControl.InheritanceFlags.None, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow);

                    //SafeTokenHandle handle = new SafeTokenHandle(ownerexplorer.Handle);
                    ////var perm = new OpenRPA.Interfaces.ProcessSecurity(handle);
                    //var perm = new OpenRPA.Interfaces.ProcessSecurity(handle);
                    //perm.AddAccessRule(rule);
                    //try
                    //{
                    //    perm.SaveChanges(handle);
                    //}
                    //catch (Exception ex)
                    //{
                    //    Log.Error(new Exception("Failed setting DACL on explore proccess: " + ex.Message, ex).ToString());
                    //    created = DateTime.Now;
                    //    return;
                    //}
                    if (Program.isService)
                    {
                        Log.Information("Attaching to user explorer and launching robot in session");
                        Log.Information(client.openrpapath);
                        created = DateTime.Now;
                        hasShownLaunchWarning = false;
                        if (!NativeMethods.Launch(ownerexplorer, path, client.openrpapath.Replace("/", @"\")))
                        {
                            Log.Error("Failed launching robot in session");
                            string errorMessage = new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()).Message;
                            Log.Error(errorMessage);
                        }
                    }
                    else if (!hasShownLaunchWarning)
                    {
                        Log.Warning("Not running as Local System, so cannot spawn processes in other users desktops");
                        created = DateTime.Now;
                        hasShownLaunchWarning = true;
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex.ToString());
                    created = DateTime.Now;
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                created = DateTime.Now;
            }
        }