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 #2
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);
        }
        public static void TryWaitOnHandleAndDispose(ref System.Threading.WaitHandle handle)
        {
            if (handle == null)
            {
                return;
            }

            try
            {
                handle.WaitOne();
            }
            catch (System.ObjectDisposedException)
            {
                return;
            }
            catch (System.Exception ex)
            {
                Media.Common.Extensions.Exception.ExceptionExtensions.TryRaiseTaggedException(handle, "An exception occured while waiting.", ex);
            }
            finally
            {
                if (handle != null)
                {
                    handle.Dispose();
                }
            }

            handle = null;
        }
Example #4
0
        public void CheckConnection(MainActivity main)
        {
            var address = IPAddress.Parse("192.168.192.46");

            using (TcpClient client = new TcpClient()) {
                IAsyncResult ar = client.BeginConnect(address, 444, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false))
                {
                    new AlertDialog.Builder(main)
                    .SetNeutralButton("Close", (sender, EventArgs) => {
                        main.btnClose.Clickable    = false;
                        main.btnDown.Clickable     = false;
                        main.btnShutdown.Clickable = false;
                        main.btnUp.Clickable       = false;
                        main.btnVDown.Clickable    = false;
                        main.btnVMute.Clickable    = false;
                        main.btnVUp.Clickable      = false;
                    })
                    .SetMessage("No Connection")
                    .Show();
                }
                else
                {
                    main.btnClose.Clickable    = true;
                    main.btnDown.Clickable     = true;
                    main.btnShutdown.Clickable = true;
                    main.btnUp.Clickable       = true;
                    main.btnVDown.Clickable    = true;
                    main.btnVMute.Clickable    = true;
                    main.btnVUp.Clickable      = true;
                }
            }
        }
Example #5
0
        //public static Task WaitOneAsync(this System.Threading.WaitHandle waitHandle, TimeSpan timeout)
        //{
        //    if (waitHandle == null) throw new ArgumentNullException("waitHandle");
        //    var Milliseconds = timeout.TotalMilliseconds;
        //    if (Milliseconds < 1) Milliseconds = -1;
        //    var tcs = new TaskCompletionSource<bool>();
        //    var rwh = System.Threading.ThreadPool.RegisterWaitForSingleObject(waitHandle, delegate { tcs.TrySetResult(true); }, null, (uint)Milliseconds, true);
        //    var t = tcs.Task;
        //    t.ContinueWith((antecedent) => rwh.Unregister(null));
        //    return t;
        //}
        public static async Task <bool> WaitOneAsync(this System.Threading.WaitHandle handle, int millisecondsTimeout, System.Threading.CancellationToken cancellationToken)
        {
            System.Threading.RegisteredWaitHandle registeredHandle = null;
            var tokenRegistration = default(System.Threading.CancellationTokenRegistration);

            try
            {
                var tcs = new TaskCompletionSource <bool>();
                registeredHandle = System.Threading.ThreadPool.RegisterWaitForSingleObject(
                    handle,
                    (state, timedOut) => ((TaskCompletionSource <bool>)state).TrySetResult(!timedOut),
                    tcs,
                    millisecondsTimeout,
                    true);
                tokenRegistration = cancellationToken.Register(
                    state => ((TaskCompletionSource <bool>)state).TrySetCanceled(),
                    tcs);
                return(await tcs.Task);
            }
            finally
            {
                if (registeredHandle != null)
                {
                    registeredHandle.Unregister(null);
                }
                tokenRegistration.Dispose();
            }
        }
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
        internal bool Wait(System.Threading.WaitHandle handle, int timeout)
        {
            var handles = handle == null ?
                          new System.Threading.WaitHandle[] { _breakEvent } :
            new System.Threading.WaitHandle[] { _breakEvent, handle };
            var startWait = DateTime.Now;

            do
            {
                IsWait = true;
                int ret = System.Threading.WaitHandle.WaitAny(handles, timeout);
                IsWait = false;
                if (ret == System.Threading.WaitHandle.WaitTimeout)
                {
                    return(handle == null);
                }
                else if (ret == 1)
                {
                    return(true);
                }
                else if (ret == 0)
                {
                    if (State == ContextState.Pause)
                    {
                        _continueEvent.WaitOne();
                    }
                    if (State == ContextState.Stop)
                    {
                        return(false);
                    }
                    timeout -= (DateTime.Now - startWait).Milliseconds;
                }
            } while (timeout >= 0);
            return(false);
        }
        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 #9
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;
        }
Example #10
0
 public LhtAsResult(object state, MemBlock res)
 {
     _state = state;
     //We start off signalled, and stay there.
     _wh    = new System.Threading.ManualResetEvent(true);
     Result = res;
 }
Example #11
0
 public AsyncLockScreenResult(object asyncState, System.Threading.WaitHandle asyncWaitHandle, bool completedSynchronously, bool isCompleted)
 {
     AsyncState             = asyncState;
     AsyncWaitHandle        = asyncWaitHandle;
     CompletedSynchronously = completedSynchronously;
     IsCompleted            = isCompleted;
 }
        public static void TryWaitOnHandleAndDispose(ref System.Threading.WaitHandle handle)
        {
            if (object.ReferenceEquals(handle, NilWaitHandle))
            {
                return;
            }

            try
            {
                handle.WaitOne();
            }
            catch (System.ObjectDisposedException)
            {
                return;
            }
            catch (System.Exception ex)
            {
                //Should just return? (At least document that it will throw and how to catch or ignore)
                TaggedExceptionExtensions.TryRaiseTaggedException(handle, "An exception occured while waiting.", ex);
            }
            finally
            {
                if (object.ReferenceEquals(handle, NilWaitHandle).Equals(false))
                {
                    handle.Dispose();
                }
            }

            handle = null;
        }
Example #13
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 #14
0
        private void waitthread()
        {
            System.Threading.WaitHandle[] wh = new System.Threading.WaitHandle[inputdevices.Count + 1];
            for (int i = 0; i < inputdevices.Count; i++)
            {
                wh[i] = inputdevices[i].Eventhandle();
            }
            wh[inputdevices.Count] = stophandle;

            System.Diagnostics.Debug.WriteLine("IDL start");

            while (true)
            {
                int hhit = System.Threading.WaitHandle.WaitAny(wh);

                if (hhit == inputdevices.Count)  // stop!
                {
                    break;
                }

                List <InputDeviceEvent> list = inputdevices[hhit].GetEvents();

                if (list != null)
                {
                    //System.Diagnostics.Debug.WriteLine(Environment.TickCount + " Handle hit " + hhit + " " + inputdevices[hhit].ID().Name);

                    invokeAsyncOnUiThread(() => { OnNewEvent?.Invoke(list); }); // call in action context.
                }
            }
        }
Example #15
0
        public static System.Boolean WaitOneMSS(
            System.Threading.WaitHandle target)
        {
            object result;

            if (TestSpecificStubsUtil.RunTestSpecificStub(System.Reflection.MethodBase.GetCurrentMethod(), new object[] { target }, out result))
            {
                return((System.Boolean)result);
            }
            else
            {
                kk++;
                if (kk == 1)
                {
                    return(target.WaitOne());
                }
                else
                {
                    OPCDataLogger.OPCLoggerWriteQuene writeQueue = OPCDataLogger.DotTest.Factories.OPCLoggerWriteQueneFactory.CreateOPCLoggerWriteQuene01();
                    Accessor writeQAccessor = ReflectionAccessor.Wrap(writeQueue);
                    writeQAccessor.SetField("m_terminate", true);
                    kk = 0;
                    return(true);
                }
            }
        }
Example #16
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 #17
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);
            }
        }
Example #18
0
 internal static void AddThreadExitSignal(System.Threading.WaitHandle waitHandle)
 {
     lock (threadExitSignalListLock)
     {
         threadExitSignalList.Add(waitHandle);
     }
 }
 public static WaitHandle AddSafetyWH(WaitHandle handle)
 {
     if (true)
     {
         return(handle);
     }
     return(new SafeWaitHandle(handle));
 }
 /// <summary>
 /// Closes the form when required.
 /// </summary>
 /// <param name="asyncResult">The async result.</param>
 /// <remarks></remarks>
 private void CloseWhenRequired(IAsyncResult asyncResult)
 {
     System.Threading.WaitHandle[] closeSignals = new System.Threading.WaitHandle[] { asyncResult.AsyncWaitHandle, this.forceClose };
     System.Threading.WaitHandle.WaitAny(closeSignals);
     if (!this.IsDisposed)
     {
         this.Invoke(new Action(this.Close));
     }
     this.formClosed.Set();
 }
Example #21
0
        /// <summary>
        /// Will dispose the given upon disposition of this instance.
        /// </summary>
        /// <param name="waitHandle"></param>
        public DisposableWaitHandle(System.Threading.WaitHandle waitHandle)
        {
            if (waitHandle == null)
            {
                throw new System.ArgumentNullException("waitHandle");
            }

            //base.Handle = waitHandle.Handle;

            base.SafeWaitHandle = waitHandle.SafeWaitHandle;
        }
        public void wake_on_lan(string mac_addr, string ip, int port)
        {
            mac_addr = mac_addr.Replace("-", "");
            mac_addr = mac_addr.Replace(".", "");
            mac_addr = mac_addr.Replace(":", "");
            if (mac_addr.Length < 10)
            {
                System.Windows.Forms.MessageBox.Show("Error bad MAC address value", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return;
            }

            easy_socket.udp.Socket_Data s = new easy_socket.udp.Socket_Data(ip, port);
            s.event_Socket_Data_Error          += new easy_socket.udp.Socket_Data_Error_EventHandler(Socket_Data_Error_EventHandler);
            s.event_Socket_Data_Send_Completed += new easy_socket.udp.Socket_Data_Send_Completed_EventHandler(Socket_Data_Send_Completed_EventHandler);
            s.allow_broadcast = true;

/*
 * AMD Publication# 20213
 * If the IEEE address for a particular node on the network
 * was 11h 22h 33h 44h 55h 66h, then the LAN controller
 * would be scanning for the data sequence (assuming an
 * Ethernet Frame):
 * DESTINATION SOURCE MISC FF FF FF FF FF
 * FF 11 22 33 44 55 66 11 22 33 44 55 66 11 22 33 44
 * 55 66 11 22 33 44 55 66 11 22 33 44 55 66 11 22 33
 * 44 55 66 11 22 33 44 55 66 11 22 33 44 55 66 11 22
 * 33 44 55 66 11 22 33 44 55 66 11 22 33 44 55 66 11
 * 22 33 44 55 66 11 22 33 44 55 66 11 22 33 44 55 66
 * 11 22 33 44 55 66 11 22 33 44 55 66 MISC CRC
 */
            byte[] bytes = new byte[6 + 6 * 16];
            //first 6 bytes should be 0xff
            for (int cpt = 0; cpt < 6; cpt++)
            {
                bytes[cpt] = 0xff;
            }
            //now repeate MAC 16 times
            for (int cpt = 0; cpt < 16; cpt++)
            {
                for (int cpt2 = 0; cpt2 < 6; cpt2++)
                {
                    bytes[6 + cpt * 6 + cpt2] = byte.Parse(mac_addr.Substring(2 * cpt2, 2),//mac address is at least 10 length see if (mac_addr.Length<10)
                                                           System.Globalization.NumberStyles.HexNumber);
                }
            }
            s.send(bytes);
            // wait for multiple handles (error and send completed)
            System.Threading.WaitHandle[] waithandles = new System.Threading.WaitHandle[2];
            waithandles[0] = evt_success;
            waithandles[1] = evt_error;
            System.Threading.WaitHandle.WaitAny(waithandles, 10000, true);
        }
Example #23
0
        public static Task WaitOneAsync(this System.Threading.WaitHandle waitHandle)
        {
            if (waitHandle == null)
            {
                throw new ArgumentNullException("waitHandle");
            }
            var tcs = new TaskCompletionSource <bool>();
            var rwh = System.Threading.ThreadPool.RegisterWaitForSingleObject(waitHandle, delegate { tcs.TrySetResult(true); }, null, -1, true);
            var t   = tcs.Task;

            t.ContinueWith((antecedent) => rwh.Unregister(null));
            return(t);
        }
Example #24
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;
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="FacebookAsyncResult"/> class.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <param name="asyncState">State of the async.</param>
 /// <param name="asyncWaitHandle">The async wait handle.</param>
 /// <param name="completedSynchronously">if set to <c>true</c> [completed synchronously].</param>
 /// <param name="isCompleted">if set to <c>true</c> [is completed].</param>
 /// <param name="error">The error.</param>
 public FacebookAsyncResult(
     object result,
     object asyncState,
     System.Threading.WaitHandle asyncWaitHandle,
     bool completedSynchronously,
     bool isCompleted,
     FacebookApiException error)
 {
     this.result = result;
     this.asyncState = asyncState;
     this.asyncWaitHandle = asyncWaitHandle;
     this.completedSynchronously = completedSynchronously;
     this.isCompleted = isCompleted;
     this.error = error;
 }
Example #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FacebookAsyncResult"/> class.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <param name="asyncState">State of the async.</param>
 /// <param name="asyncWaitHandle">The async wait handle.</param>
 /// <param name="completedSynchronously">if set to <c>true</c> [completed synchronously].</param>
 /// <param name="isCompleted">if set to <c>true</c> [is completed].</param>
 /// <param name="error">The error.</param>
 public FacebookAsyncResult(
     object result,
     object asyncState,
     System.Threading.WaitHandle asyncWaitHandle,
     bool completedSynchronously,
     bool isCompleted,
     FacebookApiException error)
 {
     _result                 = result;
     _asyncState             = asyncState;
     _asyncWaitHandle        = asyncWaitHandle;
     _completedSynchronously = completedSynchronously;
     _isCompleted            = isCompleted;
     _error = error;
 }
Example #27
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 ThreadLoop()
        {
            System.IntPtr registryKey;
            int           result = RegOpenKeyEx(_registryHive, _registrySubName, 0, STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_NOTIFY,
                                                out registryKey);

            if (result != 0)
            {
                throw new System.ComponentModel.Win32Exception(result);
            }

            try
            {
                System.Threading.AutoResetEvent _eventNotify = new System.Threading.AutoResetEvent(false);
                System.Threading.WaitHandle[]   waitHandles  = new System.Threading.WaitHandle[]
                { _eventNotify, _eventTerminate };

                while (!_eventTerminate.WaitOne(0, true))
                {
                    result = RegNotifyChangeKeyValue(registryKey, true, _regFilter
                                                     , _eventNotify.Handle, true);

                    if (result != 0)
                    {
                        throw new System.ComponentModel.Win32Exception(result);
                    }

                    if (System.Threading.WaitHandle.WaitAny(waitHandles) == 0)
                    {
                        OnRegChanged();
                    }
                }
            }
            finally
            {
                if (registryKey != System.IntPtr.Zero)
                {
                    RegCloseKey(registryKey);
                }
            }
        }
        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 #30
0
        /// <summary>
        ///
        /// </summary>
        static void ControlationLogic()
        {
            System.TimeSpan HalfTimeout = System.TimeSpan.FromTicks(Timeout.Ticks >> 1);

            System.DateTime lastControlation;

Start:

            System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.BelowNormal;

            lastControlation = System.DateTime.UtcNow;

            CurrentResult = Media.Common.Extensions.Delegate.ActionExtensions.NoOp.BeginInvoke(Controlation, null);

            //use the handle on the already allocated result which was obtained by calling BeginAccept.
            using (System.Threading.WaitHandle handle = CurrentResult.AsyncWaitHandle)
            {
                System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;

                //Wait half the timeout using the event
                while (false.Equals(CurrentResult.IsCompleted) && false.Equals(handle.WaitOne(HalfTimeout)))
                {
                    //Check for stop or completion and wait the other half
                    if (CurrentResult.IsCompleted)
                    {
                        continue;
                    }
                    else if (System.DateTime.UtcNow - lastControlation >= Timeout)
                    {
                        break;
                    }
                }
            }

            CurrentResult = null;

            goto Start;
        }
Example #31
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 #32
0
        public bool LaunchInstaller(string uri, bool appIsAlreadyRunning, ref List<InternalNotification> queuedNotifications)
        {
            bool newDisplayLoaded = false;
            this.uri = uri;
            this.appIsAlreadyRunning = appIsAlreadyRunning;
            this.tempFolder = Path.Combine(Utility.UserSettingFolder, TEMP_FOLDER);

            try
            {
                this.wc = new Growl.CoreLibrary.WebClientEx();
                wc.Headers.Add("User-Agent", USER_AGENT);

                byte[] data = wc.DownloadData(this.uri);
                string definition = Encoding.UTF8.GetString(data).Trim();
                DisplayInfo info = DisplayInfo.Parse(definition);
                if (info != null)
                {
                    this.InfoLabel.Text = String.Format(Utility.GetResourceString(Properties.Resources.DisplayInstaller_Prompt), info.Name, info.Author, info.Description);
                    this.YesButton.Visible = true;
                    this.NoButton.Visible = true;
                    this.OKButton.Visible = false;

                    /* NOTE: there is a bug that is caused when Growl is launched via protocol handler (growl:) from Opera.
                     * when that happens, the call to ShowDialog hangs.
                     * i could not find any documentation on this or any reason why it would be happening (not on a non-ui thread, windows handle is already created, etc).
                     * the only fix i could find was to Show/Hide the form before calling ShowDialog. i dont even know why this works, but it does.
                     * */
                    this.Show();
                    this.Hide();

                    DialogResult result = this.ShowDialog();
                    if (result == DialogResult.Yes)
                    {
                        this.InfoLabel.Text = Utility.GetResourceString(Properties.Resources.DisplayInstaller_Installing);
                        this.progressBar1.Value = 0;
                        this.progressBar1.Visible = true;
                        this.YesButton.Enabled = false;
                        this.NoButton.Enabled = false;
                        this.Show();
                        this.Refresh();

                        if (Directory.Exists(this.tempFolder))
                            Directory.Delete(this.tempFolder, true);
                        Directory.CreateDirectory(this.tempFolder);
                        string zipFileName = Path.Combine(this.tempFolder, String.Format("{0}.zip", System.Guid.NewGuid().ToString()));
                        info.LocalZipFileLocation = zipFileName;

                        wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
                        wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);

                        StartDownload(info);

                        Utility.WriteDebugInfo(String.Format("Downloading display '{0}' to {1}", info.Name, info.LocalZipFileLocation));

                        System.Threading.WaitHandle[] handles = new System.Threading.WaitHandle[] { are, mre };
                        while (System.Threading.WaitHandle.WaitAny(handles) == 0)
                        {
                            lock (this.progress_lock)
                            {
                                this.progressBar1.Value = this.progress.ProgressPercentage;
                                Application.DoEvents();
                            }
                        }

                        this.progressBar1.Value = 100;
                        Application.DoEvents();

                        Utility.WriteDebugInfo(String.Format("Finished downloading display '{0}' to {1}", info.Name, info.LocalZipFileLocation));

                        if (this.errorMessage == null)
                        {
                            // unzip files to the correct location
                            string newDisplayFolder = Path.Combine(DisplayStyleManager.UserDisplayStyleDirectory, Growl.CoreLibrary.PathUtility.GetSafeFolderName(info.Name));
                            if (!ApplicationMain.HasProgramLaunchedYet || !Directory.Exists(newDisplayFolder))
                            {
                                Utility.WriteDebugInfo(String.Format("Display '{0}' downloaded - starting unzip.", info.Name));
                                Unzipper.UnZipFiles(info.LocalZipFileLocation, newDisplayFolder, false);

                                InternalNotification n = new InternalNotification(Properties.Resources.DisplayInstaller_NewDisplayInstalledTitle, String.Format(Utility.GetResourceString(Properties.Resources.DisplayInstaller_NewDisplayInstalledText), info.Name), info.Name);
                                queuedNotifications.Add(n);

                                newDisplayLoaded = true;

                                this.Close();
                            }
                            else
                            {
                                // display with the same name aleady exists...
                                ShowMessage(String.Format(Utility.GetResourceString(Properties.Resources.DisplayInstaller_AlreadyInstalled), info.Name));
                            }

                            // clean up
                            Utility.WriteDebugInfo(String.Format("Deleteing '{0}' zip file at {1}", info.Name, info.LocalZipFileLocation));
                            if (File.Exists(info.LocalZipFileLocation)) File.Delete(info.LocalZipFileLocation);
                        }
                        else
                        {
                            Utility.WriteDebugInfo(String.Format("Error downloading display '{0}'.", info.Name));
                            ShowMessage(errorMessage);
                        }
                    }
                }
                else
                {
                    // definition file was malformed
                    ShowMessage(String.Format(Utility.GetResourceString(Properties.Resources.DisplayInstaller_BadDefinitionFile), this.uri));
                }
            }
            catch (Exception ex)
            {
                // error downloading definition file
                Utility.WriteDebugInfo(String.Format("Error downloading display. {0} - {1}", ex.Message, ex.StackTrace));
                ShowMessage(String.Format(Utility.GetResourceString(Properties.Resources.DisplayInstaller_NonexistentDefinitionFile), this.uri));
            }
            return newDisplayLoaded;
        }
        public bool LaunchInstaller(string uri, bool appIsAlreadyRunning, ref List<InternalNotification> queuedNotifications, ref int cultureCodeHash)
        {
            bool languageInstalled = false;
            this.uri = uri;
            this.appIsAlreadyRunning = appIsAlreadyRunning;

            try
            {
                // handle special case where we are resetting the value
                if (uri == "reset")
                {
                    Properties.Settings.Default.CultureCode = "";
                    Properties.Settings.Default.Save();
                    cultureCodeHash = 0;
                    languageInstalled = true;
                    return languageInstalled;
                }

                this.wc = new Growl.CoreLibrary.WebClientEx();
                wc.Headers.Add("User-Agent", USER_AGENT);

                byte[] data = wc.DownloadData(this.uri);
                string definition = Encoding.UTF8.GetString(data).Trim();
                LanguageInfo info = LanguageInfo.Parse(definition);
                if (info != null)
                {
                    this.InfoLabel.Text = String.Format(Utility.GetResourceString(Properties.Resources.LanguageInstaller_Prompt), info.Name);
                    this.YesButton.Visible = true;
                    this.NoButton.Visible = true;
                    this.OKButton.Visible = false;

                    /* NOTE: there is a bug that is caused when Growl is launched via protocol handler (growl:) from Opera.
                     * when that happens, the call to ShowDialog hangs.
                     * i could not find any documentation on this or any reason why it would be happening (not on a non-ui thread, windows handle is already created, etc).
                     * the only fix i could find was to Show/Hide the form before calling ShowDialog. i dont even know why this works, but it does.
                     * */
                    this.Show();
                    this.Hide();

                    DialogResult result = this.ShowDialog();
                    if (result == DialogResult.Yes)
                    {
                        this.InfoLabel.Text = Utility.GetResourceString(Properties.Resources.LanguageInstaller_Installing);
                        this.progressBar1.Value = 0;
                        this.progressBar1.Visible = true;
                        this.YesButton.Enabled = false;
                        this.NoButton.Enabled = false;
                        this.Show();
                        this.Refresh();

                        if (Directory.Exists(this.tempFolder))
                            Directory.Delete(this.tempFolder, true);
                        Directory.CreateDirectory(this.tempFolder);
                        string guid = System.Guid.NewGuid().ToString();
                        string zipFileName = GetTempZipFileName(guid);
                        info.LocalZipFileLocation = zipFileName;

                        wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
                        wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);

                        StartDownload(info);

                        Utility.WriteDebugInfo(String.Format("Downloading language pack '{0}' to {1}", info.Name, info.LocalZipFileLocation));

                        System.Threading.WaitHandle[] handles = new System.Threading.WaitHandle[] { are, mre };
                        while (System.Threading.WaitHandle.WaitAny(handles) == 0)
                        {
                            lock (this.progress_lock)
                            {
                                this.progressBar1.Value = this.progress.ProgressPercentage;
                                Application.DoEvents();
                            }
                        }

                        this.progressBar1.Value = 100;
                        Application.DoEvents();

                        Utility.WriteDebugInfo(String.Format("Finished downloading language pack '{0}' to {1}", info.Name, info.LocalZipFileLocation));

                        if (this.errorMessage == null)
                        {
                            // unzip files to the correct location
                            string languageFolder = GetLanguageFolder(info.CultureCode);
                            if (!ApplicationMain.HasProgramLaunchedYet || !Directory.Exists(languageFolder))
                            {
                                Utility.WriteDebugInfo(String.Format("Language '{0}' downloaded - starting unzip.", info.Name));

                                // NOTE: installing a language pack requires elevated privileges (to write the resource assemblies to the bin folder).
                                // as such, we have to be elevated first
                                if (UserAccountControlHelper.IsElevated())
                                {
                                    cultureCodeHash = UnzipFilesToBin(info.Name, info.LocalZipFileLocation, info.CultureCode, ref queuedNotifications);
                                }
                                else
                                {
                                    string argument = String.Format("growl:languageelevatedinstall*{0}~{1}~{2}", info.CultureCode, info.Name, guid);
                                    UserAccountControlHelper.LaunchElevatedApplication(System.Windows.Forms.Application.ExecutablePath, argument, true);
                                }

                                this.Close();
                            }
                            else
                            {
                                // display with the same name aleady exists...
                                ShowMessage(String.Format(Utility.GetResourceString(Properties.Resources.LanguageInstaller_AlreadyInstalled), info.Name), true);
                            }
                        }
                        else
                        {
                            Utility.WriteDebugInfo(String.Format("Error downloading language pack '{0}'.", info.Name));
                            ShowMessage(errorMessage, true);
                        }
                    }
                }
                else
                {
                    // definition file was malformed
                    ShowMessage(String.Format(Utility.GetResourceString(Properties.Resources.LanguageInstaller_BadDefinitionFile), this.uri), true);
                }
            }
            catch (Exception ex)
            {
                // error downloading definition file
                Utility.WriteDebugInfo(String.Format("Error downloading language pack. {0} - {1}", ex.Message, ex.StackTrace));
                ShowMessage(String.Format(Utility.GetResourceString(Properties.Resources.LanguageInstaller_NonexistentDefinitionFile), this.uri), true);
            }
            return languageInstalled;
        }
Example #34
0
 public LhtAsResult(object state, MemBlock res) {
   _state = state; 
   //We start off signalled, and stay there.
   _wh = new System.Threading.ManualResetEvent(true);
   Result = res;
 }