public void RefreshConnection()
 {
     try
     {
         RefreshConnectionImpl();
     }
     catch (P4Exception ex)
     {
         throw ex;
     }
     finally
     {
         ConnectionChanged?.Invoke(this, EventArgs.Empty);
     }
 }
示例#2
0
 public void Disconnect(Action <string> ErrorHandler = null)
 {
     try
     {
         Port.Close();
     }
     catch (Exception error)
     {
         ErrorHandler?.Invoke(error.Message);
     }
     finally
     {
         ConnectionChanged?.Invoke(IsConnected);
     }
 }
示例#3
0
        private async void Connect()
        {
            try
            {
                if (messageWebSocket == null)
                {
                    messageWebSocket = new MessageWebSocket();
                    messageWebSocket.Control.MessageType = SocketMessageType.Utf8;
                    messageWebSocket.MessageReceived    += (sender, args) =>
                    {
                        using (DataReader reader = args.GetDataReader())
                        {
                            reader.UnicodeEncoding = UnicodeEncoding.Utf8;

                            try
                            {
                                string read     = reader.ReadString(reader.UnconsumedBufferLength);
                                var    response = PlayerResponse.ToObject(read);
                                StatusReceived?.Invoke(response);
                            }
                            catch (Exception ex)
                            {
                                LogReceived?.Invoke(ex.Message);
                            }
                        }
                    };
                    messageWebSocket.Closed += (sender, args) =>
                    {
                        _websocketConnected = false;
                        ConnectionChanged?.Invoke(_websocketConnected);
                    };
                }

                await messageWebSocket.ConnectAsync(new Uri(WebsocketUrl));

                messageWriter = new DataWriter(messageWebSocket.OutputStream);

                _websocketConnected = true;
                ConnectionChanged?.Invoke(_websocketConnected);
                AddRegister(_registered);
            }
            catch (Exception)
            {
                _websocketConnected = false;
                ConnectionChanged?.Invoke(_websocketConnected);
                await Task.CompletedTask;
            }
        }
示例#4
0
#pragma warning disable 1998
        public async Task DisconnectInternal(Exception ifErrorWhy)
        {
            if (disconnecting)
            {
                return;
            }
            if (connection != null && connection.State == HubConnectionState.Connected)
            {
                SendMessageToAll("I_AM_OUTTA_HERE", string.Empty, true).Wait(1000);

                disconnecting = true;
                disconnectingCancel.Cancel();
#if !UNITY_2018_3_OR_NEWER
                await connection.DisposeAsync();
#else
                var tt = connection.DisposeAsync();
#endif
            }
            if (!disconnecting)
            {
                disconnecting = true;
                disconnectingCancel.Cancel();
            }
            try
            {
                connection = null;

                if (httpClient != null)
                {
                    httpClient.Dispose();
                    httpClient = null;
                }

                ConnectionChanged?.Invoke(this, false, ifErrorWhy);
            }
            finally
            {
                peers.Clear();
                UserId       = string.Empty;
                ClientUrl    = string.Empty;
                ClientToken  = string.Empty;
                MessageToken = string.Empty;
                Me           = null;

                disconnectingCancel = new CancellationTokenSource();
                disconnecting       = false;
            }
        }
        public ConnectionInformation(int _ConnectionId, Socket DataStream, SocketManager _Manager, IDataParser _Parser, string _Ip)
        {
            Parser     = _Parser;
            Buffer     = new byte[SocketManagerStatics.BUFFER_SIZE];
            Manager    = _Manager;
            DataSocket = DataStream;
            DataSocket.SendBufferSize = SocketManagerStatics.BUFFER_SIZE;
            Ip           = _Ip;
            SendCallback = SentData;
            ConnectionId = _ConnectionId;

            if (ConnectionChanged != null)
            {
                ConnectionChanged.Invoke(this, ConnectionState.OPEN);
            }
        }
        public async Task Connect()
        {
            var ipAddress = "192.168.1.150";

            try
            {
                Console.WriteLine($"Creating client for [{ipAddress}]");
                _connectingTimer.Start();
                _client = await MqttClient.CreateAsync(ipAddress, _config);

                _client.Disconnected += HandleDisconnected;

                Console.WriteLine($"Connecting client to [{ipAddress}]");
                await _client.ConnectAsync(new MqttClientCredentials("yay"), null, true);

                _connectingTimer.Stop();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Connecting failed due to [{ex.Message}]");
                _connectingTimer.Stop();
                ConnectionChanged?.Invoke(this, new ConnectionStatusEventArgs(IsConnected));
            }

            if (_client.IsConnected)
            {
                await TryToSubscribe("/garage/status");
                await TryToSubscribe($"/garage/response/{_deviceId}");

                var statusObserver = Observer.Create <MqttApplicationMessage>((message) =>
                {
                    var payload = Encoding.ASCII.GetString(message.Payload);
                    var garages = JsonConvert.DeserializeObject <Garages>(payload);
                    Console.WriteLine($"Topic [{message.Topic}] Payload [{garages}]");
                    GaragesChanged?.Invoke(this, new GaragesChangedEventArgs(garages));
                }, (exception) =>
                {
                    Console.WriteLine($"Exception: {exception.Message}");
                });
                _client.MessageStream.SubscribeSafe(statusObserver);

                var requestMessage = new MqttApplicationMessage($"/garage/request/{_deviceId}", new byte[] { });
                Console.WriteLine($"Publishing message to [/garage/request/{_deviceId}]");
                await _client.PublishAsync(requestMessage, MqttQualityOfService.AtMostOnce);
            }
        }
        void HandleReachabilityChanged(NetworkReachabilityFlags flags)
        {
            Console.WriteLine($"Reachability Changed Event with {flags}");

            if (flags.HasFlag(NetworkReachabilityFlags.Reachable) && !IsConnected)
            {
                Task.Factory.StartNew(async() => await Connect());
            }
            else if (!flags.HasFlag(NetworkReachabilityFlags.Reachable) && IsConnected)
            {
                Disconnect();
            }
            else
            {
                ConnectionChanged?.Invoke(this, new ConnectionStatusEventArgs(IsConnected));
            }
        }
示例#8
0
        /// <summary>
        ///     Disconnects the current connection
        /// </summary>
        public void Disconnect()
        {
            try
            {
                if (_isConnected)
                {
                    _isConnected = false;

                    //Out.writeLine("Connection [" + this.connectionID + "] has been disconnected", Out.logFlags.BelowStandardlogLevel);
                    try
                    {
                        if (_dataSocket != null && _dataSocket.Connected)
                        {
                            _dataSocket.Shutdown(SocketShutdown.Both);
                            _dataSocket.Close();
                        }
                    }
                    catch
                    {
                        //ignored
                    }
                    _dataSocket.Dispose();
                    Parser.Dispose();

                    try
                    {
                        if (ConnectionChanged != null)
                        {
                            ConnectionChanged.Invoke(this, ConnectionState.Closed);
                        }
                    }
                    catch
                    {
                        //ignored
                    }
                    ConnectionChanged = null;
                }
                else
                {
                    //Out.writeLine("Connection [" + this.connectionID + "] has already been disconnected - ignoring Disconnect call", Out.logFlags.BelowStandardlogLevel);
                }
            }
            catch
            {
            }
        }
        private int BroadcastCallback(int message, IntPtr data)
        {
            if (message == 1)
            {
                if (data != IntPtr.Zero)
                {
                    Marshal.Copy(data, _colors, 0, RzChromaBroadcastNative.BroadcastColorCount);
                    ColorChanged?.Invoke(this, new RzBroadcastColorChangedEventArgs(_colors));
                }
            }
            else if (message == 2)
            {
                ConnectionChanged?.Invoke(this, new RzBroadcastConnectionChangedEventArgs(data.ToInt32() == 1));
            }

            return(0);
        }
示例#10
0
        public bool SendMessage(Message message, bool autoconnect = false)
        {
            try
            {
                if (!client.Connected && !autoconnect)
                {
                    return(false);
                }

                CheckConnection();

                lock (criticalSection)
                {
                    MemoryStream buffer = new MemoryStream();
                    message.Write(new BinaryWriter(buffer));
                    buffer.Flush();

                    UInt32 length = (UInt32)buffer.Length;

                    NetworkStream stream = client.GetStream();

                    BinaryWriter writer = new BinaryWriter(stream);
                    writer.Write(Message.MESSAGE_MARK);
                    writer.Write(length);

                    buffer.WriteTo(stream);
                    stream.Flush();
                }

                return(true);
            }
            catch (Exception ex)
            {
                lock (criticalSection)
                {
                    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        ConnectionChanged?.Invoke(IpAddress, Port, State.Disconnected, ex.Message);
                    }));

                    Reconnect();
                }
            }

            return(false);
        }
示例#11
0
 private async void NotifyConnectionChanged(bool connected)
 {
     logger.WriteLine($"connected: {connected}");
     if (ConnectionChanged != null)
     {
         var data = new ConnectionChangedEvent
         {
             Connected = connected,
             AdapterId = "adapterId",
             WiFiName  = "wiFiName"
         };
         await dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                   new DispatchedHandler(() =>
         {
             ConnectionChanged?.Invoke(this, data);
         }));
     }
 }
示例#12
0
        public static async Task <bool> Elevate(this NamedPipeAsAppServiceConnection connection)
        {
            if (connection == null)
            {
                App.MainViewModel.IsFullTrustElevated = false;
                return(false);
            }

            bool wasElevated = false;

            var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
            {
                { "Arguments", "Elevate" }
            });

            if (status == AppServiceResponseStatus.Success)
            {
                var res = response.Get("Success", 1L);
                switch (res)
                {
                case 0:     // FTP is restarting as admin
                    var nullConn = Task.FromResult <NamedPipeAsAppServiceConnection>(null);
                    ConnectionChanged?.Invoke(null, nullConn);
                    (await Instance)?.Dispose();
                    Instance = BuildConnection(false);     // Fulltrust process is already running
                    _        = await Instance;
                    ConnectionChanged?.Invoke(null, Instance);
                    wasElevated = true;
                    break;

                case -1:     // FTP is already admin
                    wasElevated = true;
                    break;

                default:     // Failed (e.g canceled UAC)
                    wasElevated = false;
                    break;
                }
            }

            App.MainViewModel.IsFullTrustElevated = wasElevated;

            return(wasElevated);
        }
示例#13
0
        public ADOTabularConnection(string connectionString, AdomdType connectionType, bool showHiddenObjects, ADOTabularMetadataDiscovery vistorType)
        {
            ShowHiddenObjects = showHiddenObjects;
            ConnectionString  = connectionString;
            _adomdConn        = new AdomdConnection(ConnectionString, connectionType);
            _connectionType   = connectionType;
            //   _adomdConn.ConnectionString = connectionString;

            //_adomdConn.Open();
            if (vistorType == ADOTabularMetadataDiscovery.Adomd)
            {
                Visitor = new MetaDataVisitorADOMD(this);
            }
            else
            {
                Visitor = new MetaDataVisitorCSDL(this);
            }
            ConnectionChanged?.Invoke(this, new EventArgs());
        }
示例#14
0
        private void Disconnect()
        {
            try
            {
                if (!_isConnected)
                {
                    return;
                }

                _isConnected = false;

                try
                {
                    if (_dataSocket != null && _dataSocket.Connected)
                    {
                        _dataSocket.Shutdown(SocketShutdown.Both);
                        _dataSocket.Close();
                    }
                }
                catch
                {
                    // ignored
                }

                _dataSocket?.Dispose();

                Parser.Dispose();
                try
                {
                    ConnectionChanged?.Invoke(this, ConnectionState.Closed);
                }
                catch
                {
                    // ignored
                }

                ConnectionChanged = null;
            }
            catch
            {
                // ignored
            }
        }
示例#15
0
        private void OnConnectionTimerEvent(Object source, ElapsedEventArgs e)
        {
            try
            {
                FSUIPCConnection.Open();
            }
            catch
            {
                Logger.Instance.LogMessage(TracingLevel.INFO, "connection failed");
            }

            if (FSUIPCConnection.IsOpen)
            {
                _connectionTimer.Enabled = false;
                Logger.Instance.LogMessage(TracingLevel.INFO, "connected");
                ConnectionChanged?.Invoke(this, true);
                SetupMainTimer();
            }
        }
示例#16
0
        public void Connect(string login = null, string pwd = null)
        {
            if (!string.IsNullOrEmpty(login))
            {
                _login = login;
            }
            if (!string.IsNullOrEmpty(pwd))
            {
                _password = pwd;
            }

            if (!string.IsNullOrEmpty(_login) && !string.IsNullOrEmpty(_password))
            {
                _client       = BitbucketClient.WithBasicAuthentication(_login, _password);
                _clientCommit = new ClientCommit(_client);
                _clientRepo   = new RepoClient(_client);
            }
            ConnectionChanged?.Invoke(null);
        }
示例#17
0
        /// <summary>
        /// Send a the command to the VLC media player.
        /// </summary>
        /// <param name="query">The query to send. If a null query is provided, just an updated status
        /// will be requested.</param>
        private async Task SendCommand(string query = null)
        {
            HttpResponseMessage response = null;

            try
            {
                response = await client.GetAsync("requests/status.xml" + (query == null ? "" : "?" + query));
            }
            catch (HttpRequestException)
            {
                IsConnected = false;
                ConnectionChanged?.Invoke(this, new EventArgs());
                return;
            }

            IsConnected = true;

            if (response.IsSuccessStatusCode)
            {
                var stream = await response.Content.ReadAsStreamAsync();

                try
                {
                    Status = (VlcStatus)statusSerializer.Deserialize(stream);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                StatusUpdated?.Invoke(this, new EventArgs());
            }
            else if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                IsConnected = false;
                ConnectionChanged?.Invoke(this, new EventArgs());
            }
            else
            {
                Console.WriteLine("error: " + response.StatusCode);
            }
        }
示例#18
0
        public void Disconnect()
        {
            try
            {
                if (IsConnected)
                {
                    IsConnected = false;

                    try
                    {
                        if (DataSocket != null && DataSocket.Connected)
                        {
                            DataSocket.Shutdown(SocketShutdown.Both);
                            DataSocket.Close();
                        }
                    }
                    catch
                    {
                    }

                    DataSocket.Dispose();
                    Parser.Dispose();

                    try
                    {
                        if (ConnectionChanged != null)
                        {
                            ConnectionChanged.Invoke(this, ConnectionState.CLOSED);
                        }
                    }
                    catch
                    {
                    }

                    ConnectionChanged = null;
                }
            }
            catch
            {
            }
        }
示例#19
0
        public Task <bool> ConnectNetworkAsync(ProfileItem profileItem, TimeSpan timeout)
        {
            var targetProfiles = _sourceProfiles
                                 .Where(x => x.InterfaceId == profileItem.InterfaceId)
                                 .ToList();

            var targetProfile = targetProfiles.FirstOrDefault(x => x.Id == profileItem.Id);

            if (targetProfile == null)
            {
                return(Task.FromResult(false));
            }

            targetProfile.IsConnected = true;
            targetProfiles.Remove(targetProfile);

            targetProfiles.ForEach(x => x.IsConnected = false);

            deferTask = DeferAsync(() => ConnectionChanged?.Invoke(this, EventArgs.Empty));
            return(Task.FromResult(true));
        }
示例#20
0
 public void Connect(string portName, int baudRate, Action <string> ErrorHandler = null)
 {
     Port.PortName = portName;
     Port.BaudRate = baudRate;
     try
     {
         Port.Open();
     }
     catch (UnauthorizedAccessException error)
     {
         ErrorHandler?.Invoke("Выбранный порт занят другим приложением");
     }
     catch (Exception error)
     {
         ErrorHandler?.Invoke(error.Message);
     }
     finally
     {
         ConnectionChanged?.Invoke(IsConnected);
     }
 }
        private void ConnectionStable()
        {
            if (!_oldConnected)
            {
                ConnectionChanged?.Invoke(_connectionContext, true);
                _oldConnected = true;
            }

            if (_forceInitialEvents)
            {
                Trace.TraceWarning($"{_traceId}: Force initial events");
                _forceInitialEvents = false;
                for (var ix = 0; ix < ProcessImage.Length; ix++)
                {
                    ProcessImage[ix] = (ushort)~ProcessImage[ix];
                }
            }

            _retryCount = 0;
            GoState(PollRegisters);
        }
示例#22
0
        /// <summary>
        /// Listens to the specified ip address for incoming UDP messages, and pushes those to a buffer
        /// Also Raises the SSHConsoleSyslog.SyslogListener.DataReceived Event
        /// </summary>
        /// <returns>Task completion information</returns>
        public Task Start()
        {
            byte[] bytes = new byte[256];
            CalledStop = false;
            try
            {
                BConsole.WriteLine($"Syslog Listener started...");
                while (!CalledStop)
                {
                    byte[]             bits     = Server.Receive(ref UdpEndpoint);
                    string             response = Encoding.ASCII.GetString(bits, 0, bits.Length);
                    DataReceivedObject receiv   = new DataReceivedObject
                    {
                        Data             = response.Replace("\n", ""),
                        IPAddress        = UdpEndpoint.Address.ToString(),
                        ReceivedDateTime = DateTime.Now
                    };

                    var validRule = SyslogFilters.CheckConnectionState(receiv.Data);

                    //this item is a connection log
                    if (validRule.Item1)
                    {
                        ConnectionChanged?.Invoke(validRule.Item2, receiv);
                    }

                    LastReceiveTime = DateTime.Now;
                }
            }
            catch (SocketException e)
            {
                BConsole.WriteLine($"Exception: {e.Message}");
            }
            catch (Exception e)
            {
                BConsole.WriteLine($"Exception: {e.Message}");
            }
            BConsole.WriteLine("Service stopped!");
            return(Task.CompletedTask);
        }
示例#23
0
        public void Initialize(bool tryReconnect)
        {
#if NETFX_CORE
            Connect();
#else
            if (_webSocket != null)
            {
                Console.Write("Initialized\n");
                return;
            }

            if (tryReconnect)
            {
                _timer          = new Timer(3 * 1000); // 3 sec
                _timer.Elapsed += TimerOnElapsed;
                _timer.Start();
            }

            _webSocket = new WebSocket(WebsocketUrl);

            _webSocket.OnMessage += MessageReceived;
            _webSocket.OnOpen    += OnConnected;
            _webSocket.OnError   += (sender, args) =>
            {
                Console.Write($"OnError {args.Message }\n");
            };

            _webSocket.OnClose += (sender, args) =>
            {
                Console.Write("Closed.\n");
                _websocketConnected = false;
                ConnectionChanged?.Invoke(_websocketConnected);
            };

            _webSocket.Connect();
#endif
            _enable = true;
        }
示例#24
0
        private void Open(string Hostname, int Port, Boolean CauseEvent)
        {
            SystemSocket = Connect(Hostname, Port);
            if (SystemSocket != null)
            {
                ConnectedHost = Hostname;
                ConnectedPort = Port;

                if (!connectDone.WaitOne(SocketTimeoutMS))
                {
                    SystemSocket = null;
                }

                RecvThread = new Thread(new ThreadStart(ReadLoop));

                if (CauseEvent)
                {
                    ConnectionChanged?.Invoke(this);
                }

                RecvThread.Start();
            }
        }
示例#25
0
        /*       public void Open(string connectionString)
         *     {
         *         _adomdConn.Open(connectionString);
         *         if (ConnectionChanged!=null)
         *             ConnectionChanged(this,new EventArgs());
         *     }
         */

        public void ChangeDatabase(string database)
        {
            _currentDatabase = database;
            if (_adomdConn.State != ConnectionState.Open)
            {
                _adomdConn.Open();
            }
            //if (PowerBIFileName != string.Empty)
            //{
            //    _currentDatabase = PowerBIFileName;
            //    ADOTabularDatabase db = Database;
            //    _adomdConn.ChangeDatabase(db.Id);
            //}
            //else
            //{
            _adomdConn.ChangeDatabase(database);
            //}
            ConnectionChanged?.Invoke(this, new EventArgs());

            _spid = 0; // reset the spid to 0 so that it will get re-evaluated
                       // the PowerBI xmla endpoint sets the permissions to call DISCOVER_SESSIONS on a per data set basis
                       // depending on whether the user has admin access to the given data set
        }
示例#26
0
        public unsafe GlfwInputContext(IView window) : base(window)
        {
            void OnConnectionChanged(IInputDevice a, bool b) => ConnectionChanged?.Invoke(a, b);

            if (window is not GlfwWindow)
            {
                throw new ArgumentNullException
                          (nameof(window), "Attempted to create input context for null or non-GLFW window.");
            }

            Handle = window.Handle;
            for (var i = 0; i < _gamepads.Length; i++)
            {
                _gamepads[i] = new GlfwGamepad(i)
                {
                    OnConnectionChanged = OnConnectionChanged
                };
            }

            for (var i = 0; i < _joysticks.Length; i++)
            {
                _joysticks[i] = new GlfwJoystick(i)
                {
                    OnConnectionChanged = OnConnectionChanged
                };
            }

            _subscribers[0] = _keyboards[0] = new GlfwKeyboard();
            _subscribers[1] = _mice[0] = new GlfwMouse();

            Gamepads  = new IsConnectedWrapper <GlfwGamepad>(_gamepads);
            Joysticks = new IsConnectedWrapper <GlfwJoystick>(_joysticks);
            Keyboards = _keyboards;
            Mice      = _mice;

            GlfwInputPlatform.RegisterWindow((WindowHandle *)Handle, _subscribers);
        }
示例#27
0
 private void connect_Button_Click(object sender, EventArgs e)
 {
     using (var cf = new ConnectForm())
     {
         if (connectionInfo != null)
         {
             cf.Server  = connectionInfo.DataSource;
             cf.SQLAuth = !connectionInfo.IntegratedSecurity;
             if (cf.SQLAuth)
             {
                 cf.UserName = connectionInfo.UserID;
                 cf.Password = connectionInfo.Password;
             }
         }
         if (cf.ShowDialog() == DialogResult.Cancel)
         {
             return;
         }
         connectionInfo = new SqlConnectionStringBuilder
         {
             DataSource         = cf.Server,
             IntegratedSecurity = !cf.SQLAuth
         };
         if (cf.SQLAuth)
         {
             connectionInfo.UserID   = cf.UserName;
             connectionInfo.Password = "******";
         }
         connectionString_Label.Text = connectionInfo.ConnectionString;
         if (cf.SQLAuth)
         {
             connectionInfo.Password = cf.Password;
         }
         ConnectionChanged?.Invoke(new ConnectionChangedEventArg(connectionInfo));
     }
 }
        public static async Task <bool> Elevate(this NamedPipeAsAppServiceConnection connection)
        {
            if (connection == null)
            {
                return(false);
            }

            var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
            {
                { "Arguments", "Elevate" }
            });

            if (status == AppServiceResponseStatus.Success)
            {
                var res = response.Get("Success", 1L);
                switch (res)
                {
                case 0:
                    var nullConn = Task.FromResult <NamedPipeAsAppServiceConnection>(null);
                    ConnectionChanged?.Invoke(null, nullConn);
                    (await Instance)?.Dispose();
                    Instance = BuildConnection(false);     // Fulltrust process is already running
                    _        = await Instance;
                    ConnectionChanged?.Invoke(null, Instance);
                    break;

                case -1:
                    return(true);

                default:
                    return(false);
                }
            }

            return(false);
        }
示例#29
0
 /// <summary>
 /// Raises the 'ConnectionChanged' event.
 /// </summary>
 private void OnConnectionChanged() => ConnectionChanged?.Invoke(this, EventArgs.Empty);
 private void RaiseConnectionChangedEvent()
 {
     ConnectionChanged?.Invoke(this, new ServiceHandlerConnectionChangedEventArgs(this, Status));
 }