private void StoreConnection(int?boardId = null) { var user = _userResolver.GetUser(Context.User); if (user == null) { return; } var connectionId = Context.ConnectionId; if (boardId.HasValue && !_accessService.HasAccess(user.ID, boardId.Value)) { return; } if (ActiveConnections.TryGetValue(connectionId, out var syncPoint)) { syncPoint.BoardId = boardId; } else { _activeConnections.TryAdd(Context.ConnectionId, new BoardSynchronizationPoint { UserId = user.ID, BoardId = boardId }); } }
public void FreeConnectionID(int connectionID) { if (ActiveConnections.ContainsKey(connectionID)) { this.ActiveConnections.Remove(connectionID); } }
private async void LoggingInMessageHandler(NotificationMessage <ConnectionInfo> message) { if (message.Notification == Constants.LoggingInMessage) { var _mongoDbService = SimpleIoc.Default.GetInstanceWithoutCaching <IMongoDbService>(); MongoDbServerViewModel serverVm = new MongoDbServerViewModel(_mongoDbService); serverVm.IsBusy = true; serverVm.Name = message.Content.Address + ":" + message.Content.Port; DispatcherHelper.CheckBeginInvokeOnUI(() => { ActiveConnections.Add(serverVm); }); try { LoggerHelper.Logger.Info("Connecting to server " + message.Content.Address + ":" + message.Content.Port); var serverInfo = await _mongoDbService.ConnectAsync(message.Content); serverVm.ServerVersion = SemanticVersion.Parse(serverInfo.ServerStatus["version"].AsString); LoggerHelper.Logger.Info("Connected to server " + message.Content.Address + ":" + message.Content.Port); serverVm.LoadDatabases(serverInfo.Databases); } catch (Exception ex) { LoggerHelper.Logger.Error("Failed to connect to server " + message.Content.Address + ":" + message.Content.Port, ex); } serverVm.IsBusy = false; } }
private Enums.Mode SetConnection(CallEventArgs call) { Port portOut = Ports.FirstOrDefault(x => x.PhoneNumber == call.OutPhoneNumber); if (portOut == null) { return(Enums.Mode.NotExist); } Port portIn = Ports.First(x => x.PhoneNumber == call.InPhoneNumber); Enums.Mode modePort = portOut.Mode; if (modePort == Enums.Mode.Free) { if (!ActiveConnections.ContainsKey(call.InPhoneNumber)) { GetStation().TerminalAnswered += portIn.OutCallAnswered; GetStation().TerminalNoAnswered += portIn.OutCallNoAnswered; GetStation().TerminalRejected += portIn.OutCallRejected; ActiveConnections.Add(call.InPhoneNumber, call.OutPhoneNumber); portOut.Mode = Enums.Mode.Ringing; portIn.Mode = Enums.Mode.Ringing; portOut.AnswerEvent += AnsweredCall; portOut.RejectEvent += RejectedCall; portOut.NoAnswerEvent += NoAnsweredCall; portOut.IncomingCall(call.InPhoneNumber); } } if (modePort == Enums.Mode.Ringing) { return(Enums.Mode.Busy); } return(modePort); }
private void MainWindowViewModel_OnConnectionsInformationReceived(List <ConnectionInfo> connections) { App.Current.Dispatcher.Invoke((Action) delegate { lock (lockActiveSessions) { int selIndex = ConnectionInfoCollectionView.CurrentPosition; _connectionInfoCollection.Clear(); foreach (var connection in connections) { ActiveConnections activeConn = new ActiveConnections(); activeConn.Username = connection.Username; if (_connectionInfoCollection.Contains(activeConn)) { activeConn = _connectionInfoCollection.First(x => x.Username == connection.Username); } else { _connectionInfoCollection.Add(activeConn); } activeConn.Connections.Add(connection); } ConnectionInfoCollectionView.MoveCurrentToPosition(selIndex); ConnectionInfoCollectionView.Refresh(); } }); }
private Task Client_VoiceStateUpdate(VoiceStateUpdateEventArgs e) { var gld = e.Guild; if (gld == null) { return(Task.Delay(0)); } if (e.User == null) { return(Task.Delay(0)); } if (e.User.Id == Client.CurrentUser.Id && ActiveConnections.TryGetValue(e.Guild.Id, out var vnc)) { vnc.Channel = e.Channel; } if (!string.IsNullOrWhiteSpace(e.SessionId) && e.User.Id == Client.CurrentUser.Id && e.Channel != null && VoiceStateUpdates.ContainsKey(gld.Id)) { VoiceStateUpdates.TryRemove(gld.Id, out var xe); xe.SetResult(e); } return(Task.Delay(0)); }
/// <summary> /// Funzione che chiude un singolo tab /// </summary> /// <param name="tab">Riferimento al tab da chiudere</param> public void CloseTab(DynamicTabItem tab) { // Caso in cui il tab da chiudere sia l'ultimo attivo: chiusura dell'intera finestra if (ServerTabs.Count == 1) { this.Close(); return; } ServerTabManagement servertab = tab.ServerTab; // In caso di chiusura della main window, la funzione di chiusura di questo tab non andrà più eseguita ClosingEvent -= servertab.ServerTabClose; // Chiusura del tab servertab.ServerTabClose(); // Rimozione di questo tab dalla lista dei tab dei server ServerTabs.Remove(tab); // Rimozione dei questa connessione dalla lista di connessioni attive ActiveConnections.Remove(tab.RemoteHost); if (ServerTabs.Count == 1) { ForegroundAppsBox.IsEnabled = false; } }
public void SetActive(int conID) { if (!ActiveConnections.Contains(conID) && connections.Count > conID && conID >= 0) { activeConnections.Add(conID); ConnectionVoxelContainer.StoreConnection(connections[conID]); } }
public void SetInactive(int conID) { if (ActiveConnections.Contains(conID) && connections.Count > conID) { activeConnections.Remove(conID); ConnectionVoxelContainer.RemoveConnection(connections[conID]); } }
public virtual void Disconnected(ConnectionServer con, EDisconnectReason eReason) { Logger.Info("Connection closed: {connection}. {reason}.", con, eReason); con.Disconnect(eReason); if (!ActiveConnections.Remove(con)) { Logger.Error("Unknown connection: {connection}.", con); } }
/// <summary> /// Gets a VoiceNext connection for specified guild. /// </summary> /// <param name="guild">Guild to get VoiceNext connection for.</param> /// <returns>VoiceNext connection for the specified guild.</returns> public VoiceNextConnection GetConnection(DiscordGuild guild) { if (ActiveConnections.ContainsKey(guild.Id)) { return(ActiveConnections[guild.Id]); } return(null); }
/// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { _activeConnections = new ObservableCollection <MongoDbServerViewModel>(); _tabs = new ObservableCollection <TabViewModel>(); LogEvents = LoggerHelper.LogEvents; ViewLogDetails = new RelayCommand <log4net.Core.LoggingEvent>((param) => { Messenger.Default.Send(new NotificationMessage <log4net.Core.LoggingEvent>(param, Constants.ShowLogDetailsMessage)); }); Messenger.Default.Register <NotificationMessage <ConnectionInfo> >(this, (message) => LoggingInMessageHandler(message)); Messenger.Default.Register <NotificationMessage <TabViewModel> >(this, (message) => TabMessageHandler(message)); Messenger.Default.Register <NotificationMessage <MongoDbServerViewModel> >(this, (message) => MongoDbServerMessageHandler(message)); if (IsInDesignModeStatic) { var _mongoDbService = GalaSoft.MvvmLight.Ioc.SimpleIoc.Default.GetInstanceWithoutCaching <IMongoDbService>(); MongoDbServerViewModel serverVm = new MongoDbServerViewModel(_mongoDbService); serverVm.Name = "127.0.0.1:27017"; ActiveConnections.Add(serverVm); var task = _mongoDbService.ConnectAsync(new ConnectionInfo()); task.Wait(); var serverInfo = task.Result; serverVm.LoadDatabases(serverInfo.Databases); TabViewModel tabDesign1 = SimpleIoc.Default.GetInstanceWithoutCaching <TabViewModel>(); tabDesign1.Name = "Collection1"; tabDesign1.SelectedOperation = tabDesign1.FindOperation; this.Tabs.Add(tabDesign1); this.SelectedTab = tabDesign1; TabViewModel tabDesign2 = SimpleIoc.Default.GetInstanceWithoutCaching <TabViewModel>(); tabDesign2.Name = "localhost:27017"; tabDesign2.SelectedOperation = tabDesign2.AggregateOperation; this.Tabs.Add(tabDesign2); LogEvents = new ObservableCollection <log4net.Core.LoggingEvent>(); LogEvents.Add(new log4net.Core.LoggingEvent(new log4net.Core.LoggingEventData() { Level = log4net.Core.Level.Debug, Message = "Test debug message", TimeStamp = DateTime.Parse("2015/11/09 00:01:00") })); LogEvents.Add(new log4net.Core.LoggingEvent(new log4net.Core.LoggingEventData() { Level = log4net.Core.Level.Info, Message = "Test info message", TimeStamp = DateTime.Parse("2015/11/09 00:02:00") })); LogEvents.Add(new log4net.Core.LoggingEvent(new log4net.Core.LoggingEventData() { ExceptionString = "TestException", Level = log4net.Core.Level.Warn, Message = "Test warn message", TimeStamp = DateTime.Parse("2015/11/09 00:03:00") })); LogEvents.Add(new log4net.Core.LoggingEvent(new log4net.Core.LoggingEventData() { ExceptionString = "TestException", Level = log4net.Core.Level.Error, Message = "Test error message", TimeStamp = DateTime.Parse("2015/11/09 00:04:00") })); } }
private void MongoDbServerMessageHandler(NotificationMessage <MongoDbServerViewModel> message) { if (message.Notification == Constants.DisconnectMessage) { LoggerHelper.Logger.Info("Disconnecting from server " + message.Content.Name); DispatcherHelper.CheckBeginInvokeOnUI(() => { ActiveConnections.Remove(message.Content); message.Content.Cleanup(); }); } }
/// <summary> /// create a new managed connection. /// </summary> /// <param name="connection">connection</param> /// <param name="attemptToPool">true if we are going to try and reuse the /// connection if possible</param> public ManagedConnection(SqlOlapConnectionInfoBase sourceConnection, bool attemptToPool) { // parameter check if (sourceConnection == null) { throw new ArgumentNullException("sourceConnection"); } // see if the connection can restrict access (single user mode) IRestrictedAccess access = sourceConnection as IRestrictedAccess; // see if it is cloneable ICloneable cloneable = sourceConnection as ICloneable; lock (ActiveConnections) { // if it's not single user mode then we can see if the object can be cloned if (access == null || access.SingleConnection == false) { // if we are going to attempt to pool, see if the connection is in use if (attemptToPool && !ActiveConnections.Contains(SharedConnectionUtil.GetConnectionKeyName(sourceConnection))) { // add it to the hashtable to indicate use. ActiveConnections.Add(SharedConnectionUtil.GetConnectionKeyName(sourceConnection), sourceConnection); this.connection = sourceConnection; this.closeOnDispose = false; this.connectionAddedToActiveConnections = true; } else if (cloneable != null) { this.connection = (SqlOlapConnectionInfoBase)cloneable.Clone(); this.closeOnDispose = true; } else if (sourceConnection is SqlConnectionInfoWithConnection) { this.connection = ((SqlConnectionInfoWithConnection)sourceConnection).Copy(); this.closeOnDispose = true; } } } // if everything else has failed just use to passed in connection. if (this.connection == null) { this.connection = sourceConnection; } // always set the lock timeout to prevent the shell from not responding if (this.connection is SqlConnectionInfoWithConnection) { // set lock_timeout to 10 seconds ((SqlConnectionInfoWithConnection)this.connection).ServerConnection.LockTimeout = 10; } }
public void SetInactive(Connection c) { int i = 0; foreach (Connection con in Connections) { if (c == con) { if (ActiveConnections.Contains(i)) { activeConnections.Remove(i); } } ++i; } }
public void SetActive(Connection c) { int i = 0; foreach (Connection con in Connections) { if (c == con) { if (!ActiveConnections.Contains(i)) { activeConnections.Add(i); } } ++i; } }
private async Task Client_VoiceServerUpdate(VoiceServerUpdateEventArgs e) { var gld = e.Guild; if (gld == null) { return; } if (ActiveConnections.TryGetValue(e.Guild.Id, out var vnc)) { vnc.ServerData = new VoiceServerUpdatePayload { Endpoint = e.Endpoint, GuildId = e.Guild.Id, Token = e.VoiceToken }; var eps = e.Endpoint; var epi = eps.LastIndexOf(':'); var eph = string.Empty; var epp = 80; if (epi != -1) { eph = eps.Substring(0, epi); epp = int.Parse(eps.Substring(epi + 1)); } else { eph = eps; } vnc.ConnectionEndpoint = new ConnectionEndpoint { Hostname = eph, Port = epp }; vnc.Resume = false; await vnc.ReconnectAsync().ConfigureAwait(false); } if (VoiceServerUpdates.ContainsKey(gld.Id)) { VoiceServerUpdates.TryRemove(gld.Id, out var xe); xe.SetResult(e); } }
public void SetActive(Connection c) { int i = 0; foreach (Connection con in Connections) { if (c == con) { if (!ActiveConnections.Contains(i)) { activeConnections.Add(i); ConnectionVoxelContainer.StoreConnection(con); return; } } ++i; } }
protected override NorthwindDataContext CreateDataContext() { NorthwindDataContext context = null; string connection = ActiveConnections.Get("Northwind"); if (!string.IsNullOrEmpty(connection)) { // if there is an active connection in scope use it context = new NorthwindDataContext(connection); } else { context = base.CreateDataContext(); } return(context); }
public void SetInactive(Connection c) { int i = 0; foreach (Connection con in Connections) { if (c == con) { if (ActiveConnections.Contains(i)) { activeConnections.Remove(i); ConnectionVoxelContainer.RemoveConnection(con); return; } } ++i; } }
/// <summary> /// Close the current connection if applicable. /// </summary> public void Close() { if (this.closed) { return; } if (this.closeOnDispose) { IDisposable disp = this.connection as IDisposable; if (disp != null) { disp.Dispose(); } } else { // if we are not closing the connection and it is a sql connection then ensure it // is left in the master database. SqlConnectionInfoWithConnection sqlConnection = this.connection as SqlConnectionInfoWithConnection; if (sqlConnection != null && sqlConnection.ServerConnection.DatabaseEngineType == DatabaseEngineType.Standalone) { try { sqlConnection.ServerConnection.ExecuteNonQuery("use [master]"); } // don't error if this fails catch { } } } if (this.connectionAddedToActiveConnections) { lock (ActiveConnections) { ActiveConnections.Remove(SharedConnectionUtil.GetConnectionKeyName(connection)); } } this.connection = null; this.closed = true; }
protected override DbCtxNorthwindEntities CreateDbContext() { DbCtxNorthwindEntities context = null; string connection = ActiveConnections.Get("Northwind"); if (!string.IsNullOrEmpty(connection)) { // if there is an active connection in scope use it // Here we have to append the mapping file info to the connection string connection = string.Format("metadata=res://*/Northwind.NorthwindDbCtx.csdl|res://*/Northwind.NorthwindDbCtx.ssdl|res://*/Northwind.NorthwindDbCtx.msl;provider=System.Data.SqlClient;provider connection string=\"{0}\"", connection); context = new DbCtxNorthwindEntities(connection); } else { context = base.CreateDbContext(); } return(context); }
protected override EFCFNorthwindEntities CreateDbContext() { EFCFNorthwindEntities context = null; string connection = ActiveConnections.Get("Northwind"); if (!string.IsNullOrEmpty(connection)) { // if there is an active connection in scope use it // Here we have to append the mapping file info to the connection string connection = string.Format("Persist Security Info=True;MultipleActiveResultSets=True;{0}", connection); context = new EFCFNorthwindEntities(connection); } else { context = base.CreateDbContext(); } return(context); }
private void NoAnsweredCall(object o, EventArgs e) { Port port = (o as Port); port.AnswerEvent -= AnsweredCall; port.RejectEvent -= RejectedCall; port.NoAnswerEvent -= NoAnsweredCall; var connection = ActiveConnections.FirstOrDefault(x => x.Value == port.PhoneNumber); ActiveConnections.Remove(connection.Key); TerminalNoAnswered?.Invoke(this, new CallEventArgs(connection.Value, connection.Key)); if (Calls.ContainsKey(connection)) { Calls[connection].Add(new CallInfo(connection.Key, connection.Value, DateTime.Now, Enums.AnswerType.NotResponding)); } else { Calls.Add(connection, new List <CallInfo>()); Calls[connection].Add(new CallInfo(connection.Key, connection.Value, DateTime.Now, Enums.AnswerType.NotResponding)); } }
protected override NorthwindEntities CreateObjectContext() { NorthwindEntities context = null; string connection = ActiveConnections.Get("Northwind"); if (!string.IsNullOrEmpty(connection)) { // if there is an active connection in scope use it var builder = new EntityConnectionStringBuilder(); builder.ConnectionString = ConfigurationManager.ConnectionStrings[NorthwindEntities.ConnectionStringName].ConnectionString; builder.ProviderConnectionString = connection; context = new NorthwindEntities(builder.ConnectionString); } else { context = base.CreateObjectContext(); } return(context); }
private void ExecuteDisconnectSelectedUsersCommand() { ActiveConnections session = null; lock (lockActiveSessions) { int selIndex = ConnectionInfoCollectionView.CurrentPosition; if (selIndex >= 0 && selIndex < _connectionInfoCollection.Count) { session = _connectionInfoCollection[selIndex]; } } if (session != null) { DealerService.GetInstance().disconnectAndLockSession( session.Username, session.Connections.Select(x => x.MqName).ToArray() ); } }
protected override EFCFNorthwindEntities CreateDbContext() { EFCFNorthwindEntities context = null; string connection = ActiveConnections.Get("Northwind"); if (!string.IsNullOrEmpty(connection)) { // if there is an active connection in scope use it // Here we have to append the mapping file info to the connection string //"data source=Alexappfxss01;Persist Security Info=True;User ID=RiaTest;Password=TestPassword;MultipleActiveResultSets=True;Database=Northwind_Light" connection = string.Format("Persist Security Info=True;MultipleActiveResultSets=True;{0}", connection); //connection = "Data Source=AlexAppFxss02;Initial Catalog=Northwind;Persist Security Info=True;User ID=RiaTest;Password=TestPassword;MultipleActiveResultSets=True"; context = new EFCFNorthwindEntities(connection); } else { context = base.CreateDbContext(); } return(context); }
private void Vnc_VoiceDisconnected(DiscordGuild guild) { VoiceNextConnection vnc = null; if (ActiveConnections.ContainsKey(guild.Id)) { ActiveConnections.TryRemove(guild.Id, out vnc); } var vsd = new VoiceDispatch { OpCode = 4, Payload = new VoiceStateUpdatePayload { GuildId = guild.Id, ChannelId = null } }; var vsj = JsonConvert.SerializeObject(vsd, Formatting.None); (guild.Discord as DiscordClient)._webSocketClient.SendMessage(vsj); }
private void EndCall(object o, EventArgs e) { Port port = (o as Port); Port secondPort; port.EndCallEventOnPort -= EndCall; var connection = ActiveConnections.FirstOrDefault(x => (x.Value == (o as Port).PhoneNumber) || (x.Key == (o as Port).PhoneNumber)); if (port.PhoneNumber == connection.Key) { secondPort = Ports.First(x => x.PhoneNumber == connection.Value); } else { secondPort = Ports.First(x => x.PhoneNumber == connection.Key); } List <CallInfo> calls = Calls.FirstOrDefault(x => (x.Key.Key == port.PhoneNumber && x.Key.Value == secondPort.PhoneNumber) || (x.Key.Value == port.PhoneNumber && x.Key.Key == secondPort.PhoneNumber)).Value; CallInfo call = calls[calls.Count - 1]; call.FinishCall(DateTime.Now); EndCallEvent?.Invoke(this, call); secondPort.EndCallEventOnPort -= EndCall; ActiveConnections.Remove(connection.Key); }
/// <summary> /// Create a VoiceNext connection for the specified channel. /// </summary> /// <param name="channel">Channel to connect to.</param> /// <returns>VoiceNext connection for this channel.</returns> public async Task <VoiceNextConnection> ConnectAsync(DiscordChannel channel) { if (channel.Type != ChannelType.Voice) { throw new ArgumentException(nameof(channel), "Invalid channel specified; needs to be voice channel"); } if (channel.Guild == null) { throw new ArgumentException(nameof(channel), "Invalid channel specified; needs to be guild channel"); } if (!channel.PermissionsFor(channel.Guild.CurrentMember).HasPermission(Permissions.UseVoice)) { throw new InvalidOperationException("You need UseVoice permission to connect to this voice channel"); } var gld = channel.Guild; if (ActiveConnections.ContainsKey(gld.Id)) { throw new InvalidOperationException("This guild already has a voice connection"); } var vstut = new TaskCompletionSource <VoiceStateUpdateEventArgs>(); var vsrut = new TaskCompletionSource <VoiceServerUpdateEventArgs>(); this.VoiceStateUpdates[gld.Id] = vstut; this.VoiceServerUpdates[gld.Id] = vsrut; var vsd = new VoiceDispatch { OpCode = 4, Payload = new VoiceStateUpdatePayload { GuildId = gld.Id, ChannelId = channel.Id, Deafened = false, Muted = false } }; var vsj = JsonConvert.SerializeObject(vsd, Formatting.None); await(channel.Discord as DiscordClient)._webSocketClient.SendMessageAsync(vsj).ConfigureAwait(false); var vstu = await vstut.Task.ConfigureAwait(false); var vstup = new VoiceStateUpdatePayload { SessionId = vstu.SessionId, UserId = vstu.User.Id }; var vsru = await vsrut.Task.ConfigureAwait(false); var vsrup = new VoiceServerUpdatePayload { Endpoint = vsru.Endpoint, GuildId = vsru.Guild.Id, Token = vsru.VoiceToken }; var vnc = new VoiceNextConnection(this.Client, gld, channel, this.Configuration, vsrup, vstup); vnc.VoiceDisconnected += this.Vnc_VoiceDisconnected; await vnc.ConnectAsync().ConfigureAwait(false); await vnc.WaitForReadyAsync().ConfigureAwait(false); this.ActiveConnections[gld.Id] = vnc; return(vnc); }