Example #1
0
        /// <summary>
        /// Open tcp/ip connection to meter
        /// </summary>
        /// <param name="tcpClient">host ip address</param>
        /// <param name="host">host ip address</param>
        /// <param name="port">host tcp port</param>
        /// <param name="unitId">unit/slave id</param>
        /// <param name="timeout">timeout in seconds</param>
        /// <returns></returns>
        public static bool TcpConnectWithTimeout(TcpClient tcpClient, string host, int port, int timeout = 20)
        {
            if (tcpClient != null)
            {
                return(false);
            }

            try
            {
                IAsyncResult ar = tcpClient.BeginConnect(host, port, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false))
                    {
                        tcpClient.Close();
                        return(false);
                    }

                    tcpClient.EndConnect(ar);
                }
                finally
                {
                    wh.Close();
                }

                return(true);
            }
            catch (Exception)
            {
                // general error
                return(false);
            }
        }
        private bool CheckConnection()
        {
            bool   success = false;
            string ip      = ConfigurationManager.AppSettings["bankServerIP"];
            int    port    = Convert.ToInt32(ConfigurationManager.AppSettings["bankServerPort"]);
            int    timeout = Convert.ToInt32(ConfigurationManager.AppSettings["connectionTimeout"]);

            try
            {
                using (System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient())
                {
                    IAsyncResult ar = tcp.BeginConnect(ip, port, null, null);
                    System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                    try
                    {
                        if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false))
                        {
                            tcp.Close();
                            throw new TimeoutException();
                        }
                        success = tcp.Connected;
                        tcp.EndConnect(ar);
                    }
                    finally
                    {
                        wh.Close();
                    }
                }
            }
            catch (Exception e) {
                log.Error(e);
            }

            return(success);
        }
Example #3
0
File: Tools.cs Project: cxdcxd/RRS
        public static bool CheckServiceAvailablity(string remote_ip, int remote_port)
        {
            bool result = true;

            using (TcpClient tcp = new TcpClient())
            {
                IAsyncResult ar = tcp.BeginConnect(remote_ip, remote_port, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false))
                    {
                        tcp.Close();
                        result = false;
                    }
                    else
                    {
                        tcp.EndConnect(ar);
                    }
                }
                catch
                {
                    result = false;
                }
                finally
                {
                    wh.Close();
                }
            }
            return(result);
        }
Example #4
0
        public void Connect()
        {
            try
            {
                Close();
            }
            catch (Exception)
            {
                // ignored
            }
            _client = new TcpClient {
                NoDelay = true
            };
            IAsyncResult ar = _client.BeginConnect(Host, Port, null, null);

            System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                {
                    _client.Close();
                    throw new IOException("Connection timoeut.", new TimeoutException());
                }

                _client.EndConnect(ar);
            }
            finally
            {
                wh.Close();
            }
            _stream              = _client.GetStream();
            _stream.ReadTimeout  = 10000;
            _stream.WriteTimeout = 10000;
        }
        public TcpClient Connect()
        {
            TcpClient tcp = new TcpClient();

            tcp.ReceiveTimeout = Convert.ToInt32(Timeout.TotalMilliseconds);
            tcp.SendTimeout    = Convert.ToInt32(Timeout.TotalMilliseconds);

            Stopwatch clock = Stopwatch.StartNew();

            IAsyncResult ar = tcp.BeginConnect(Ip, Port, null, null);

            System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(Timeout, false))
                {
                    tcp.Close();
                    throw new Exception("NOT_CONNECTED");
                }

                tcp.EndConnect(ar);
            }
            finally
            {
                wh.Close();
                ConnectionTime = Convert.ToInt32(clock.ElapsedMilliseconds);
                clock.Stop();
            }

            return(tcp);
        }
Example #6
0
        public bool TryConnectWith(IPAddress serverAddress, int serverPort)
        {
            _clientSocket = new TcpClient();
            IAsyncResult ar = _clientSocket.BeginConnect(serverAddress, serverPort, null, null);

            System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false))
                {
                    _clientSocket.Close();
                    return(false);
                }

                _clientSocket.EndConnect(ar);
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR CONNECTING " + e.Message);
                return(false);
            }
            finally
            {
                wh.Close();
            }
        }
Example #7
0
        private void connect()
        {
            int    port  = Convert.ToInt32(portTCP);
            string IPadr = adress;

            if (IPadr == "")
            {
                IPadr = GetIPs();
            }
            _tcpClient = new TcpClient();
            IAsyncResult ar = _tcpClient.BeginConnect(IPadr, port, null, null);

            System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3), false))
                {
                    _tcpClient.Close();
                    throw new TimeoutException();
                }
                _tcpClient.EndConnect(ar);
            }
            finally
            {
                wh.Close();
            }

            _tcpClient.NoDelay        = true;
            _tcpClient.ReceiveTimeout = 2000;
            _tcpClient.SendTimeout    = 2000;
        }
Example #8
0
        /// <summary>
        /// Connects to the server
        /// </summary>
        /// <returns>True if success; false otherwise</returns>
        public Result Connect()
        {
            try
            {
                client.ReceiveTimeout = GlobalSettings.Instance.PingTimeout;
                client.SendTimeout    = GlobalSettings.Instance.PingTimeout;

                IAsyncResult ar = client.BeginConnect(host, port, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(GlobalSettings.Instance.PingTimeout), false))
                    {
                        client.Close();
                        return(Result.Timeout);
                    }

                    client.EndConnect(ar);
                }
                finally
                {
                    wh.Close();
                }

                return(sendRequest("PING"));
            }
            catch
            {
                return(Result.Timeout);
            }
        }
Example #9
0
        public virtual void Connect(string hostname, int port, bool ssl, System.Net.Security.RemoteCertificateValidationCallback validateCertificate)
        {
            try {
                Host = hostname;
                Port = port;
                Ssl  = ssl;

                _Connection.SendTimeout    = this.Timeout;
                _Connection.ReceiveTimeout = this.Timeout;
                IAsyncResult ar = _Connection.BeginConnect(hostname, port, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(this.Timeout), true))
                    {
                        throw new TimeoutException(string.Format("Could not connect to {0} on port {1}.", hostname, port));
                    }
                    _Connection.EndConnect(ar);
                }
                finally
                {
                    wh.Close();
                }
                _Stream = _Connection.GetStream();
                if (ssl)
                {
                    System.Net.Security.SslStream sslStream;
                    if (validateCertificate != null)
                    {
                        sslStream = new System.Net.Security.SslStream(_Stream, false, validateCertificate);
                    }
                    else
                    {
                        sslStream = new System.Net.Security.SslStream(_Stream, false);
                    }
                    _Stream = sslStream;
                    sslStream.AuthenticateAsClient(hostname);
                }

                OnConnected(GetResponse());

                IsConnected = true;
                Host        = hostname;
            } catch (Exception) {
                IsConnected = false;
                Utilities.TryDispose(ref _Stream);
                throw;
            }
        }
Example #10
0
        public Int32 mbOpen(string IPadd, UInt16 port)
        {
            Int32 retCode = -1;

            try
            {
                if (isMbClietOpen == true)
                {
                    MessageBox.Show("mbClient is already Open");
                }
                else
                {
                    if (IPadd.Count() > 0 && port != 0)
                    {
                        IAsyncResult ar = clientConnection.BeginConnect(IPadd, port, null, null);
                        System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                        try
                        {
                            if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false))
                            {
                                clientConnection.Close();
                                throw new TimeoutException();
                            }

                            networkStream = clientConnection.GetStream();
                            isMbClietOpen = true;
                            retCode       = 0;
                        }
                        finally
                        {
                            wh.Close();
                        }
                    }
                } //else
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return(retCode);
        }
        private void Connect()
        {
            _tcpClient = new TcpClient();
            IAsyncResult asyncResult = _tcpClient.BeginConnect(RemoteAddress, RemotePort, null, null);

            System.Threading.WaitHandle waitHandle = asyncResult.AsyncWaitHandle;
            try
            {
                if (!asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(_timeout), false))
                {
                    _tcpClient.Close();
                    throw new TimeoutException(string.Format("Failed to connect to {0}:{1} within {2} seconds.", RemoteAddress, RemotePort, _timeout));
                }

                _tcpClient.EndConnect(asyncResult);
            }
            finally
            {
                waitHandle.Close();
            }
        }
Example #12
0
        private bool HostIsAvailableViaTcp(double timeout)
        {
            bool returnValue = false;

            using (System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient())
            {
                System.IAsyncResult         asyncResult = tcp.BeginConnect(SyslogServerHostname, SyslogServerPort, null, null);
                System.Threading.WaitHandle waitHandle  = asyncResult.AsyncWaitHandle;
                try
                {
                    if (!asyncResult.AsyncWaitHandle.WaitOne(System.TimeSpan.FromSeconds(timeout), false))
                    {
                        tcp.Close();
                        returnValue = false;
                        //throw new TimeoutException();
                    }

                    if (tcp.Client != null)
                    {
                        if (tcp.Client.Connected)
                        {
                            tcp.EndConnect(asyncResult);
                            returnValue = true;
                        }
                        else
                        {
                            returnValue = false;
                        }
                    }
                }
                finally
                {
                    waitHandle.Close();
                }
            }

            return(returnValue);
        }
Example #13
0
        public void Connect()
        {
            try
            {
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            this.client = new TcpClient {
                NoDelay = true
            };
            IAsyncResult ar = this.client.BeginConnect(this.Host, this.Port, null, null);

            System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                {
                    this.client.Close();
                    throw new IOException("Connection timeout.", new TimeoutException());
                }

                this.client.EndConnect(ar);
            }
            finally
            {
                wh.Close();
            }

            this.stream              = this.client.GetStream();
            this.stream.ReadTimeout  = 10000;
            this.stream.WriteTimeout = 10000;
        }
Example #14
0
            /// <summary>Attempts to connect to the server via TCP.</summary>
            public void Connect()
            {
                socket = new TcpClient {
                    ReceiveBufferSize = dataBufferSize,
                    SendBufferSize    = dataBufferSize
                };

                receiveBuffer = new byte[dataBufferSize];

                var ar = socket.BeginConnect(instance.ip, instance.port, ConnectCallback, socket);

                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false))
                    {
                        socket.Close();                                        //We have timed out!
                        UnityEngine.SceneManagement.SceneManager.LoadScene(0); //this line is here so that we go back to the menu
                        return;
                    }
                }
                finally {
                    wh.Close();
                }
            }
Example #15
0
        public ServerPingData PingServer(string host, int port, out string error)
        {
            ServerPingData pingData = new ServerPingData();

            error = string.Empty;
            //Attempt to contact the server
            try
            {
                using (TcpClient client = new TcpClient())
                {
                    IAsyncResult ar = client.BeginConnect(host, port, null, null);
                    System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                    try
                    {
                        if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(Common.GlobalSettings.ConnectTimeout), false))
                        {
                            client.Close();
                            error          = "Offline (Connection Timeout)";
                            pingData.Error = true;
                            return(pingData);
                        }

                        client.EndConnect(ar);
                    }
                    finally
                    {
                        wh.Close();
                    }
                    //Send a single message notifying the server we would like it's stats (0 is the ping request ID)
                    data = new byte[1] {
                        0x00
                    };

                    //Get a client stream for reading and writing
                    stream = client.GetStream();

                    //Send the message to the connected TcpServer.
                    stream.Write(data, 0, data.Length);

                    int size = (stream.ReadByte() << 8) + stream.ReadByte();
                    Debug.WriteLine("ServerPinger Sent: " + data.ToString());

                    //Buffer to store the response bytes.
                    data = new byte[size];

                    //Read the first batch of the TcpServer response bytes
                    int bytes = stream.Read(data, 0, data.Length);

                    using (MemoryStream ms = new MemoryStream(data))
                    {
                        using (StreamReader reader = new StreamReader(ms))
                        {
                            pingData.Online      = (int)byte.Parse(reader.ReadLine());
                            pingData.MaxOnline   = (int)byte.Parse(reader.ReadLine());
                            pingData.Description = reader.ReadLine();
                        }
                    }
                    client.Close();
                }
            }
            catch (Exception e)
            {
                error          = e.Message;
                pingData.Error = true;
                Debug.WriteLine(e.ToString());
                if (e is SocketException)
                {
                    //Provide some better error messages
                    int id = (e as SocketException).ErrorCode;
                    if (id == 10061) //No connection could be made because the target machine actively refused it
                    {
                        error = "Offline (Target Online, Server Not Accessible)";
                    }
                    else if (id == 10060) //A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
                    {
                        error = "Offline (Connection Timeout)";
                    }
                }
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
            }
            return(pingData);
        }
Example #16
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        internal static void Main()
        {
            /*
             *
             * System.Security.Principal.WindowsIdentity currentIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(TokenAccessLevels.Read);
             * //Console.WriteLine(currentIdentity.User.Value);
             * System.Security.Principal.SecurityIdentifier userSid = new SecurityIdentifier("S-1-5-21-149779583-363096731-646672791-379352");
             * Console.WriteLine((userSid == currentIdentity.User));
             *
             * System.Collections.Specialized.StringCollection existingRights = GetRights(currentIdentity);
             * Console.WriteLine("Rights for {0}", currentIdentity.Name);
             * Console.WriteLine(new string('=', 30));
             * foreach (string rightName in existingRights)
             * {
             *  Console.WriteLine(rightName);
             * }
             *
             * SetRight(currentIdentity, "SeDebugPrivilege");
             * SetRight(currentIdentity, "SeBackupPrivilege");
             *
             * System.Collections.Specialized.StringCollection newRights = GetRights(currentIdentity);
             * Console.WriteLine();
             * Console.WriteLine("Rights for {0}", currentIdentity.Name);
             * Console.WriteLine(new string('=', 30));
             * foreach (string rightName in newRights)
             * {
             *  Console.WriteLine(rightName);
             * }
             *
             * RemoveRight(currentIdentity, "SeBackupPrivilege");
             *
             * newRights = GetRights(currentIdentity);
             * Console.WriteLine();
             * Console.WriteLine("Rights for {0}", currentIdentity.Name);
             * Console.WriteLine(new string('=', 30));
             * foreach (string rightName in newRights)
             * {
             *  Console.WriteLine(rightName);
             * }
             */


            string SyslogServerHostname = "patrick-syslog";
            //int SyslogServerPort = 514;
            int SyslogServerPort = 1468;

            Console.WriteLine(DateTime.Now);

            /*
             * System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient();
             * tcpClient.SendTimeout = 5;
             * try
             * {
             *  tcpClient.Connect(SyslogServerHostname, SyslogServerPort);
             * }
             * catch (Exception) { };
             */


            Console.WriteLine(DateTime.Now);

            /*
             * System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient();
             * udpClient.Connect(SyslogServerHostname, SyslogServerPort);
             *
             * byte[] testBytes = System.Text.UnicodeEncoding.Unicode.GetBytes("TEST");
             *
             * int returnValue = udpClient.Send(testBytes, testBytes.Length);
             */

            using (System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient())
            {
                IAsyncResult asyncResult = tcp.BeginConnect(SyslogServerHostname, SyslogServerPort, null, null);
                System.Threading.WaitHandle waitHandle = asyncResult.AsyncWaitHandle;
                try
                {
                    if (!asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false))
                    {
                        tcp.Close();
                        Console.WriteLine("Failed to connect.");
                        //throw new TimeoutException();
                    }

                    if (tcp.Client != null)
                    {
                        if (tcp.Client.Connected)
                        {
                            tcp.EndConnect(asyncResult);
                        }
                        else
                        {
                            Console.WriteLine("TCP client is not connected.");
                        }
                    }
                }
                finally
                {
                    waitHandle.Close();
                }
            }

            int q = 0;

            /*
             * for (int x = 0; x < 2; x++)
             * {
             *  syslog.WriteInformationEvent(string.Format("This is informational event {0:N0}.", x), System.Diagnostics.Process.GetCurrentProcess().Id, string.Empty);
             * }
             */

            /*
             * Console.WriteLine(new string('=', 30));
             * Console.WriteLine(new string('=', 30));
             * Console.WriteLine(LocalAdministratorGroup.LocalAdminGroupName);
             * Console.WriteLine(new string('=', 30));
             * Console.WriteLine(new string('=', 30));
             *
             * Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.Name);
             * Console.WriteLine(System.Globalization.CultureInfo.CurrentUICulture.Name);
             *
             * Console.WriteLine(new string('=', 30));
             *
             * Console.WriteLine(System.Threading.Thread.CurrentThread.CurrentCulture.Name);
             * Console.WriteLine(System.Threading.Thread.CurrentThread.CurrentUICulture.Name);
             *
             * System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;
             *
             * Console.WriteLine(new string('=', 30));
             *
             * Console.WriteLine(System.Threading.Thread.CurrentThread.CurrentCulture.Name);
             * Console.WriteLine(System.Threading.Thread.CurrentThread.CurrentUICulture.Name);
             */

            /*
             * }
             *
             * FreeSid(sid);
             */


            /*
             * //Now that we have the SID an the policy,
             * //we can add rights to the account.
             *
             * //initialize an unicode-string for the privilege name
             * LSA_UNICODE_STRING[] userRights = new LSA_UNICODE_STRING[1];
             * userRights[0] = new LSA_UNICODE_STRING();
             * userRights[0].Buffer = Marshal.StringToHGlobalUni(privilegeName);
             * userRights[0].Length = (UInt16)(privilegeName.Length * UnicodeEncoding.CharSize);
             * userRights[0].MaximumLength = (UInt16)((privilegeName.Length + 1) * UnicodeEncoding.CharSize);
             *
             * //add the right to the account
             * long res = LsaAddAccountRights(policyHandle, sid, userRights, 1);
             * winErrorCode = LsaNtStatusToWinError(res);
             * if (winErrorCode != 0)
             * {
             *  Console.WriteLine("LsaAddAccountRights failed: " + winErrorCode);
             * }
             */



            /*
             *
             * int WinWorldSid = 1;
             * int POLICY_ALL_ACCESS = 0xF0FFF;
             * int SECURITY_MAX_SID_SIZE = 68;
             * string SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME = "SeDenyRemoteInteractiveLogonRight";
             * uint NT_STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034;
             * uint STATUS_NO_MORE_ENTRIES = 0x8000001A;
             *
             * // add the Deny permission
             * Public Sub DenyTS(ByVal PC As String)
             * Dim ret, Access, sidsize As Integer
             * Dim SystemName, DenyTSRights As LSA_UNICODE_STRING
             * Dim objectAttributes As LSA_OBJECT_ATTRIBUTES
             * Dim policyHandle, EveryoneSID As IntPtr
             *
             * // build a well-known SID for "Everyone"
             * sidsize = SECURITY_MAX_SID_SIZE
             * EveryoneSID = Marshal.AllocHGlobal(sidsize)
             * If CreateWellKnownSid(WinWorldSid, IntPtr.Zero, EveryoneSID, sidsize) = False Then
             * ret = Marshal.GetLastWin32Error()
             * Throw New Win32Exception(ret)
             * End If
             *
             * // setup the parameters for the LsaOpenPolicy API
             * objectAttributes.Length = Marshal.SizeOf(objectAttributes)
             * SystemName.Length = PC.Length * UnicodeEncoding.CharSize
             * SystemName.MaximumLength = (PC.Length + 1) * UnicodeEncoding.CharSize
             * SystemName.Buffer = Marshal.StringToHGlobalUni(PC)
             * Access = POLICY_ALL_ACCESS
             *
             * // open a policy handle on the remote PC
             * ret = LsaOpenPolicy(SystemName, objectAttributes, Access, policyHandle)
             * If ret<> 0 Then
             * Throw New Win32Exception(LsaNtStatusToWinError(ret))
             * End If
             *
             * // clean up
             * Marshal.FreeHGlobal(SystemName.Buffer)
             *
             * // Setup the input parameters for the LsaRemoveAccountRights API
             * DenyTSRights.Length = SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME.Length * UnicodeEncoding.CharSize
             * DenyTSRights.MaximumLength = (SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME.Length + 1) * UnicodeEncoding.CharSize
             * DenyTSRights.Buffer = Marshal.StringToHGlobalUni(SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME)
             *
             * // Do it!
             * ret = LsaAddAccountRights(policyHandle, EveryoneSID, DenyTSRights, 1)
             * If ret<> 0 Then
             * Marshal.FreeHGlobal(DenyTSRights.Buffer)
             * LsaClose(policyHandle)
             * Throw New Win32Exception(LsaNtStatusToWinError(ret))
             * End If
             *
             * // clean up
             * Marshal.FreeHGlobal(DenyTSRights.Buffer)
             * LsaClose(policyHandle)
             * End Sub
             *
             */
            /*
             * for (int i = 0; i < 10; i++)
             * {
             */
            /*
             * Console.WriteLine(DateTime.Now.ToLongTimeString());
             * Console.WriteLine("Desktops Detected");
             * Console.WriteLine("=================");
             *
             * System.Text.StringBuilder desktopNameString = new System.Text.StringBuilder("Desktops: ");
             * string[] desktopNames = Desktop.GetDesktops();
             * for (int j = 0; j < desktopNames.Length; j++)
             * {
             *  desktopNameString.Append(desktopNames[j]);
             *  if (j < (desktopNames.Length - 1))
             *  {
             *      desktopNameString.Append(", ");
             *  }
             * }
             * Console.WriteLine(desktopNameString.ToString());
             */

            /*
             * foreach (string desktop in Desktop.GetDesktops())
             * {
             *  Console.WriteLine(desktop);
             * }
             */

            /*
             * Console.WriteLine();
             */

            /*
             * Console.WriteLine("Window Stations Detected");
             * Console.WriteLine("========================");
             * System.Text.StringBuilder winStaNameString = new System.Text.StringBuilder("Window Stations: ");
             * string[] winStaNames = Desktop.GetWindowStations();
             * for (int j = 0; j < winStaNames.Length; j++)
             * {
             *  winStaNameString.Append(winStaNames[j]);
             *  if (j < (winStaNames.Length - 1))
             *  {
             *      winStaNameString.Append(", ");
             *  }
             * }
             * Console.WriteLine(winStaNameString.ToString());
             */

            /*
             * foreach (string winsta in Desktop.GetWindowStations())
             * {
             *  Console.WriteLine(winsta);
             * }
             */

            /*
             * long DESKTOP_ENUMERATE = 0x0040L;
             * long DESKTOP_READOBJECTS = 0x0001L;
             * long DESKTOP_WRITEOBJECTS = 0x0080L;
             * long READ_CONTROL = 0x00020000L;
             *
             * long MAXIMUM_ALLOWED = 0x02000000L;
             */

            /*
             * //Console.WriteLine(LsaLogonSessions.LogonSessions.WTSGetActiveConsoleSessionId());
             * //Console.WriteLine(LsaLogonSessions.LogonSessions.GetDesktopWindow());
             * IntPtr inputDesktopPtr = LsaLogonSessions.LogonSessions.OpenInputDesktop(0, false, 256);
             *
             * if (inputDesktopPtr == IntPtr.Zero)
             * {
             *  Console.ForegroundColor = ConsoleColor.Red;
             *  Console.WriteLine("input desktop pointer was zero!");
             *  Console.ResetColor();
             *
             *  inputDesktopPtr = LsaLogonSessions.LogonSessions.OpenDesktop("Winlogon", 0, false, (uint)MAXIMUM_ALLOWED);
             *  if (inputDesktopPtr == IntPtr.Zero)
             *  {
             *      Console.ForegroundColor = ConsoleColor.Red;
             *      Console.WriteLine("input desktop pointer is still zero!");
             *      Console.ResetColor();
             *  }
             *  LsaLogonSessions.LogonSessions.SetThreadDesktop(inputDesktopPtr);
             *  int lastError = Marshal.GetLastWin32Error();
             *  Console.WriteLine("SetThreadDesktop Error: {0:N0}", lastError);
             *  LsaLogonSessions.LogonSessions.CloseDesktop(inputDesktopPtr);
             *  lastError = Marshal.GetLastWin32Error();
             *  Console.WriteLine("CloseDesktop Error: {0:N0}", lastError);
             */

            /*
             * inputDesktopPtr = LsaLogonSessions.LogonSessions.OpenDesktop("Default", 0, false, 256);
             * if (inputDesktopPtr == IntPtr.Zero)
             * {
             *  Console.ForegroundColor = ConsoleColor.Red;
             *  Console.WriteLine("input desktop pointer is still zero!");
             *  Console.ResetColor();
             * }
             * else
             * {
             *  Console.ForegroundColor = ConsoleColor.Green;
             *  Console.WriteLine("i was able to open the default desktop!");
             *  Console.ResetColor();
             *  bool switchResult = LsaLogonSessions.LogonSessions.SwitchDesktop(inputDesktopPtr);
             *  Console.WriteLine("able to switch desktops: {0}", switchResult);
             * }
             */
            /*
             * }
             *
             * //int lastError = Marshal.GetLastWin32Error();
             * Console.WriteLine(inputDesktopPtr);
             * //Console.WriteLine("Last Error: {0:N0}", lastError);
             * LsaLogonSessions.LogonSessions.CloseDesktop(inputDesktopPtr);
             */

            /*
             *  System.Threading.Thread.Sleep(2000);
             *  Console.WriteLine();
             * }
             */


            /*currentIdentity.Dispose();*/

#if DEBUG
            Console.Write("\n\nPress <ENTER> to close this program.");
            Console.ReadLine();
#endif
        }
Example #17
0
        bool ValidateUserID(string _UserID)
        {
            if (_UserID.Contains("Unknown.123456") || _UserID == "")
            {
                Utility.MessageBoxShow("You must fill in the correct UserID");
                return(false);
            }
            if (RealmPlayersUploader.IsValidUserID(c_txtUserID.Text) == false)
            {
                Utility.MessageBoxShow("UserID is not valid format, must be <name(a-z)>.<number> example of valid UserID: Unknown.123456");
                return(false);
            }
            if (char.IsUpper(c_txtUserID.Text[0]) == false ||
                c_txtUserID.Text.Last((char _Char) => char.IsUpper(_Char)) == c_txtUserID.Text[0])
            {
                Utility.MessageBoxShow("UserID have to start with capital letter and not contain any other capital letters in the UserName section!");
                return(false);
            }
            Socket tcpSocket = null;

            try
            {
                DateTime startConnectionTime = DateTime.Now;
                tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var          ipAddress = System.Net.Dns.GetHostEntry(ServerComm.g_Host).AddressList[0];
                IAsyncResult ar        = tcpSocket.BeginConnect(ipAddress, 18374, null, null);
                System.Threading.WaitHandle waitHandle = ar.AsyncWaitHandle;
                try
                {
                    for (int t = 0; t < 5; ++t)
                    {
                        if (waitHandle.WaitOne(TimeSpan.FromSeconds(1), false))
                        {
                            break;
                        }
                        Application.DoEvents();
                        //Console.Write(".");
                    }
                    Console.Write("\r\n");
                    if (!waitHandle.WaitOne(TimeSpan.FromSeconds(1), false))
                    {
                        tcpSocket.Close();
                        Utility.SoftThreadSleep(1000);
                        waitHandle.Close();
                        Utility.MessageBoxShow("Could not validate UserID because connection to server failed, try again later.");
                        return(false);
                    }

                    tcpSocket.EndConnect(ar);
                }
                finally
                {
                    waitHandle.Close();
                }
                tcpSocket.ReceiveTimeout = 5000;
                tcpSocket.SendTimeout    = 5000;
                byte[] bytes  = System.Text.Encoding.UTF8.GetBytes("NullNullNullNullNullNullNullNull");
                byte[] header = System.Text.Encoding.UTF8.GetBytes("Command=UserCheck;UserID=" + _UserID + ";FileSize=" + bytes.Length + "%");
                tcpSocket.Send(header);
                tcpSocket.Send(bytes);
                tcpSocket.Shutdown(SocketShutdown.Send);
                Byte[] readBuffer = new Byte[1024];
                int    i          = 0;
                string data       = "";
                while ((i = tcpSocket.Receive(readBuffer, readBuffer.Length, SocketFlags.None)) != 0)
                {
                    data += System.Text.Encoding.UTF8.GetString(readBuffer, 0, i);
                    if ((DateTime.Now - startConnectionTime).TotalSeconds > 10)
                    {
                        throw new Exception("Transfer took longer than 10 seconds, should not be allowed, canceling");
                    }
                }
                bool wasSuccess = false;
                if (data.Contains(";") && data.Contains("="))
                {
                    string[] dataSplit = data.Split(';');
                    foreach (string currDataSplit in dataSplit)
                    {
                        if (currDataSplit.Contains("="))
                        {
                            string[] currValue = currDataSplit.Split('=');
                            if (currValue[0] == "VF_RPP_Success")
                            {
                                wasSuccess = ConvertBool(currValue[1]);
                            }
                            else if (currValue[0] == "Message")
                            {
                                Utility.MessageBoxShow(currValue[1]);
                            }
                        }
                    }
                }
                if (wasSuccess == true)
                {
                    Utility.MessageBoxShow("The UserID \"" + _UserID + "\" was valid and is now in use! The program will now start upload your inspected database automatically everytime you close wow(if started using the WowLauncher).");
                    return(true);
                }
                else
                {
                    Utility.MessageBoxShow("The UserID \"" + _UserID + "\" is not valid. Please enter the correct UserID that was given to you.");
                }
            }
            catch (Exception ex)
            {
                Utility.MessageBoxShow("Could not validate UserID because of a connection error. Printscreen this message and PM to Dilatazu @ realmplayers forums or try again later.\r\nException:\r\n" + ex.ToString());
            }
            return(false);
        }
Example #18
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length == 2)
                {
                    int    port = 0;
                    string host = args[0];
                    try
                    {
                        port = Convert.ToInt32(args[1]);
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("Could not parse port number.");
                        Console.WriteLine("");
                        Environment.Exit(2);
                    }

                    System.Net.Sockets.TcpClient tcpclient = new System.Net.Sockets.TcpClient();
                    IAsyncResult connection = tcpclient.BeginConnect(host, port, null, null);
                    System.Threading.WaitHandle waithandle = connection.AsyncWaitHandle;
                    tcpclient.SendTimeout = 3000;

                    try
                    {
                        if (!connection.AsyncWaitHandle.WaitOne(tcpclient.SendTimeout, false))
                        {
                            tcpclient.Close();
                            throw new TimeoutException();
                        }

                        tcpclient.EndConnect(connection);
                        Console.WriteLine("");
                        Console.WriteLine("Successfully connected to server.");
                        Console.WriteLine("");
                        Environment.Exit(1);
                    }
                    catch (TimeoutException)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("The connection attempt timed out.");
                        Console.WriteLine("");
                        Environment.Exit(2);
                    }
                    catch (SocketException)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("Connection actively refused.");
                        Console.WriteLine("");
                    }
                    finally
                    {
                        waithandle.Close();
                    }
                }
                else
                {
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                Console.WriteLine("");
                Console.WriteLine("Invalid arguments");
                Console.WriteLine("");
                Environment.Exit(2);
            }
        }
Example #19
0
 internal static void Dispose(this System.Threading.WaitHandle waitHandle)
 {
     waitHandle.Close();
 }