private void OnLoaded() { if (!Connections.Any()) { Add(); } }
public Context() { _settings = ApplicationData.Current.RoamingSettings; try { if (_settings.Values.ContainsKey(nameof(Connections))) { string serialization = _settings.Values[nameof(Connections)] as string; var array = JsonConvert.DeserializeObject <KodiConnection[]>(serialization); Connections = new ObservableCollection <KodiConnection>(array); } } catch (Exception) { } if (Connections == null) { Connections = new ObservableCollection <KodiConnection>(); } #if DEBUG if (!Connections.Any()) { var cnx = new KodiConnection { IsDefault = true, Kodi = new KodiRemote.Core.Connection("123", "80", "kodi", "") }; Connections.Add(cnx); } #endif }
/// <summary> /// Refreshes the connections from the available device sources /// </summary> /// <returns>Collection of connection objects available to the app</returns> public async Task <Connections> RefreshConnections() { Connections connections = new Connections(); connections.Clear(); await BluetoothSerial.listAvailableDevicesAsync().AsTask().ContinueWith( listTask => { listTask.Result.ForEach( d => connections.Add(new Connection(d.Name, d, ConnectionType.BluetoothSerial))); }); await UsbSerial.listAvailableDevicesAsync().AsTask().ContinueWith( listTask => { listTask.Result.ForEach( d => connections.Add(new Connection(d.Name, d, ConnectionType.UsbSerial))); }); string previousConnection = App.CurrentAppSettings.PreviousConnectionName; if (this.CurrentConnection == null && !string.IsNullOrEmpty(previousConnection) && connections.Any(c => c.DisplayName == App.CurrentAppSettings.PreviousConnectionName)) { await this.Connect( connections.FirstOrDefault( c => c.DisplayName == App.CurrentAppSettings.PreviousConnectionName)); } return(connections); }
public void Update(TimeSpan delta) { if (LatencyMonitor.HasFlag(LatencyMonitorMethod.Ping) && !_awaitingPingResponse && !_awaitingEchoResponse && _now >= _pingSent + PingEveryMillis * TimeSpan.TicksPerMillisecond) { _awaitingPingResponse = true; _pingSent = _now; SendMessage(new[] { PingDenoter }, _server.Connections); } if (_awaitingEchoResponse && _now >= _toEchoSent + 5 * TimeSpan.TicksPerSecond || _awaitingPingResponse && _now >= _pingSent + 5 * TimeSpan.TicksPerSecond) { Latency = NO_RESPONSE; NoResponseCallback(); } for (var i = 0; i < _lastConnections.Count(); i++) { if (!Connections.Any((c) => c == _lastConnections[i])) { OnDisconnect(_lastConnections[i]); } } for (var i = 0; i < Connections.Count(); i++) { if (!_lastConnections.Any((c) => c == Connections[i])) { OnConnect(Connections[i]); } } }
private void ExecuteRemoveSelectedConnection() { if (SelectedConnection == null) { return; } var result = MessageBox.Show($"Delete connection '{SelectedConnection.Name}'?", "Confirm", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (result != MessageBoxResult.Yes) { return; } SettingsHelper.DeleteConnection(SelectedConnection.Id); Connections.Remove(SelectedConnection); if (Connections.Any()) { SelectedConnectionIndex = 0; } else { Configurations.Clear(); } }
/// <summary>Carrega as conexões com base nas configurações do servidor e do banco selecionado</summary> private void LoadConnectionStrins() { if (_connectionIsLoad) { return; } TryDeserializerConnectionString(); if (!string.IsNullOrWhiteSpace(_dataBaseNames) && !string.IsNullOrWhiteSpace(Server)) { foreach (var dbName in _dataBaseNames.Split(new[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries)) { if (string.IsNullOrWhiteSpace(Password) || string.IsNullOrWhiteSpace(UserId) || UseSspi) { Connections[dbName] = $"Integrated Security=SSPI;Persist Security Info=False;Data Source={Server};Application Name=SqlPackageUpdate"; } else { Connections[dbName] = $"Data Source={Server};User Id={UserId};Password={Password};Integrated Security=False;Application Name=SqlPackageUpdate"; } } } if (!Connections.Any()) { Console.Error.WriteLine("Your must be define the connection string, see example:"); Console.Error.WriteLine("1. --server=<ip or damain> --databasenames=<database name or multi db name separated by ;> --userId=<user with permission> --password=<user password>"); Console.Error.WriteLine("2. --ConnectionString='Data Source={Server};User Id={UserId};Password={Password}'"); } _connectionIsLoad = true; }
void PreValidateDefaultEntityConnections() { foreach (var entity in Entities.Where(entity => !entity.HasConnection())) { entity.Connection = Connections.Any(c => c.Name == "input") ? "input" : Connections.First().Name; } }
/// <summary> /// Checks wether the rules make sense. /// </summary> public bool Check() { if (Logic == null) { return(false); } //connections is not null if (Connections == null) { return(false); } //must contain 2 elements if (Connections.Count() < 2) { return(false); } //must contain altleast one in and one out if (Connections.Any(c => c.Type == ConnectionType.In) && Connections.Any(c => c.Type == ConnectionType.Out)) { return(true); } //or one in and one both if (Connections.Any(c => c.Type == ConnectionType.In) && Connections.Any(c => c.Type == ConnectionType.Both)) { return(true); } //or one out and one both if (Connections.Any(c => c.Type == ConnectionType.Out) && Connections.Any(c => c.Type == ConnectionType.Both)) { return(true); } //or two both return(Connections.Count(c => c.Type == ConnectionType.Both) > 1); }
void HandlePacket(Packet p) { p.Seek(+1); var sender = p.Sender; if (LogPackets && p.Header != HeaderTypes.POST_MESSAGE) { Program.Write("Received packet of type " + GetHeaderType(p.Header) + ", from " + sender.Username + "[" + sender.UserID + "]", "PacketLogs", ConsoleColor.Blue); } if (p.Header == HeaderTypes.POST_MESSAGE) // msg { sender.MessagesSent++; string message = p.ReadString(); foreach (var user in Connections.Values) { user.Send(CreatePacket(HeaderTypes.NOTIFY_POST, sender.UserID ^ 0x121, message)); } } else if (p.Header == HeaderTypes.SEND_WHISPER) // whisper { string targetName = p.ReadString(); Client target = Connections.Values.FirstOrDefault(c => c.Username == targetName); if (target != null) { string message = p.ReadString(); target.Send(CreatePacket(HeaderTypes.RECEIVE_WHISPER, sender.UserID, message)); // 37 = received whisper sender.Send(CreatePacket(HeaderTypes.SENT_WHISPER, target.UserID, message)); // 38 = sent whisper } else { sender.Send(CreatePacket(HeaderTypes.WHISPER_ERROR)); } } else if (p.Header == HeaderTypes.CHANGE_USERNAME_REQUEST) // change Username request { string newUsername = p.ReadString(); if (Connections.Any(pair => pair.Value.Username == newUsername)) // there is someone with this username { sender.Send(CreatePacket(HeaderTypes.CHANGE_USERNAME_DENIED)); } else { Program.Write(LogMessageType.UserEvent, "{0}[{1}] changed username to {2}", sender.Username, sender.UserID, newUsername); sender.Username = newUsername; foreach (var client in Connections.Values) { client.Send(CreatePacket(HeaderTypes.CHANGE_USERNAME_ANNOUNCE, sender.UserID, sender.Username)); } } } else if (p.Header == HeaderTypes.REPORT_USER) { HandleReportPacket(p, sender); } else if (p.Header == HeaderTypes.REQUEST_SEND_FILE) { } }
private bool HandleChatTypePacket(Packet p, Client sender) { if (p.Header == HeaderTypes.POST_MESSAGE) // msg { sender.MessagesSent++; string message = p.ReadString(); foreach (var user in Connections.Values) { user.Send(CreatePacket(HeaderTypes.NOTIFY_POST, sender.UserID ^ 0x121, message)); } } else if (p.Header == HeaderTypes.SEND_WHISPER) // whisper { string targetName = p.ReadString(); Client target = Connections.Values.FirstOrDefault(c => c.Username == targetName); if (target != null) { string message = p.ReadString(); target.Send(CreatePacket(HeaderTypes.RECEIVE_WHISPER, sender.UserID, message)); // 37 = received whisper sender.Send(CreatePacket(HeaderTypes.SENT_WHISPER, target.UserID, message)); // 38 = sent whisper } else { sender.Send(CreatePacket(HeaderTypes.WHISPER_ERROR)); } } else if (p.Header == HeaderTypes.CHANGE_USERNAME_REQUEST) // change Username request { string newUsername = p.ReadString(); if (Connections.Any(pair => pair.Value.Username == newUsername)) // there is someone with this username { sender.Send(CreatePacket(HeaderTypes.CHANGE_USERNAME_DENIED)); } else { Program.Write(LogMessageType.UserEvent, "{0}[{1}] changed username to {2}", sender.Username, sender.UserID, newUsername); sender.Username = newUsername; foreach (var client in Connections.Values) { client.Send(CreatePacket(HeaderTypes.CHANGE_USERNAME_ANNOUNCE, sender.UserID, sender.Username)); } } } else if (p.Header == HeaderTypes.REPORT_USER) { //HandleReportPacket(p, sender); } else if (p.Header == HeaderTypes.REQUEST_SEND_FILE) { } else { return(false); } return(true); }
public bool OutputIsConsole() { // check if this is a master job with actions, and no real entities if (Actions.Count > 0 && Entities.Count == 1 && Entities.First().GetAllFields().All(f => f.System)) { return(false); } return(Connections.Any(c => c.Name == Constants.OriginalOutput && c.Provider == "console" || c.Name == "output" && c.Provider == "console")); }
public static void AddConnection(ConnectionInformation connectionInformation) { if (Connections.Any(connection => connection.Name.Equals(connectionInformation.Name))) { throw new SybaseManagerException("Connection name already exists"); } Connections.Add(connectionInformation); }
public void SendQVM(IEnumerable <int> students, int moduleHistoryId) { foreach (int student in Connections.Any(students)) { foreach (string connection in Connections.GetConnections(student)) { Clients.Client(connection).ReciveModuleHistoryId(moduleHistoryId); } } }
public void StartListening() { var ipAddress = IPAddress.Parse("127.0.0.1"); var localEndPoint = new IPEndPoint(ipAddress, 8080); var listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { listener.Bind(localEndPoint); listener.Listen(10); while (true) { var handler = listener.Accept(); if (!Connections.Any(socket => socket.Equals(handler))) { var syncFilesAction = new SyncFilesAction(Directory); var teste = FileHelper.Serialize(syncFilesAction); handler.Send(FileHelper.Serialize(syncFilesAction)); Connections.Add(handler); new Thread(() => { var client = handler; while (true) { try { var bytes = new Byte[1024]; client.Receive(bytes); var action = (FileAction)FileHelper.Deserialize(bytes); ExecuteAction(action); SendActionToOthers(action, client); } catch (SocketException e) { client.Shutdown(SocketShutdown.Both); client.Close(); Connections.Remove(client); break; } } }).Start(); } } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
/// <summary> /// Called when an attached view's Loaded event fires. /// </summary> /// <param name="view"></param> protected override void OnViewLoaded(object view) { if (Connections.Any()) { return; } var connections = LoadConnectionsFromFile(); InsertConnections(connections, _selectConnectionItem); }
public void Update(Command command) { if (command.CommandDefinition is DeleteCommandDefinition) { command.Enabled = SelectedElements.Any() || Connections.Any(x => x.IsSelected); } else if (command.CommandDefinition is DrawConnectLineCommandDefinition) { command.Enabled = true; } }
/// <summary> /// Initializes the connections. /// </summary> public void InitializeConnections() { if (Connections.Any()) { return; } var connections = LoadConnectionsFromFile(); var connection = GetAutoConnection(connections); InsertConnections(connections, connection); }
/// <summary> /// Get connection /// </summary> /// <returns></returns> public static DbConnection Get() { if (!Connections.Any()) { throw new Exception("Connection not initiated"); } var connection = GetConnection(); if (connection.State == ConnectionState.Closed) { connection.Open(); } return(connection); }
public void BindConnectionWithUserId(string connectionId, Guid userId) { var alreadyAdded = Connections.Any(x => x.ConnectionId.Equals(connectionId) && UserId.Equals(userId)); if (alreadyAdded) { return; } Connections.Add(new SignalRConnection { ConnectionId = connectionId, UserId = userId }); }
private void refreshConnections(ISettingsManager <MySettings> settingsManager) { Connections = (settingsManager.LoadSettings() ?? new MySettings()).Connections; DataIsEnabled = Connections.Any(); if (DataIsEnabled) { SelectedConnection = Connections.First(); } else { MessengerInstance.Send(new MessageBoxMessage("No Databases Configured", "No database connections have been configured.\nPlease add some on the 'Config' tab.")); SelectedTabIndex = ConfigTabIndex; } }
internal void ConnectClosestNodes(List <Node> boundaries) { var connections = new List <Edge>(); foreach (var boundary in boundaries) { if (boundary.Id == this.Id) { continue; } double dist = Math.Sqrt(Math.Pow(Point.X - boundary.Point.X, 2) + Math.Pow(Point.Y - boundary.Point.Y, 2)); if (dist < 0.04) { connections.Add(new Edge { ConnectedNode = boundary, Length = dist, Cost = dist, }); } } connections = connections.OrderBy(x => x.Length).ToList(); var counter = 0; foreach (var cnn in connections) { if (!Connections.Any(c => c.ConnectedNode == cnn.ConnectedNode)) { Connections.Add(cnn); } counter++; if (!cnn.ConnectedNode.Connections.Any(cc => cc.ConnectedNode == this)) { var backConnection = new Edge { ConnectedNode = this, Length = cnn.Length }; cnn.ConnectedNode.Connections.Add(backConnection); } if (counter == 10) { return; } } }
protected override void OnNewControlEvent(ControlEventBase controlEvent) { var ev = controlEvent as ButtonEvent; var hardwareId = controlEvent.Hardware.GetHardwareGuid(); var button = (AssignmentForButton)Connections.FirstOrDefault(hw => hw.GetAssignedHardware() == hardwareId); var direction = button.GetInverseState() ? !ev.IsPressed : ev.IsPressed; if (_emulateToggle) { var action = button.Toggle(direction); if (action == ToggleState.MakeOn) { AccessDescriptor.SetState(button.GetConnector().Id); _lastStateId = button.GetConnector().Id; button.IsOn = true; } if (action == ToggleState.MakeOff) { button.IsOn = false; } } else { if (direction) { AccessDescriptor.SetState(button.GetConnector().Id); _lastStateId = button.GetConnector().Id; button.IsOn = true; } else { button.IsOn = false; _lastStateId = -1; } } // Для дампа кнопок с первого раза (без AllKeys, затем PressedKeysOnly) нужно игнорировать события отжатых кнопок, если одна из кнопок уже нажата if (Connections.Any(bi => ((AssignmentForButton)bi).IsOn)) { return; } _lastStateId = -1; AccessDescriptor.SetDefaultState(); }
public new GraphNodeVis <T> Add(params GraphNodeVis <T>[] nodes) { if (Connections == null) { Connections = new List <GraphNodeVis <T> >(); } foreach (var node in nodes) { if (Connections.Any(x => node.Data.Equals(x.Data))) { throw new Exception($"For node {Data} connection {node.Data} already exists"); } Connections.Add(node); } return(this); }
/*internal static Node GetRandom(Random rnd, string name) * { * return new Node * { * Point = new Point * { * X = rnd.NextDouble(), * Y = rnd.NextDouble() * }, * Id = Guid.NewGuid(), * Name = name * }; * }*/ internal void ConnectClosestNodes(List <Node> nodes, int branching, Random rnd, bool randomWeight) { var connections = new List <Edge>(); foreach (var node in nodes) { if (node.Id == this.Id) { continue; } var dist = Math.Sqrt(Math.Pow(Point.X - node.Point.X, 2) + Math.Pow(Point.Y - node.Point.Y, 2)); connections.Add(new Edge { ConnectedNode = node, Length = dist, Cost = randomWeight ? rnd.NextDouble() : dist, }); } connections = connections.OrderBy(x => x.Length).ToList(); var count = 0; foreach (var cnn in connections) { //Connect three closes nodes that are not connected. if (!Connections.Any(c => c.ConnectedNode == cnn.ConnectedNode)) { Connections.Add(cnn); } count++; //Make it a two way connection if not already connected if (!cnn.ConnectedNode.Connections.Any(cc => cc.ConnectedNode == this)) { var backConnection = new Edge { ConnectedNode = this, Length = cnn.Length }; cnn.ConnectedNode.Connections.Add(backConnection); } if (count == branching) { return; } } }
public void GetReadyConnections(Action <IEnumerable <IRCConnection> > callback) { if (callback == null) { throw new ArgumentNullException(nameof(callback)); } lock (Sync) { if (!Connections.Any()) { callback(Enumerable.Empty <IRCConnection>()); return; } List <Socket> sockets = new List <Socket>(Sockets.Values); Socket.Select(sockets, null, null, 5000000); callback(sockets.Select(s => Connections[s])); } }
public void sendToConnection(SItem newItem) { if (Connections == null || !Connections.Any()) { return; } var rand1 = rand.NextDouble(); var prob = Connections.OrderBy(x => x.Item2); foreach (Tuple <Activity, double> tup in prob) { if (rand1 <= tup.Item2) { tup.Item1.FilaEntrada.Add(newItem); return; } } }
public override async Task <WebSocketConnection> OnConnected(HttpContext context) { var channelId = context.Request.Query["channelId"]; var subscriberId = context.Request.Query["subscriberId"]; var key = context.Request.Query["key"]; if (string.IsNullOrEmpty(subscriberId) || string.IsNullOrEmpty(channelId)) { return(null); } var connection = Connections.FirstOrDefault(m => ((PiHubConnection)m).ChannelId == channelId && ((PiHubConnection)m).SubscriberId == subscriberId); if (connection != null) { try { await connection.WebSocket.CloseAsync(WebSocketCloseStatus.PolicyViolation, "The connection was reused from the other client", CancellationToken.None); } catch (Exception e) { } finally { Connections.Remove(connection); } } if (Connections.Any(c => ((PiHubConnection)c).Key != key && ((PiHubConnection)c).ChannelId == channelId)) { throw new NotAuthorizedException("provided key does not match the channel"); } var webSocket = await context.WebSockets.AcceptWebSocketAsync(); connection = new PiHubConnection(this, channelId, subscriberId, key) { WebSocket = webSocket }; Connections.Add(connection); return(connection); }
public void Run() { // Não roda caso o Nó seja uma "folha", ou seja, não tenha conexões if (!Connections.Any()) { if (Print) { PrintAtividadesEntrada(); } return; } // Ordena a fila de entrada pela ordem de entrada na atividade FilaEntrada = FilaEntrada.OrderBy(x => x.Inicio).ToList(); foreach (SItem item in FilaEntrada) { // Seleciona a próxima atividade (conexão) de acordo com um número aleatório gerado SConnection target = GetConnectionByProbability(rand.NextDouble()); // Pega o tempo de processamento desse item e atualiza o mesmo var tempoProc = target.CalcTS(); var newItem = ProcessItem(new SItem { Nome = item.Nome, Inicio = item.Inicio }, tempoProc); // Adiciona o item na lista de resultados Resultado.Add(newItem); // Adiciona o item na fila de entrada da próxima atividade target.Connection.FilaEntrada.Add(new SItem { Inicio = newItem.Fim, Nome = newItem.Nome }); } // Faz o Display das informações obtidas com a simulação da atividade if (Print) { PrintAtividadesResultado(); } // Processa as connexões RunConnectedActivities(); }
public bool Any() { return(HubVariables.Any() || Datajobs.Any() || Datalinks.Any() || Connections.Any() || Tables.Any() || ColumnValidations.Any() || CustomFunctions.Any() || FileFormats.Any() || RemoteAgentHubs.Any() || DatalinkTests.Any() || Views.Any() || Apis.Any() || Dashboards.Any() || ListOfValues.Any() || Tags.Any() || TagObjects.Any()); }
public async Task RefreshConnections() { //RefreshingConnections = true; IAgentContext context = await _agentContextProvider.GetContextAsync(); IList <ConnectionRecord> connectionRecords = await _connectionService.ListAsync(context); connectionRecords = connectionRecords.OrderBy(r => r.CreatedAtUtc).ToList(); foreach (var record in connectionRecords) { AddOrUpdateConnection(record); } IList <ConnectionViewModel> connectionsToRemove = new List <ConnectionViewModel>(); foreach (ConnectionViewModel connection in Connections) { var found = false; foreach (var record in connectionRecords) { if (record.Id == connection.Id) { found = true; break; } } if (!found) { connectionsToRemove.Add(connection); } } foreach (ConnectionViewModel connection in connectionsToRemove) { Connections.Remove(connection); } HasConnections = Connections.Any(); //RefreshingConnections = false; }
/// <summary> /// Refreshes the connections from the available device sources /// </summary> /// <returns>Collection of connection objects available to the app</returns> public async Task<Connections> RefreshConnections() { Connections connections = new Connections(); connections.Clear(); await BluetoothSerial.listAvailableDevicesAsync().AsTask().ContinueWith( listTask => { listTask.Result.ForEach( d => connections.Add(new Connection(d.Name, d, ConnectionType.BluetoothSerial))); }); await UsbSerial.listAvailableDevicesAsync().AsTask().ContinueWith( listTask => { listTask.Result.ForEach( d => connections.Add(new Connection(d.Name, d, ConnectionType.UsbSerial))); }); string previousConnection = App.CurrentAppSettings.PreviousConnectionName; if (this.CurrentConnection == null && !string.IsNullOrEmpty(previousConnection) && connections.Any(c => c.DisplayName == App.CurrentAppSettings.PreviousConnectionName)) { await this.Connect( connections.FirstOrDefault( c => c.DisplayName == App.CurrentAppSettings.PreviousConnectionName)); } return connections; }