/[AnywhereTS-MSSQL]/branches/TerminalServices/TSAdminTool/TerminalServices.cs
ViewVC logotype

Diff of /branches/TerminalServices/TSAdminTool/TerminalServices.cs

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

--- branches/TerminalServices/TSAdminTool/TerminalServices.cs	2012/08/25 23:01:27	270
+++ branches/TerminalServices/TSAdminTool/TerminalServices.cs	2012/08/26 00:04:01	271
@@ -17,6 +17,9 @@
 using log4net;
 using System.Diagnostics;
 using System.ComponentModel;
+using Cassia.Impl;
+using Cassia;
+using AnywhereTS.Extensions;
 namespace AnywhereTS
 {
     public class TSManager
@@ -58,260 +61,8 @@
 #endif
         }
         #endregion
-        #region Win32 Support
-        #region Unmanaged Code
-        [DllImport("wtsapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
-        static extern IntPtr WTSOpenServer(string pServerName);
-
-        [DllImport("wtsapi32.dll", SetLastError = true)]
-        public static extern void WTSCloseServer(IntPtr hServer);
-
-        [DllImport("wtsapi32.dll", SetLastError = true)]
-        static extern int WTSEnumerateSessions(
-                         System.IntPtr hServer,
-                         int Reserved,
-                         int Version,
-                         ref System.IntPtr ppSessionInfo,
-                         ref int pCount);
-
-        /// <summary>
-        /// The WTSQuerySessionInformation function retrieves session information for the specified 
-        /// session on the specified terminal server. 
-        /// It can be used to query session information on local and remote terminal servers.
-        /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/termserv/termserv/wtsquerysessioninformation.asp
-        /// </summary>
-        /// <param name="hServer">Handle to a terminal server. Specify a handle opened by the WTSOpenServer function, 
-        /// or specify <see cref="WTS_CURRENT_SERVER_HANDLE"/> to indicate the terminal server on which your application is running.</param>
-        /// <param name="sessionId">A Terminal Services session identifier. To indicate the session in which the calling application is running 
-        /// (or the current session) specify <see cref="WTS_CURRENT_SESSION"/>. Only specify <see cref="WTS_CURRENT_SESSION"/> when obtaining session information on the 
-        /// local server. If it is specified when querying session information on a remote server, the returned session 
-        /// information will be inconsistent. Do not use the returned data in this situation.</param>
-        /// <param name="wtsInfoClass">Specifies the type of information to retrieve. This parameter can be one of the values from the <see cref="WTSInfoClass"/> enumeration type. </param>
-        /// <param name="ppBuffer">Pointer to a variable that receives a pointer to the requested information. The format and contents of the data depend on the information class specified in the <see cref="WTSInfoClass"/> parameter. 
-        /// To free the returned buffer, call the <see cref="WTSFreeMemory"/> function. </param>
-        /// <param name="pBytesReturned">Pointer to a variable that receives the size, in bytes, of the data returned in ppBuffer.</param>
-        /// <returns>If the function succeeds, the return value is a nonzero value.
-        /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
-        /// </returns>
-        [DllImport("Wtsapi32.dll", SetLastError = true)]
-        public static extern bool WTSQuerySessionInformation(
-            System.IntPtr hServer,
-            int sessionId,
-#if USE_CASSIA_WTS_INFO_CLASS
- Cassia.Impl.WTS_INFO_CLASS wtsInfoClass,
-#else
- WTSInfoClass wtsInfoClass,
-#endif
- out System.IntPtr ppBuffer,
-            out uint pBytesReturned);
-
-        [DllImport("wtsapi32.dll")]
-        static extern void WTSFreeMemory(IntPtr pMemory);
-
-        // For Lookup of MAC address
-        [DllImport("iphlpapi.dll", ExactSpelling = true, SetLastError = true)]
-        public static extern int SendARP(int DestIP, int SrcIP, [Out] byte[]
-        pMacAddr, ref int PhyAddrLen);
-        #endregion
-        #region Constants
-        public const int WTS_CURRENT_SESSION = -1;
-        #endregion
-        #region Type Definitions
-
-#if !USE_CASSIA_WTS_INFO_CLASS
-        #region WTSInfoClass
-        /// <summary>
-        /// Contains values that indicate the type of session information to retrieve in a call to the WTSQuerySessionInformation function.
-        /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa383861(v=vs.85).aspx
-        /// </summary>
-        public enum WTSInfoClass
-        {
-            /// <summary>
-            /// A null-terminated string that contains the name of the initial program that Remote Desktop Services runs when the user logs on.
-            /// </summary>
-            WTSInitialProgram,
-            /// <summary>
-            /// A null-terminated string that contains the published name of the application that the session is running.
-            /// </summary>
-            WTSApplicationName,
-            /// <summary>
-            /// A null-terminated string that contains the default directory used when launching the initial program.
-            /// </summary>
-            WTSWorkingDirectory,
-            /// <summary>
-            /// This value is not used.
-            /// </summary>
-            WTSOEMId,
-            /// <summary>
-            /// A ULONG value that contains the session identifier.
-            /// </summary>
-            WTSSessionId,
-            /// <summary>
-            /// A null-terminated string that contains the name of the user associated with the session.
-            /// </summary>
-            WTSUserName,
-            /// <summary>
-            /// A null-terminated string that contains the name of the Remote Desktop Services session. 
-            /// Note  Despite its name, specifying this type does not return the window station name. Rather, it returns the name of the Remote Desktop Services session. Each Remote Desktop Services session is associated with an interactive window station. Because the only supported window station name for an interactive window station is "WinSta0", each session is associated with its own "WinSta0" window station. For more information, see Window Stations.
-            /// </summary>
-            WTSWinStationName,
-            /// <summary>
-            /// A null-terminated string that contains the name of the domain to which the logged-on user belongs.
-            /// </summary>
-            WTSDomainName,
-            /// <summary>
-            /// The session's current connection state. For more information, see WTS_CONNECTSTATE_CLASS.
-            /// </summary>
-            WTSConnectState,
-            /// <summary>
-            /// A ULONG value that contains the build number of the client.
-            /// </summary>
-            WTSClientBuildNumber,
-            /// <summary>
-            /// A null-terminated string that contains the name of the client.
-            /// </summary>
-            WTSClientName,
-            /// <summary>
-            /// A null-terminated string that contains the directory in which the client is installed.
-            /// </summary>
-            WTSClientDirectory,
-            /// <summary>
-            /// A USHORT client-specific product identifier.
-            /// </summary>
-            WTSClientProductId,
-            /// <summary>
-            /// A ULONG value that contains a client-specific hardware identifier. This option is reserved for future use. WTSQuerySessionInformation will always return a value of 0.
-            /// </summary>
-            WTSClientHardwareId,
-            /// <summary>
-            /// The network type and network address of the client. For more information, see WTS_CLIENT_ADDRESS.
-            /// The IP address is offset by two bytes from the start of the Address member of the WTS_CLIENT_ADDRESS structure.
-            /// </summary>
-            WTSClientAddress,
-            /// <summary>
-            /// Information about the display resolution of the client. For more information, see WTS_CLIENT_DISPLAY.
-            /// </summary>
-            WTSClientDisplay,
-            /// <summary>
-            /// A USHORT value that specifies information about the protocol type for the session. This is one of the following values.
-            /// 0: The console session.
-            /// 1: This value is retained for legacy purposes.
-            /// 2: The RDP protocol.
-            /// </summary>
-            WTSClientProtocolType,
-            /// <summary>
-            /// This value returns FALSE. If you call GetLastError to get extended error information, GetLastError returns ERROR_NOT_SUPPORTED. 
-            /// Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, and Windows 2000:  This value is not used.
-            /// </summary>
-            WTSIdleTime,
-            /// <summary>
-            /// This value returns FALSE. If you call GetLastError to get extended error information, GetLastError returns ERROR_NOT_SUPPORTED. 
-            /// Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, and Windows 2000:  This value is not used.
-            /// </summary>
-            WTSLogonTime,
-            /// <summary>
-            /// This value returns FALSE. If you call GetLastError to get extended error information, GetLastError returns ERROR_NOT_SUPPORTED. 
-            /// Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, and Windows 2000:  This value is not used.
-            /// </summary>
-            WTSIncomingBytes,
-            /// <summary>
-            /// This value returns FALSE. If you call GetLastError to get extended error information, GetLastError returns ERROR_NOT_SUPPORTED. 
-            /// Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, and Windows 2000:  This value is not used.
-            /// </summary>
-            WTSOutgoingBytes,
-            /// <summary>
-            /// This value returns FALSE. If you call GetLastError to get extended error information, GetLastError returns ERROR_NOT_SUPPORTED. 
-            /// Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, and Windows 2000:  This value is not used.
-            /// </summary>
-            WTSIncomingFrames,
-            /// <summary>
-            /// This value returns FALSE. If you call GetLastError to get extended error information, GetLastError returns ERROR_NOT_SUPPORTED.
-            /// Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, and Windows 2000:  This value is not used.
-            /// </summary>
-            WTSOutgoingFrames,
-            /// <summary>
-            /// Information about a Remote Desktop Connection (RDC) client. For more information, see WTSCLIENT.
-            /// Windows Vista, Windows Server 2003, Windows XP, and Windows 2000:  This value is not supported. 
-            /// This value is supported beginning with Windows Server 2008 and Windows Vista with SP1.
-            /// </summary>
-            WTSClientInfo,
-            /// <summary>
-            /// Information about a client session on an RD Session Host server. For more information, see WTSINFO. 
-            /// Windows Vista, Windows Server 2003, Windows XP, and Windows 2000:  This value is not supported.
-            /// This value is supported beginning with Windows Server 2008 and Windows Vista with SP1.
-            /// </summary>
-            WTSSessionInfo,
-            /// <summary>
-            /// Extended information about a session on an RD Session Host server. For more information, see WTSINFOEX.
-            /// Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, and Windows 2000:  This value is not supported.
-            /// </summary>
-            WTSSessionInfoEx,
-            /// <summary>
-            /// Information about the configuration of an RD Session Host server. 
-            /// Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, and Windows 2000:  This value is not supported.
-            /// </summary>
-            WTSConfigInfo,
-            /// <summary>
-            /// This value is not supported.
-            /// </summary>
-            WTSValidationInfo,
-            /// <summary>
-            /// A WTS_SESSION_ADDRESS structure that contains the IPv4 address assigned to the session. If the session does not have a virtual IP address, the WTSQuerySessionInformation function returns ERROR_NOT_SUPPORTED.
-            /// Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, and Windows 2000:  This value is not supported.
-            /// </summary>
-            WTSSessionAddressV4,
-            /// <summary>
-            /// Determines whether the current session is a remote session. The WTSQuerySessionInformation function returns a value of TRUE to indicate that the current session is a remote session, and FALSE to indicate that the current session is a local session. This value can only be used for the local machine, so the hServer parameter of the WTSQuerySessionInformation function must contain WTS_CURRENT_SERVER_HANDLE.
-            /// Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, and Windows 2000:  This value is not supported.
-            /// </summary>
-            WTSIsRemoteSession,
-        };
-        #endregion
-#endif
-
-        // Selected info for terminal server sessions
-        public struct TS_SESSION_INFO
-        {
-            public int sessionID;
-            public string ipAddress; // The IP address of the client
-            public string macAddress; // The MAC address of the client
-            public string name; // The (netbios) name of the client
-            public string username; // User logged in to the session, if any.
-            public Cassia.ConnectionState state; // The state of the session
-            public int HorizontalResolution; // Vertical screen res for the session
-            public int VerticalResolution;  // Horiz screen res for the session
-            public int ColorDepth; // Screen color depth for the session
-        };
-        #endregion
-        #endregion
-
-        public static IntPtr OpenServer(String Name)
-        {
-            LogDebugVerboseMessage("OpenServer(String Name): Name={0}", Name);
-            IntPtr server = WTSOpenServer(Name);
-            int error = Marshal.GetLastWin32Error();
-            if (error != 0)
-            {
-                Win32Exception exc = new Win32Exception(error);
-                LogErrorVerboseMessage("OpenServer::WTSOpenServer({1}){0}Error:{0}{2}", System.Environment.NewLine, Name, exc.ToString());
-            }
-            LogDebugVerboseMessage("OpenServer(String Name): server={0}", server);
-            return server;
-        }
-        public static void CloseServer(IntPtr ServerHandle)
-        {
-            LogDebugVerboseMessage("CloseServer(IntPtr ServerHandle): Closing handle={0}", ServerHandle.ToString());
-            WTSCloseServer(ServerHandle);
-            int error = Marshal.GetLastWin32Error();
-            if (error != 0)
-            {
-                Win32Exception exc = new Win32Exception(error);
-                LogErrorVerboseMessage("CloseServer::WTSCloseServer({1}){0}Error:{0}{2}", System.Environment.NewLine, ServerHandle.ToInt32(), exc.ToString());
-            }
-            LogDebugVerboseMessage("CloseServer(IntPtr ServerHandle): Closed Handle");
-        }
-
 
+       
         // Return address for a terminal server session.
         // WTSClientAddress gives a pointer to a WTS_CLIENT_ADDRESS structure containing
         // the network type and network address of the client. If the function is called 
@@ -319,563 +70,83 @@
         // Note that the first byte of the IP address returned in the ppBuffer 
         // parameter will be located at an offset of two bytes from the first location
         // of the buffer.
-        private static string GetTSClientAddress(int sessionID, IntPtr server)
+        private static string GetTSClientAddress(int sessionID, ITerminalServerHandle server)
         {
-            System.IntPtr ppBuffer = System.IntPtr.Zero;
-            uint pBytesReturned = 0;
-            StringBuilder builder = new StringBuilder();
-
-            // Interface avec API
-            Cassia.Impl.WTS_CLIENT_ADDRESS wtsAdr = new Cassia.Impl.WTS_CLIENT_ADDRESS();
-
-
-            if (WTSQuerySessionInformation(
-                server,
-                sessionID,
-#if USE_CASSIA_WTS_INFO_CLASS
-                Cassia.Impl.WTS_INFO_CLASS.WTSClientAddress,
-#else
- WTSInfoClass.WTSClientAddress,
-#endif
- out ppBuffer,
-                out pBytesReturned))
-            {
-                wtsAdr.Address = new Byte[pBytesReturned - 1];
-                int run = (int)ppBuffer; // pointeur sur les données
-                Type t = typeof(Byte);
-                Type t1 = typeof(uint);
-
-                int uintSize = Marshal.SizeOf(t1);
-                int byteSize = Marshal.SizeOf(t);
-
-                wtsAdr.AddressFamily = (int)Marshal.ReadInt32((System.IntPtr)run);
-
-                // Address family can be only:
-                // AF_UNSPEC  = 0 (unspecified)
-                // AF_INET    = 2 (internetwork: UDP, TCP, etc.)
-                // AF_IPX     = AF_NS = 6 (IPX protocols: IPX, SPX, etc.)
-                // AF_NETBIOS = 17 (NetBios-style addresses)
-
-                //run+=uintSize;
-                //run+=dataSize;			
-                /*switch(wtsAdr.AddressFamily)
-                {
-                    case 0:builder.Append("AF_UNSPEC");
-                        break;
-                    case 1:builder.Append("AF_INET");
-                        break;
-                    case 2:builder.Append("AF_IPX");
-                        break;
-                    case 3:builder.Append("AF_NETBIOS");
-                        break;
-                }*/
-                for (int i = 0; i < pBytesReturned - 1; i++)
-                {
-                    wtsAdr.Address[i] = Marshal.ReadByte((System.IntPtr)run);
-                    run += byteSize;
-                    // TO GET and to SEE ALL the DATA
-                    //builder.Append(wtsAdr.Address[i].ToString()+"-");
-                }
-                //builder.Append("-");
-
-                // The IP address is located in bytes 2, 3, 4, and 5. The other bytes are not used. 
-                // If AddressFamily returns AF_UNSPEC, the first byte in Address 
-                // is initialized to zero. 
-
-                // Check if the returned address is an IP address
-                if (wtsAdr.AddressFamily == 2)
-                {   // It is an IP address
-                    builder.Append((wtsAdr.Address[4 + 2]).ToString());
-                    builder.Append(".");
-                    builder.Append((wtsAdr.Address[4 + 3]).ToString());
-                    builder.Append(".");
-                    builder.Append((wtsAdr.Address[4 + 4]).ToString());
-                    builder.Append(".");
-                    builder.Append((wtsAdr.Address[4 + 5]).ToString());
-                }
-            }
-            int error = Marshal.GetLastWin32Error();
-            if (error != 0)
-            {
-                Win32Exception exc = new Win32Exception(error);
-                LogErrorVerboseMessage("GetTSClientAddress::WTSQuerySessionInformation({1}){0}Error:{0}{2}", System.Environment.NewLine, server.ToInt32(), exc.ToString());
-            }
-            WTSFreeMemory(ppBuffer);
-            return builder.ToString();
+            TerminalServer ts = new TerminalServer(server);
+            ts.Open();
+            var session = ts.GetSession(sessionID);
+            var ClientIPAddress = session.ClientIPAddress;
+            ts.Close();
+            return ClientIPAddress.ToString();
         }
 
         // Get display parameters for a user session on a terminal server
         // In: SessionID = identifier for the session
         // In: server = server handle for the server that the session resides on.  
-        private static void GetTSClientDisplay(int sessionID, IntPtr server, out int horizontalResolution, out int verticalResolution, out int colorDepth)
-        {
-            Cassia.Impl.WTS_CLIENT_DISPLAY clientDisplay = Cassia.Impl.WTS_CLIENT_DISPLAY.Empty;
-            horizontalResolution = clientDisplay.HorizontalResolution;
-            verticalResolution = clientDisplay.VerticalResolution;
-            colorDepth = clientDisplay.ColorDepth;
-            System.IntPtr ppBuffer = System.IntPtr.Zero;
-            uint pBytesReturned = 0;
-            StringBuilder sDisplay = new StringBuilder();
-            if (WTSQuerySessionInformation(
-                server,
-                sessionID,
-#if USE_CASSIA_WTS_INFO_CLASS
-                Cassia.Impl.WTS_INFO_CLASS.WTSClientDisplay,
-#else
- WTSInfoClass.WTSClientDisplay,
-#endif
- out ppBuffer,
-                out pBytesReturned))
-            {
-                clientDisplay = (Cassia.Impl.WTS_CLIENT_DISPLAY)Marshal.PtrToStructure(ppBuffer, typeof(Cassia.Impl.WTS_CLIENT_DISPLAY));
-                horizontalResolution = clientDisplay.HorizontalResolution;
-                verticalResolution = clientDisplay.VerticalResolution;
-                colorDepth = clientDisplay.ColorDepth;
-            }
-            int error = Marshal.GetLastWin32Error();
-            if (error != 0)
-            {
-                Win32Exception exc = new Win32Exception(error);
-                LogErrorVerboseMessage("GetTSClientDisplay::WTSQuerySessionInformation({1}){0}Error:{0}{2}", System.Environment.NewLine, server.ToInt32(), exc.ToString());
-            }
-            LogDebugVerboseMessage("GetTSClientDisplay::server.ToInt32()={0}", server.ToInt32());
-            LogDebugVerboseMessage("GetTSClientDisplay::sessionID={0}", sessionID);
-            LogDebugVerboseMessage("GetTSClientDisplay::horizontalResolution={0}", horizontalResolution);
-            LogDebugVerboseMessage("GetTSClientDisplay::verticalResolution={0}", verticalResolution);
-            LogDebugVerboseMessage("GetTSClientDisplay::colorDepth={0}", colorDepth);
-            WTSFreeMemory(ppBuffer);
-        }
-
-
-        // Get Mac from IP, using ARP
-        private static string GetMACFromIP(string ipString)
-        {
-
-            IPAddress ip = IPAddress.Parse(ipString); // Actual IP
-            int rv;
-            string macStr;
-            byte[] mac = new byte[6];
-            int maclen = mac.Length;
-
-            rv = SendARP(BitConverter.ToInt32(ip.GetAddressBytes(), 0), 0, mac, ref maclen);
-            if (rv == 0) // If not 0, error
-            {
-                // macStr = BitConverter.ToString(mac, 0, 6);
-                macStr = BitConverter.ToString(mac, 0, 1) + BitConverter.ToString(mac, 1, 1) + BitConverter.ToString(mac, 2, 1)
-                    + BitConverter.ToString(mac, 3, 1) + BitConverter.ToString(mac, 4, 1) + BitConverter.ToString(mac, 5, 1);
-            }
-            else
-            {
-                macStr = "";
-            }
-            return macStr;
-        }
-
-
-        private static string GetTSUserName(int sessionID, IntPtr server)
+        private static void GetTSClientDisplay(int sessionID, ITerminalServerHandle server, out int horizontalResolution, out int verticalResolution, out int colorDepth)
         {
-            System.IntPtr ppBuffer = System.IntPtr.Zero;
-            uint pBytesReturned = 0;
-            string currentUserName = "";
-
-            if (WTSQuerySessionInformation(
-                server,
-                sessionID,
-#if USE_CASSIA_WTS_INFO_CLASS
-                Cassia.Impl.WTS_INFO_CLASS.WTSUserName,
-#else
- WTSInfoClass.WTSUserName,
-#endif
- out ppBuffer,
-                out pBytesReturned))
-            {
-                currentUserName = Marshal.PtrToStringAnsi(ppBuffer);
-            }
-            int error = Marshal.GetLastWin32Error();
-            if (error != 0)
-            {
-                Win32Exception exc = new Win32Exception(error);
-                LogErrorVerboseMessage("GetTSUserName::WTSQuerySessionInformation({1}){0}Error:{0}{2}", System.Environment.NewLine, server.ToInt32(), exc.ToString());
-            }
-            WTSFreeMemory(ppBuffer);
-            LogDebugVerboseMessage("GetTSUserName::currentUserName={0}", currentUserName);
+            TerminalServer ts = new TerminalServer(server);
+            ts.Open();
+            var session = ts.GetSession(sessionID);
+            var ClientDisplay = session.ClientDisplay;
+            horizontalResolution = ClientDisplay.HorizontalResolution;
+            verticalResolution = ClientDisplay.VerticalResolution;
+            colorDepth = ClientDisplay.BitsPerPixel;
+            ts.Close();
+        }
+        
+
+        private static string GetTSUserName(int sessionID, ITerminalServerHandle server)
+        {            
+            TerminalServer ts = new TerminalServer(server);
+            ts.Open();
+            var session = ts.GetSession(sessionID);
+            var currentUserName = session.UserName;
+            ts.Close();
             return currentUserName;
         }
 
-        public static string GetTSClientName(int sessionID, IntPtr server)
+        public static string GetTSClientName(int sessionID, ITerminalServerHandle server)
         {
-            string clientName = "";
-            if (!System.Windows.Forms.SystemInformation.TerminalServerSession)
-            {
-                System.IntPtr ppBuffer = System.IntPtr.Zero;
-                int adrBuffer;
-                uint pBytesReturned = 0;
-                if (WTSQuerySessionInformation(
-                    server,
-                    sessionID,
-#if USE_CASSIA_WTS_INFO_CLASS
-                Cassia.Impl.WTS_INFO_CLASS.WTSClientName,
-#else
- WTSInfoClass.WTSClientName,
-#endif
- out ppBuffer,
-                    out pBytesReturned))
-                {
-                    adrBuffer = (int)ppBuffer;
-                    clientName = Marshal.PtrToStringAnsi((System.IntPtr)adrBuffer);
-                }
-
-                WTSFreeMemory(ppBuffer);
-            }
-            else
-            {
-                clientName = System.Environment.MachineName;
-            }
-            LogDebugVerboseMessage("GetTSClientName::clientName={0}", clientName);
-            return clientName;
+            TerminalServer ts = new TerminalServer(server);
+            ts.Open();
+            var session = ts.GetSession(sessionID);
+            var ClientName = session.ClientName;
+            ts.Close();
+            return ClientName;
         }
 
         // List all sessions on all registered terminal servers and return in a list with selected data for each session.
-        public static List<TS_SESSION_INFO> ListSessions()
+        public static List<ITerminalServicesSession> ListSessions()
         {
-            List<TS_SESSION_INFO> ret = new List<TS_SESSION_INFO>();
-            if (ATSGlobals.terminalServerConfig == 0) // This server is a terminal server
-            {
-                ListSessions(ret, "localhost"); // Add sessions from local server
-            }
-
-            // Add sessions from other terminal servers
-            atsDataSet.TerminalServerDataTable datatableTerminalServer;
-            datatableTerminalServer = new atsDataSet.TerminalServerDataTable();
-            ProSupport.terminalServerTableAdapter.Fill(datatableTerminalServer);
-            foreach (DataRow row in datatableTerminalServer.Rows)
-            {
-                string strError = "";
-                try
-                {
-                    strError = ListSessions(ret, row["Path"].ToString());
-                }
-                catch
-                {
-                    //MessageBox.Show("Error: Could not retrieve session data from server '" + row["Path"].ToString() + "'. Error 39092.");
-                }
-                if (strError.Length != 0)
-                {
-                    //MessageBox.Show("Warning: " + strError, "AnywhereTS"); 
-                }
-            }
-            return ret;
+            return ListSessions(GetMyName());
         }
 
         // List all sessions on the terminal server and return in a list with selected data for each session.
-        public static List<TS_SESSION_INFO> ListSessions(String serverName)
+        public static List<ITerminalServicesSession> ListSessions(String serverName)
         {
-            IntPtr server = IntPtr.Zero;
-            List<TS_SESSION_INFO> ret = new List<TS_SESSION_INFO>();
-            server = OpenServer(serverName);
-
-            try
-            {
-                IntPtr ppSessionInfo = IntPtr.Zero;
-
-                Int32 count = 0;
-                Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count);
-                int error = Marshal.GetLastWin32Error();
-                if (error != 0)
-                {
-                    Win32Exception exc = new Win32Exception(error);
-                    LogErrorVerboseMessage("ListSessions(String serverName)::WTSEnumerateSessions({1}){0}Error:{0}{2}", System.Environment.NewLine, server.ToInt32(), exc.ToString());
-                }
-                Int32 dataSize = Marshal.SizeOf(typeof(Cassia.Impl.WTS_SESSION_INFO));
-                Int32 current = (int)ppSessionInfo;
-                TS_SESSION_INFO CurrentClientInfo;
-
-                if (retval != 0)
-                {
-                    for (int i = 0; i < count; i++) // Iterate through all sessions on the server
-                    {
-                        Cassia.Impl.WTS_SESSION_INFO si = (Cassia.Impl.WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(Cassia.Impl.WTS_SESSION_INFO));
-                        current += dataSize;
-                        CurrentClientInfo.sessionID = si.SessionID;
-                        CurrentClientInfo.ipAddress = GetTSClientAddress(si.SessionID, server);
-                        CurrentClientInfo.name = GetTSClientName(si.SessionID, server);
-                        CurrentClientInfo.username = GetTSUserName(si.SessionID, server);
-                        CurrentClientInfo.state = si.State;
-                        if (CurrentClientInfo.name != "")
-                        {
-                            CurrentClientInfo.macAddress = ProSupport.GetMacAddressFromNameAndDatabase(CurrentClientInfo.name);
-                        }
-                        else
-                        {
-                            CurrentClientInfo.macAddress = "";
-                        }
-                        LogDebugVerboseMessage("ListSessions(String serverName)::ServerName={0}", serverName);
-                        GetTSClientDisplay(si.SessionID, server, out CurrentClientInfo.HorizontalResolution, out CurrentClientInfo.VerticalResolution, out CurrentClientInfo.ColorDepth);
-                        ret.Add(CurrentClientInfo);
-                    }
-
-                    WTSFreeMemory(ppSessionInfo);
-                }
-            }
-
-            finally
-            {
-                try
-                {
-                    CloseServer(server);
-                }
-                catch (Exception e)
-                {
-                    MessageBox.Show("Error could not close terminal server connection (63210)");
-                    using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
-                    {
-                        Logging.ATSAdminLog.Error("Error could not close terminal server connection (63210)");
-                    }
-                }
-            }
-            return ret;
+            TerminalServer ts = new TerminalServer(new RemoteServerHandle(serverName));
+            List<ITerminalServicesSession> sessions = new List<ITerminalServicesSession>();
+            var ISessions = ts.GetSessions();
+            foreach (var session in ISessions) { sessions.Add(session); }
+            return sessions;
         }
-
-        // List all sessions on the terminal server and return in a list with selected data for each session.
-        public static List<AtsSession> ListTSsessions(String serverName)
-        {
-            IntPtr server = IntPtr.Zero;
-            List<AtsSession> ret = new List<AtsSession>();
-            server = OpenServer(serverName);
-
-            try
-            {
-                IntPtr ppSessionInfo = IntPtr.Zero;
-
-                Int32 count = 0;
-                Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count);
-                int error = Marshal.GetLastWin32Error();
-                if (error != 0)
-                {
-                    Win32Exception exc = new Win32Exception(error);
-                    LogErrorVerboseMessage("ListTSsessions(String serverName)::WTSEnumerateSessions({1}){0}Error:{0}{2}", System.Environment.NewLine, server.ToInt32(), exc.ToString());
-                }
-                Int32 dataSize = Marshal.SizeOf(typeof(Cassia.Impl.WTS_SESSION_INFO));
-                Int32 current = (int)ppSessionInfo;
-                AtsSession CurrentSession = new AtsSession();
-
-                if (retval != 0)
-                {
-                    for (int i = 0; i < count; i++) // Iterate through all sessions on the server
-                    {
-                        Cassia.Impl.WTS_SESSION_INFO si = (Cassia.Impl.WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(Cassia.Impl.WTS_SESSION_INFO));
-                        current += dataSize;
-                        CurrentSession.sessionID = si.SessionID;
-                        CurrentSession.ipAddress = GetTSClientAddress(si.SessionID, server);
-                        CurrentSession.name = GetTSClientName(si.SessionID, server);
-                        CurrentSession.username = GetTSUserName(si.SessionID, server);
-                        CurrentSession.state = si.State;
-                        if (CurrentSession.name != "")
-                        {
-                            CurrentSession.macAddress = ProSupport.GetMacAddressFromNameAndDatabase(CurrentSession.name);
-                        }
-                        else
-                        {
-                            CurrentSession.macAddress = "";
-                        }
-                        LogDebugVerboseMessage("ListTSsessions(String serverName)::ServerName={0}", serverName);
-                        GetTSClientDisplay(si.SessionID, server, out CurrentSession.HorizontalResolution, out CurrentSession.VerticalResolution, out CurrentSession.ColorDepth);
-                        ret.Add(CurrentSession);
-                    }
-
-                    WTSFreeMemory(ppSessionInfo);
-                }
-            }
-
-            finally
-            {
-                try
-                {
-                    CloseServer(server);
-                }
-                catch (Exception e)
-                {
-                    MessageBox.Show("Error could not close terminal server connection (63210)");
-                    using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
-                    {
-                        Logging.ATSAdminLog.Error("Error could not close terminal server connection (63210)");
-                    }
-                }
-            }
-            return ret;
-        }
-
-
-        // List all sessions on the terminal server and adds them to list with selected data for each session.
-        // Returns error message or "" if everything went ok.
-        public static string ListSessions(List<TS_SESSION_INFO> SessionInfo, String serverName)
-        {
-            IntPtr server = IntPtr.Zero;
-            server = OpenServer(serverName);
-            string strError = "Could not retrieve session data from server '" + serverName + "'"; // Assume something went wrong
-            if (server != IntPtr.Zero)
-            {
-                try
-                {
-                    IntPtr ppSessionInfo = IntPtr.Zero;
-
-                    Int32 count = 0;
-                    Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count);
-                    int error = Marshal.GetLastWin32Error();
-                    if (error != 0)
-                    {
-                        Win32Exception exc = new Win32Exception(error);
-                        LogErrorVerboseMessage("ListSessions(List<TS_SESSION_INFO> SessionInfo, String serverName)::WTSEnumerateSessions({1}:name={2}){0}Error:{0}{3}", System.Environment.NewLine, server.ToInt32(), serverName, exc.ToString());
-                    }
-                    Int32 dataSize = Marshal.SizeOf(typeof(Cassia.Impl.WTS_SESSION_INFO));
-                    Int32 current = (int)ppSessionInfo;
-                    TS_SESSION_INFO CurrentClientInfo;
-
-                    if (retval != 0)
-                    {
-                        for (int i = 0; i < count; i++)
-                        {
-                            Cassia.Impl.WTS_SESSION_INFO si = (Cassia.Impl.WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(Cassia.Impl.WTS_SESSION_INFO));
-                            current += dataSize;
-                            CurrentClientInfo.sessionID = si.SessionID;
-                            CurrentClientInfo.ipAddress = GetTSClientAddress(si.SessionID, server);
-                            CurrentClientInfo.name = GetTSClientName(si.SessionID, server);
-                            CurrentClientInfo.username = GetTSUserName(si.SessionID, server);
-                            CurrentClientInfo.state = si.State;
-                            if (CurrentClientInfo.name != "")
-                            {
-                                CurrentClientInfo.macAddress = ProSupport.GetMacAddressFromNameAndDatabase(CurrentClientInfo.name);
-                            }
-                            else
-                            {
-                                CurrentClientInfo.macAddress = "";
-                            }
-                            LogDebugVerboseMessage("ListSessions(List<TS_SESSION_INFO> SessionInfo, String serverName)::serverName={0}", serverName);
-                            GetTSClientDisplay(si.SessionID, server, out CurrentClientInfo.HorizontalResolution, out CurrentClientInfo.VerticalResolution, out CurrentClientInfo.ColorDepth);
-                            SessionInfo.Add(CurrentClientInfo);
-                        }
-
-                        WTSFreeMemory(ppSessionInfo);
-                    }
-                }
-
-                finally
-                {
-                    try
-                    {
-                        CloseServer(server);
-                    }
-                    finally
-                    {
-                        // Catch exeception
-                    }
-                }
-                strError = ""; // Everything went ok
-            } // end if (server != null)
-            return strError;
-        }
-
-        // List all sessions on the terminal server and adds them to list with selected data for each session.
-        // Returns error message or "" if everything went ok.
-        public static string ListSessions(List<AtsSession> SessionInfo, String serverName)
-        {
-            IntPtr server = IntPtr.Zero;
-            server = OpenServer(serverName);
-            string strError = "Could not retrieve session data from server '" + serverName + "'"; // Assume something went wrong
-            if (server != IntPtr.Zero)
-            {
-                try
-                {
-                    IntPtr ppSessionInfo = IntPtr.Zero;
-
-                    Int32 count = 0;
-                    Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count);
-                    int error = Marshal.GetLastWin32Error();
-                    if (error != 0)
-                    {
-                        Win32Exception exc = new Win32Exception(error);
-                        LogErrorVerboseMessage("ListSessions(List<AtsSession> SessionInfo, String serverName)::WTSEnumerateSessions({1}:name={2}){0}Error:{0}{3}", System.Environment.NewLine, server.ToInt32(), serverName, exc.ToString());
-                    }
-                    Int32 dataSize = Marshal.SizeOf(typeof(Cassia.Impl.WTS_SESSION_INFO));
-                    Int32 current = (int)ppSessionInfo;
-
-                    if (retval != 0)
-                    {
-                        for (int i = 0; i < count; i++)
-                        {
-                            AtsSession currentSession = new AtsSession();
-                            Cassia.Impl.WTS_SESSION_INFO si = (Cassia.Impl.WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(Cassia.Impl.WTS_SESSION_INFO));
-                            current += dataSize;
-                            currentSession.TerminalServerName = serverName;
-                            currentSession.sessionID = si.SessionID;
-                            currentSession.ipAddress = GetTSClientAddress(si.SessionID, server);
-                            currentSession.name = GetTSClientName(si.SessionID, server);
-                            currentSession.username = GetTSUserName(si.SessionID, server);
-                            currentSession.state = si.State;
-                            if (currentSession.name != "")
-                            {
-                                currentSession.macAddress = ProSupport.GetMacAddressFromNameAndDatabase(currentSession.name);
-                            }
-                            else
-                            {
-                                currentSession.macAddress = "";
-                            }
-                            LogDebugVerboseMessage("ListSessions(List<AtsSession> SessionInfo, String serverName)::serverName={0}", serverName);
-                            GetTSClientDisplay(si.SessionID, server, out currentSession.HorizontalResolution, out currentSession.VerticalResolution, out currentSession.ColorDepth);
-                            SessionInfo.Add(currentSession);
-                        }
-
-                        WTSFreeMemory(ppSessionInfo);
-                    }
-                }
-                finally
-                {
-                    try
-                    {
-                        CloseServer(server);
-                    }
-                    finally
-                    {
-                        // Catch exeception
-                    }
-                }
-                strError = ""; // Everything went ok
-            } // end if (server != null)
-
-            return strError;
-        }
-
         // Return matching session for a macAddress, or null, if the mac address is not used in any session.
         // Called when a child node selected in the tree view
-        public static AtsSession GetSession(string macAddress)
+        public static ITerminalServicesSession GetSession(string macAddress)
         {
             LogDebugVerboseMessage("GetSession(string macAddress)::called");
             foreach (AtsTerminalServer ts in AtsEnvironment.TerminalServers)
             {
-                LogDebugVerboseMessage("GetSession(string macAddress)::ts.networkPath={0}", ts.networkPath == null ? string.Empty : ts.networkPath);
-                LogDebugVerboseMessage("GetSession(string macAddress)::ts.Online={0}", ts.Online);
-                LogDebugVerboseMessage("GetSession(string macAddress)::ts.Session.Count={0}", ts.Session == null ? 0 : ts.Session.Count);
-                LogDebugVerboseMessage("GetSession(string macAddress)::ts.strError={0}", ts.strError == null ? string.Empty : ts.strError);
-                foreach (AtsSession session in ts.Session)
+                TerminalServer real_ts = new TerminalServer(new RemoteServerHandle(ts.networkPath));
+                foreach (var t in real_ts.GetSessions())
                 {
-                    int session_index = ts.Session.IndexOf(session);
-
-                    LogDebugVerboseMessage("GetSession(string macAddress)::session[{0}].TerminalServerName={1}", session_index, session.TerminalServerName == null ? string.Empty : session.TerminalServerName);
-                    LogDebugVerboseMessage("GetSession(string macAddress)::session[{0}].state={1}", session_index, StateToString(session.state));
-                    LogDebugVerboseMessage("GetSession(string macAddress)::session[{0}].sessionID={1}", session_index, session.sessionID);
-                    LogDebugVerboseMessage("GetSession(string macAddress)::session[{0}].name={1}", session_index, session.name == null ? string.Empty : session.name);
-                    LogDebugVerboseMessage("GetSession(string macAddress)::session[{0}].username={1}", session_index, session.username == null ? string.Empty : session.username);
-                    LogDebugVerboseMessage("GetSession(string macAddress)::session[{0}].ipAddress={1}", session_index, session.ipAddress == null ? string.Empty : session.ipAddress);
-                    LogDebugVerboseMessage("GetSession(string macAddress)::session[{0}].macAddress={1}", session_index, session.macAddress == null ? string.Empty : session.macAddress);
-                    LogDebugVerboseMessage("GetSession(string macAddress)::session[{0}].HorizontalResolution={1}", session_index, session.HorizontalResolution);
-                    LogDebugVerboseMessage("GetSession(string macAddress)::session[{0}].VerticalResolution={1}", session_index, session.VerticalResolution);
-                    LogDebugVerboseMessage("GetSession(string macAddress)::session[{0}].ColorDepth={1}", session_index, session.ColorDepth);
-
-                    // Try to find the MAC adress for the selected client in any of the sessions.
-                    if (session.macAddress == macAddress)
+                    int session_index = real_ts.GetSessions().IndexOf(t);
+                    string mac = t.ClientIPAddress.ToMacAddress();
+                    if (mac == macAddress)
                     {
                         LogDebugVerboseMessage("GetSession(string macAddress)::session[{0}] found for macAddress={1}", session_index, macAddress);
-                        return session;
+                        return t;
                     }
                 }
             }
@@ -915,9 +186,11 @@
         }
         public static string GetMyName()
         {
-            string name = GetTSClientName(WTS_CURRENT_SESSION, System.IntPtr.Zero);
-            LogDebugVerboseMessage("GetMyName()::Name={0}", name);
-            return name;
+            TerminalServer ts = new TerminalServer(new LocalServerHandle());
+            ts.Open();
+            var ClientName = ts.ServerName == null ? Environment.MachineName : ts.ServerName;
+            ts.Close();
+            return ClientName;
         }
 
     } // Class TSManager

 

  ViewVC Help
Powered by ViewVC 1.1.22