private static int GetUserSessionId(string username)
 {
     try
     {
         ITerminalServicesManager manager = new TerminalServicesManager();
         using (ITerminalServer server = manager.GetLocalServer())
         {
             server.Open();
             foreach (ITerminalServicesSession session in server.GetSessions())
             {
                 NTAccount account = session.UserAccount;
                 if (account == null)
                 {
                     continue;
                 }
                 var userName = account.Value.Split('\\')[1];
                 if (userName.ToLower().Equals(username.ToLower()))
                 {
                     return(session.SessionId);
                 }
             }
         }
         return(-1);
     }
     catch (Exception)
     {
         return(-1);
     }
 }
        public Response GetUserSesssions()
        {
            var response = new Response();

            try
            {
                var manager = new TerminalServicesManager();
                using (ITerminalServer server = manager.GetLocalServer())
                {
                    server.Open();
                    var sessions = server.GetSessions()
                                   .Where(s => !string.IsNullOrEmpty(s.UserName))
                                   .Select(s => new
                    {
                        User      = s.DomainName + @"\" + s.UserName,
                        LoginDate = s.LoginTime?.ToString("g"),
                        State     = s.ConnectionState.ToString()
                    });
                    response.Data = sessions;
                    return(response);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                response.Status = Status.Error;
                response.Notifications.Add(new Notification
                {
                    Message       = ex.Message,
                    MessageDetail = ex.StackTrace,
                    Status        = Status.Error
                });
                return(response);
            }
        }
Exemple #3
0
        private static void AskQuestion(string[] args)
        {
            if (args.Length < 8)
            {
                Console.WriteLine(
                    "Usage: SessionInfo ask [server] [session id] [icon] [caption] [text] [timeout] [buttons]");
                return;
            }
            int seconds   = int.Parse(args[6]);
            int sessionId = int.Parse(args[2]);

            using (ITerminalServer server = GetServerFromName(args[1]))
            {
                server.Open();
                ITerminalServicesSession session = server.GetSession(sessionId);
                RemoteMessageBoxIcon     icon    =
                    (RemoteMessageBoxIcon)Enum.Parse(typeof(RemoteMessageBoxIcon), args[3], true);
                RemoteMessageBoxButtons buttons =
                    (RemoteMessageBoxButtons)Enum.Parse(typeof(RemoteMessageBoxButtons), args[7], true);
                RemoteMessageBoxResult result =
                    session.MessageBox(args[5], args[4], buttons, icon, default(RemoteMessageBoxDefaultButton),
                                       default(RemoteMessageBoxOptions), TimeSpan.FromSeconds(seconds), true);
                Console.WriteLine("Response: " + result);
            }
        }
        private void SearchActiveSessions(LogFileParser.foundElementInfo [] selectedUserPCs, string selectedUser)
        {
            ITerminalServicesManager manager = new TerminalServicesManager();

            for (int i = 0; i < selectedUserPCs.Length; i++)
            {
                try {
                    Ping        ping        = new Ping();
                    PingOptions pingOptions = new PingOptions();
                    pingOptions.DontFragment = true;
                    string    data   = "fff";
                    byte[]    buffer = Encoding.ASCII.GetBytes(data);
                    PingReply reply  = ping.Send(selectedUserPCs[i].name, 120, buffer, pingOptions);
                    if (reply.Status == IPStatus.Success)
                    {
                        using (ITerminalServer server = manager.GetRemoteServer(selectedUserPCs[i].name)) {
                            server.Open();
                            foreach (ITerminalServicesSession session in server.GetSessions())
                            {
                                if (session.UserName.ToLower() == selectedUser.ToLower() && session.ConnectionState == ConnectionState.Active)
                                {
                                    selectedUserPCs[i].name = "->" + selectedUserPCs[i].name + "<-";
                                }
                            }
                        }
                    }
                } catch { }
            }
        }
Exemple #5
0
        public static List <ITerminalServicesSession> GetList()
        {
            List <ITerminalServicesSession> session_list = new List <ITerminalServicesSession>();

            ITerminalServicesManager manager = new TerminalServicesManager();

            using (ITerminalServer server = manager.GetLocalServer())
            {
                server.Open();
                foreach (ITerminalServicesSession session in server.GetSessions())
                {
                    // skip the SYSTEM session
                    if (session.SessionId == 0)
                    {
                        continue;
                    }

                    // if there is no username the session is special accounts
                    if (session.UserName == String.Empty)
                    {
                        continue;
                    }

                    session_list.Add(session);
                }
            }

            return(session_list);
        }
        private void ValidateSessionsAsync()
        {
            ThreadPool.QueueUserWorkItem(async(object o) =>
            {
                ITerminalServicesManager manager = new TerminalServicesManager();
                using (ITerminalServer server = manager.GetLocalServer())
                {
                    server.Open();

                    var localSessions = server.GetSessions().Where(s => s.SessionId > 0 && (s.ConnectionState == Cassia.ConnectionState.Active));
                    var messages      = await _msgReader.GetAllMessages();

                    if (messages.Count(m => m.Command.Type == WinGuard.Domain.Enumaretions.ClientCommandType.LOGOUT) > 0 &&
                        localSessions.Any(s => messages.Any(m => m.Command.ClientIdentifier == s.SessionId.ToString())))
                    {
                        foreach (var session in localSessions.Where(s => messages.Any(m => m.Command.ClientIdentifier == s.SessionId.ToString())))
                        {
                            session.Logoff();
                        }
                        return;
                    }
                    foreach (ITerminalServicesSession session in localSessions)
                    {
                        await _authService.Login(_encryptService.EncryptMessage(session.SessionId.ToString()),
                                                 _encryptService.EncryptMessage(session.UserName));
                    }
                }
            });
        }
 public TerminalServicesSession(ITerminalServer server, int sessionId)
     : this(server, sessionId,
         NativeMethodsHelper.QuerySessionInformationForString(server.Handle, sessionId,
                                                              WTS_INFO_CLASS.WTSWinStationName),
         NativeMethodsHelper.GetConnectionState(server.Handle, sessionId))
 {
 }
Exemple #8
0
 static void RebootServer(string computerId)
 {
     using (ITerminalServer server = manager.GetRemoteServer(computerId))
     {
         server.Open();
         server.Shutdown(ShutdownType.Reboot);
     }
 }
 /// <overloads><inheritdoc /></overloads>
 /// <inheritdoc />
 public IList <ITerminalServicesSession> GetSessions(string serverName)
 {
     using (ITerminalServer server = GetRemoteServer(serverName))
     {
         server.Open();
         return(server.GetSessions());
     }
 }
 public TerminalServicesSession(ITerminalServer server, int sessionId)
     : this(
         server, sessionId,
         NativeMethodsHelper.QuerySessionInformationForString(server.Handle, sessionId,
                                                              WTS_INFO_CLASS.WTSWinStationName),
         NativeMethodsHelper.GetConnectionState(server.Handle, sessionId))
 {
 }
 /// <inheritdoc />
 public IList <ITerminalServicesSession> GetSessions()
 {
     using (ITerminalServer server = GetLocalServer())
     {
         server.Open();
         return(server.GetSessions());
     }
 }
 static void CheckBackupTime(object sender, System.Timers.ElapsedEventArgs e)
 {
     if ((int)DateTime.Now.DayOfWeek != Settings.Default.backupday)
     {
         return;
     }
     backupTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, (int)Settings.Default.backuphour, (int)Settings.Default.backupminute, 0);
     if (backupTime > DateTime.Now)
     {
         if ((int)(backupTime - DateTime.Now).TotalMinutes <= Settings.Default.startcheck)
         {
             foreach (var session in activeusers)
             {
                 if (!Notifications.ContainsKey(session.SessionId))
                 {
                     SendMessage(session.SessionId, Settings.Default.alert1box.Replace("{time}", backupTime.ToString("HH:mm")));
                     Notifications.Add(session.SessionId, DateTime.Now);
                 }
                 else
                 {
                     if ((DateTime.Now - Notifications[session.SessionId]).TotalMinutes >= (int)Settings.Default.alert_interval)
                     {
                         SendMessage(session.SessionId, Settings.Default.alert1box.Replace("{time}", backupTime.ToString("HH:mm")));
                         Notifications[session.SessionId] = DateTime.Now;
                     }
                 }
             }
         }
     }
     else
     {
         if (backupTime < startuptime)
         {
             FinishedBackups.Add(backupTime);
             return;
         }
         if (!FinishedBackups.Contains(backupTime))
         {
             ITerminalServicesManager manager = new TerminalServicesManager();
             using (ITerminalServer server = manager.GetLocalServer())
             {
                 server.Open();
                 foreach (ITerminalServicesSession session in server.GetSessions())
                 {
                     KillParusWithNotifiction(session);
                 }
             }
             if (Settings.Default.backupauto && Application.OpenForms.OfType <BackupWindow>().Count() == 0)
             {
                 bwindow = new BackupWindow();
                 bwindow.ShowDialog();
             }
         }
     }
 }
 /// <summary>
 /// Register all active sessions on server(s)
 /// </summary>
 public void RegisterSessions()
 {
     if (!checkProgramActivityTimer.Enabled)
     {
         checkProgramActivityTimer.Start();
     }
     if (!troubleShootingTimer.Enabled)
     {
         troubleShootingTimer.Start();
     }
     activeSessions = new List <ActiveSession>();
     for (int i = LogonTracerConfig.Instance.ServersToTrace.Count() - 1; i > -1; i--)
     {
         string serverName = LogonTracerConfig.Instance.ServersToTrace[i];
         try
         {
             using (ITerminalServer server = manager.GetRemoteServer(serverName))
             {
                 server.Open();
                 foreach (ITerminalServicesSession session in server.GetSessions())
                 {
                     ActiveSession activeSession = null;
                     if (session.UserAccount == null || session.ConnectionState != Cassia.ConnectionState.Active)
                     {
                         continue;
                     }
                     activeSession = repoProvider.BuildSession(session);
                     activeSessions.Add(activeSession);
                     if (activeSession.DbId.HasValue && LogonTracerConfig.Instance.LogSessionHistory)
                     {
                         repoProvider.UpdateSessionHistory(activeSession.DbId.Value, SessionUpdateDetails.StateUpdated, new Dictionary <string, string>
                         {
                             { "Old value", SessionState.ServiceDown.ToString() },
                             { "New value", SessionState.Active.ToString() }
                         });
                     }
                     repoProvider.SaveSession(activeSession);
                 }
             }
         }
         catch (Win32Exception ex)
         {
             LoggingUtils.DefaultLogger.AddLogMessage(this, MessageType.Error, "Error while trying access the server. Check Remote Desktop Services Permissions for this server and try again. Server:{0}. Message: {1}", serverName, ex.Message);
             LogonTracerConfig.Instance.ServersToTrace = LogonTracerConfig.Instance.ServersToTrace.Where(stt => stt != serverName).ToArray();
         }
         catch (Exception ex)
         {
             LoggingUtils.DefaultLogger.AddLogMessage(this, MessageType.Error, "Type: {0}. Server:{1}. Message: {2}", ex.GetType(), serverName, ex.Message);
         }
     }
     inputActivityTimer.Start();
     sessionStateUpdateTimer.Start();
     checkRepositoryTimer.Start();
 }
Exemple #14
0
 private void initServer()
 {
     try
     {
         ITerminalServicesManager manager = new TerminalServicesManager();
         server = manager.GetLocalServer();
         server.Open();
     }
     catch (Exception)
     {
         Console.WriteLine("[Error] no se ha podido identificar el terminal server.");
     }
 }
Exemple #15
0
 private static void ListProcesses(string[] args)
 {
     if (args.Length < 2)
     {
         Console.WriteLine("Usage: SessionInfo listprocesses [server]");
         return;
     }
     using (ITerminalServer server = GetServerFromName(args[1]))
     {
         server.Open();
         WriteProcesses(server.GetProcesses());
     }
 }
Exemple #16
0
 public static void LogOffSession(ITerminalServer Server, int sessionID)
 {
     using (ITerminalServer server = Server)
     {
         server.Open();
         ITerminalServicesSession session = server.GetSession(sessionID);
         session.Logoff(false);
         server.Close();
         MessageBox.Show(new Form()
         {
             TopMost = true
         }, "Wysłano instrukcję wyłączenia sesji", "Rozłączanie sesji", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
 /// <summary>
 /// Logouts all currently s
 /// </summary>
 public static void LogoutUsers()
 {
     using (ITerminalServer server = _manager.GetLocalServer())
     {
         server.Open();
         foreach (ITerminalServicesSession session in server.GetSessions())
         {
             if (session.SessionId != 0)
             {
                 session.Logoff();
             }
         }
     }
 }
Exemple #18
0
 public TerminalServicesProcess(ITerminalServer server, WIN32.Win32API.WTS_PROCESS_INFO processInfo)
 {
     _server      = server;
     _sessionId   = processInfo.SessionId;
     _processId   = processInfo.ProcessId;
     _processName = processInfo.ProcessName;
     // The SID could be null sometimes.
     // TODO: Windows 2008 R2 beta (locally) runs null for all processes except
     // those owned by the current user; is this expected? (works fine from XP client)
     if (processInfo.UserSid != IntPtr.Zero)
     {
         _securityIdentifier = new SecurityIdentifier(processInfo.UserSid);
     }
 }
 public TerminalServicesProcess(ITerminalServer server, WIN32.Win32API.WTS_PROCESS_INFO processInfo)
 {
     _server = server;
     _sessionId = processInfo.SessionId;
     _processId = processInfo.ProcessId;
     _processName = processInfo.ProcessName;
     // The SID could be null sometimes.
     // TODO: Windows 2008 R2 beta (locally) runs null for all processes except
     // those owned by the current user; is this expected? (works fine from XP client)
     if (processInfo.UserSid != IntPtr.Zero)
     {
         _securityIdentifier = new SecurityIdentifier(processInfo.UserSid);
     }
 }
Exemple #20
0
 private static void Shutdown(string[] args)
 {
     if (args.Length < 3)
     {
         Console.WriteLine("Usage: SessionInfo shutdown [server] [shutdown type]");
         return;
     }
     using (ITerminalServer server = GetServerFromName(args[1]))
     {
         server.Open();
         ShutdownType type = (ShutdownType)Enum.Parse(typeof(ShutdownType), args[2], true);
         server.Shutdown(type);
     }
 }
Exemple #21
0
        private void RefreshProcesses(object sender, ITerminalServer server, ITerminalServicesSession session, int selectedSessionID)
        {
            var tabPage      = tabControl.SelectedTab;
            var dataGridView = (DataGridView)tabPage.Controls.Find("DataGridView", true)[0];

            dataGridView.Rows.Clear();
            foreach (ITerminalServicesProcess process in new PuzzelLibrary.Terminal.Explorer().GetExplorerProcess(server))
            {
                if (process.SessionId == selectedSessionID)
                {
                    dataGridView.Rows.Add(session.Server.ServerName, session.UserName, session.WindowStationName, process.SessionId, process.ProcessId, process.ProcessName);
                }
            }
            labelSessionCount.Text = "Lista procesów: " + dataGridView.Rows.Count;
        }
Exemple #22
0
        private static void GetSessionInfo(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: SessionInfo get [server] [session id]");
                return;
            }
            int sessionId = int.Parse(args[2]);

            using (ITerminalServer server = GetServerFromName(args[1]))
            {
                server.Open();
                WriteSessionInfo(server.GetSession(sessionId));
            }
        }
Exemple #23
0
        private static void ListSessionProcesses(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: SessionInfo listsessionprocesses [server] [session id]");
                return;
            }
            int sessionId = int.Parse(args[2]);

            using (ITerminalServer server = GetServerFromName(args[1]))
            {
                server.Open();
                ITerminalServicesSession session = server.GetSession(sessionId);
                WriteProcesses(session.GetProcesses());
            }
        }
Exemple #24
0
 private static void ListSessions(string[] args)
 {
     if (args.Length < 2)
     {
         Console.WriteLine("Usage: SessionInfo listsessions [server]");
         return;
     }
     using (ITerminalServer server = GetServerFromName(args[1]))
     {
         server.Open();
         foreach (ITerminalServicesSession session in server.GetSessions())
         {
             WriteSessionInfo(session);
         }
     }
 }
Exemple #25
0
        private void LoadTSUsers()
        {
            try
            {
                listTSUser.Clear();
                TerminalServicesManager tsManager = new TerminalServicesManager();
                string[] massHosts = new string[] { "TS1", "TS2", "TS3", "TS4", "TS5", "TS6", "TS7" };

                foreach (var host in massHosts)
                {
                    using (ITerminalServer server = tsManager.GetRemoteServer(host))
                    {
                        server.Open();
                        foreach (ITerminalServicesSession session in server.GetSessions())
                        {
                            NTAccount account = session.UserAccount;
                            if (account != null)
                            {
                                TSUser user = new TSUser()
                                {
                                    DomainName        = session.DomainName,
                                    PCName            = session.ClientName,
                                    TSName            = host,
                                    UserName          = session.UserName,
                                    ConnectionState   = session.ConnectionState.ToString(),
                                    WindowStationName = session.WindowStationName,
                                    UserAccount       = account.ToString(),
                                };
                                Dispatcher.Invoke((Action)(() =>
                                {
                                    listTSUser.Add(user);
                                }));
                            }
                        }
                    }
                }

                foreach (var user in listTSUser)
                {
                    user.ClientIPAddress = (from i in listPcIPAndPcName where i.PcName.ToLower() == user.PCName.ToLower() select i.PcIP).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                Bindings.StatusBarText = ex.Message;
            }
        }
        public TerminalServicesSession(ITerminalServer server, int sessionId, string windowStationName,
                                       ConnectionState connectionState)
        {
            _server = server;
            _sessionId = sessionId;
            _windowStationName = windowStationName;
            _connectionState = connectionState;
            _clientBuildNumber = new LazyLoadedProperty<int>(GetClientBuildNumber);
            _clientIPAddress = new LazyLoadedProperty<IPAddress>(GetClientIPAddress);
            _clientDisplay = new LazyLoadedProperty<IClientDisplay>(GetClientDisplay);
            _clientName =
                NativeMethodsHelper.QuerySessionInformationForString(_server.Handle, _sessionId,
                                                                     WTS_INFO_CLASS.WTSClientName);

            // TODO: MSDN says most of these properties should be null for the console session.
            // I haven't observed this in practice on Windows Server 2000, 2003, or 2008, but perhaps this
            // should be considered.
            if (Environment.OSVersion.Version >= new Version(6, 0))
            {
                // We can actually use documented APIs in Vista / Windows Server 2008+.
                WTSINFO info =
                    NativeMethodsHelper.QuerySessionInformationForStruct<WTSINFO>(server.Handle, _sessionId,
                                                                                  WTS_INFO_CLASS.WTSSessionInfo);
                _connectTime = NativeMethodsHelper.FileTimeToDateTime(info.ConnectTime);
                _currentTime = NativeMethodsHelper.FileTimeToDateTime(info.CurrentTime);
                _disconnectTime = NativeMethodsHelper.FileTimeToDateTime(info.DisconnectTime);
                _lastInputTime = NativeMethodsHelper.FileTimeToDateTime(info.LastInputTime);
                _loginTime = NativeMethodsHelper.FileTimeToDateTime(info.LogonTime);
                _userName = info.UserName;
                _domainName = info.Domain;
            }
            else
            {
                WINSTATIONINFORMATIONW wsInfo = NativeMethodsHelper.GetWinStationInformation(server.Handle, _sessionId);
                _connectTime = NativeMethodsHelper.FileTimeToDateTime(wsInfo.ConnectTime);
                _currentTime = NativeMethodsHelper.FileTimeToDateTime(wsInfo.CurrentTime);
                _disconnectTime = NativeMethodsHelper.FileTimeToDateTime(wsInfo.DisconnectTime);
                _lastInputTime = NativeMethodsHelper.FileTimeToDateTime(wsInfo.LastInputTime);
                _loginTime = NativeMethodsHelper.FileTimeToDateTime(wsInfo.LoginTime);
                _userName =
                    NativeMethodsHelper.QuerySessionInformationForString(server.Handle, _sessionId,
                                                                         WTS_INFO_CLASS.WTSUserName);
                _domainName =
                    NativeMethodsHelper.QuerySessionInformationForString(server.Handle, _sessionId,
                                                                         WTS_INFO_CLASS.WTSDomainName);
            }
        }
        public TerminalServicesSession(ITerminalServer server, int sessionId, string windowStationName,
                                       ConnectionState connectionState)
        {
            _server            = server;
            _sessionId         = sessionId;
            _windowStationName = windowStationName;
            _connectionState   = connectionState;
            _clientBuildNumber = new LazyLoadedProperty <int>(GetClientBuildNumber);
            _clientIPAddress   = new LazyLoadedProperty <IPAddress>(GetClientIPAddress);
            _clientDisplay     = new LazyLoadedProperty <IClientDisplay>(GetClientDisplay);
            _clientName        =
                NativeMethodsHelper.QuerySessionInformationForString(_server.Handle, _sessionId,
                                                                     WTS_INFO_CLASS.WTSClientName);

            // TODO: MSDN says most of these properties should be null for the console session.
            // I haven't observed this in practice on Windows Server 2000, 2003, or 2008, but perhaps this
            // should be considered.
            if (Environment.OSVersion.Version >= new Version(6, 0))
            {
                // We can actually use documented APIs in Vista / Windows Server 2008+.
                WTSINFO info =
                    NativeMethodsHelper.QuerySessionInformationForStruct <WTSINFO>(server.Handle, _sessionId,
                                                                                   WTS_INFO_CLASS.WTSSessionInfo);
                _connectTime    = NativeMethodsHelper.FileTimeToDateTime(info.ConnectTime);
                _currentTime    = NativeMethodsHelper.FileTimeToDateTime(info.CurrentTime);
                _disconnectTime = NativeMethodsHelper.FileTimeToDateTime(info.DisconnectTime);
                _lastInputTime  = NativeMethodsHelper.FileTimeToDateTime(info.LastInputTime);
                _loginTime      = NativeMethodsHelper.FileTimeToDateTime(info.LogonTime);
                _userName       = info.UserName;
                _domainName     = info.Domain;
            }
            else
            {
                WINSTATIONINFORMATIONW wsInfo = NativeMethodsHelper.GetWinStationInformation(server.Handle, _sessionId);
                _connectTime    = NativeMethodsHelper.FileTimeToDateTime(wsInfo.ConnectTime);
                _currentTime    = NativeMethodsHelper.FileTimeToDateTime(wsInfo.CurrentTime);
                _disconnectTime = NativeMethodsHelper.FileTimeToDateTime(wsInfo.DisconnectTime);
                _lastInputTime  = NativeMethodsHelper.FileTimeToDateTime(wsInfo.LastInputTime);
                _loginTime      = NativeMethodsHelper.FileTimeToDateTime(wsInfo.LoginTime);
                _userName       =
                    NativeMethodsHelper.QuerySessionInformationForString(server.Handle, _sessionId,
                                                                         WTS_INFO_CLASS.WTSUserName);
                _domainName =
                    NativeMethodsHelper.QuerySessionInformationForString(server.Handle, _sessionId,
                                                                         WTS_INFO_CLASS.WTSDomainName);
            }
        }
        public static void Main(string[] args)
        {
            ITerminalServicesManager manager = new TerminalServicesManager();

            using (ITerminalServer server = manager.GetRemoteServer("your-server-name"))
            {
                server.Open();
                foreach (ITerminalServicesSession session in server.GetSessions())
                {
                    NTAccount account = session.UserAccount;
                    if (account != null)
                    {
                        Console.WriteLine(account);
                    }
                }
            }
        }
Exemple #29
0
        private static void KillProcess(string[] args)
        {
            if (args.Length < 4)
            {
                Console.WriteLine("Usage: SessionInfo killprocess [server] [process id] [exit code]");
                return;
            }
            int processId = int.Parse(args[2]);
            int exitCode  = int.Parse(args[3]);

            using (ITerminalServer server = GetServerFromName(args[1]))
            {
                server.Open();
                ITerminalServicesProcess process = server.GetProcess(processId);
                process.Kill(exitCode);
            }
        }
        public static bool SendMessage(string message)
        {
            ITerminalServicesManager manager = new TerminalServicesManager();

            using (ITerminalServer server = manager.GetRemoteServer(ServerIPAddress))
            {
                server.Open();
                var session = server.GetSessions().Where(x => x.UserName == UserNameOnServer).FirstOrDefault();
                if (session != null)
                {
                    var response = session.MessageBox(message, "Message for user", RemoteMessageBoxButtons.YesNo,
                                                      RemoteMessageBoxIcon.Question, RemoteMessageBoxDefaultButton.Button2, RemoteMessageBoxOptions.None, TimeSpan.Zero, true);
                    return(response == RemoteMessageBoxResult.Yes);
                }
            }
            return(false);
        }
Exemple #31
0
        private static void DisconnectSession(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: SessionInfo disconnect [server] [session id]");
                return;
            }
            string serverName = args[1];
            int    sessionId  = int.Parse(args[2]);

            using (ITerminalServer server = GetServerFromName(serverName))
            {
                server.Open();
                ITerminalServicesSession session = server.GetSession(sessionId);
                session.Disconnect();
            }
        }
        public static void SendMessage(int sessionid, string message)
        {
            ITerminalServicesManager manager = new TerminalServicesManager();

            using (ITerminalServer server = manager.GetLocalServer())
            {
                server.Open();
                try
                {
                    var session = server.GetSession(sessionid);
                    session.MessageBox(message, "Сообщение");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ошибка отправки сообщения: " + ex.Message);
                }
            }
        }
Exemple #33
0
        private static void SendMessage(string[] args)
        {
            if (args.Length < 6)
            {
                Console.WriteLine("Usage: SessionInfo message [server] [session id] [icon] [caption] [text]");
                return;
            }
            int sessionId = int.Parse(args[2]);

            using (ITerminalServer server = GetServerFromName(args[1]))
            {
                server.Open();
                ITerminalServicesSession session = server.GetSession(sessionId);
                RemoteMessageBoxIcon     icon    =
                    (RemoteMessageBoxIcon)Enum.Parse(typeof(RemoteMessageBoxIcon), args[3], true);
                session.MessageBox(args[5], args[4], icon);
            }
        }
        public TerminalServicesSession(ITerminalServer server, int sessionId)
        {
            _server = server;
            _sessionId = sessionId;

            // TODO: on Windows Server 2008, most of these values can be fetched in one shot from WTSCLIENT.
            // Do this with GroupLazyLoadedProperty.
            _clientBuildNumber = new LazyLoadedProperty<int>(GetClientBuildNumber);
            _clientIPAddress = new LazyLoadedProperty<IPAddress>(GetClientIPAddress);
            _sessionIPAddress = new LazyLoadedProperty<IPAddress>(GetSessionIPAddress);
            _remoteEndPoint = new LazyLoadedProperty<EndPoint>(GetRemoteEndPoint);
            _clientDisplay = new LazyLoadedProperty<IClientDisplay>(GetClientDisplay);
            _clientDirectory = new LazyLoadedProperty<string>(GetClientDirectory);
            _workingDirectory = new LazyLoadedProperty<string>(GetWorkingDirectory);
            _initialProgram = new LazyLoadedProperty<string>(GetInitialProgram);
            _applicationName = new LazyLoadedProperty<string>(GetApplicationName);
            _clientHardwareId = new LazyLoadedProperty<int>(GetClientHardwareId);
            _clientProductId = new LazyLoadedProperty<short>(GetClientProductId);
            _clientProtocolType = new LazyLoadedProperty<ClientProtocolType>(GetClientProtocolType);
            _clientName = new LazyLoadedProperty<string>(GetClientName);

            // TODO: MSDN says most of these properties should be null for the console session.
            // I haven't observed this in practice on Windows Server 2000, 2003, or 2008, but perhaps this
            // should be considered.
            var loader = IsVistaSp1OrHigher
                ? (GroupPropertyLoader) LoadWtsInfoProperties
                : LoadWinStationInformationProperties;
            _windowStationName = new GroupLazyLoadedProperty<string>(loader);
            _connectionState = new GroupLazyLoadedProperty<ConnectionState>(loader);
            _connectTime = new GroupLazyLoadedProperty<DateTime?>(loader);
            _currentTime = new GroupLazyLoadedProperty<DateTime?>(loader);
            _disconnectTime = new GroupLazyLoadedProperty<DateTime?>(loader);
            _lastInputTime = new GroupLazyLoadedProperty<DateTime?>(loader);
            _loginTime = new GroupLazyLoadedProperty<DateTime?>(loader);
            _userName = new GroupLazyLoadedProperty<string>(loader);
            _domainName = new GroupLazyLoadedProperty<string>(loader);
            _incomingStatistics = new GroupLazyLoadedProperty<IProtocolStatistics>(loader);
            _outgoingStatistics = new GroupLazyLoadedProperty<IProtocolStatistics>(loader);
        }
 public TerminalServicesSession(ITerminalServer server, WIN32.Win32API.WTS_SESSION_INFO sessionInfo)
     : this(server, sessionInfo.SessionID)
 {
     _windowStationName.Value = sessionInfo.pWinStationName;
     _connectionState.Value = (WIN32.Win32API.ConnectionState)sessionInfo.State;
 }
 public TerminalServicesSession(ITerminalServer server, WTS_SESSION_INFO sessionInfo)
     : this(server, sessionInfo.SessionID, sessionInfo.WinStationName, sessionInfo.State)
 {
 }