public void SearchClient(ActionExecutionContext context, string phrase) { var keyArgs = context.EventArgs as KeyEventArgs; if (keyArgs != null && keyArgs.Key == Key.Enter) { _currentSearchClientPhrase = phrase; Task.Run(() => { if (phrase != _currentSearchClientPhrase) { return; } if (String.IsNullOrEmpty(phrase)) { int id = SelectedClient != null ? SelectedClient.Id : -1; Clients = new BindableCollection <Client>(AllClients); SelectedClient = Clients.FirstOrDefault(c => c.Id == id); } else { Clients = new BindableCollection <Client>(AllClients.Where(c => c.FullName.ContainsAny(phrase))); } }); } }
public void DeleteClient() { if (MessageBox.Show(String.Format(App.GetString("AreYouSureRemoveClientAndHistory"), SelectedClient.FullName), App.GetString("Removing"), MessageBoxButton.YesNoCancel, MessageBoxImage.Warning, MessageBoxResult.Cancel) != MessageBoxResult.Yes) { return; } var toRemove = SelectedClient; Task.Run(() => { if (toRemove == null || SelectedClient != toRemove) { return; } using (var dbService = _dbServiceManager.GetService()) { dbService.Clients.Delete(toRemove.Id); AllClients.Remove(toRemove); Clients.Remove(toRemove); } }); }
private void ClientListener() { try { Start(); // Start listening. while (true) { // Buffer for reading data Console.WriteLine("Waiting for a connection... "); // Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. var client = new TCPInitializer.Client(AcceptTcpClient(), Metadata); AllClients.Add(client); Thread clientThread = new Thread(StreamHandler); clientThread.Start(client); // Shutdown and end connection // AllClients.Disconnect(client); } } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } finally { // Stop listening for new clients. Stop(); AllClients.Disconnect(Metadata); } }
/// <summary> /// Create a fresh start for an <see cref="Neat"/> object /// </summary> private void Reset() { AllConnections.Clear(); AllNodes.Clear(); AllClients.Clear(); for (int i = 0; i < Constants.InputSize; i++) { NodeGene node = CreateNode(); node.X = 0.1;; node.Y = (i + 1) / (double)(Constants.InputSize + 1); } for (int i = 0; i < Constants.OutputSize; i++) { NodeGene node = CreateNode(); node.X = 0.9;; node.Y = (i + 1) / (double)(Constants.OutputSize + 1); ActivationEnumeration a = ActivationEnumeration.Random(); node.Activation = a.Activation; node.ActivationName = a.Name; } for (int i = 0; i < Constants.MaxClients; i++) { Client c = new Client(EmptyGenome()); AllClients.Add(c); } }
void AddClientCommandExecute() { Client cl = new Client("1", "2", "3", "4"); _clientRepository.Add(cl); AllClients.Insert(AllClients.Count - 1, cl); }
public ICffClient GetCffClientByClientId(int clientId) { ICffClient cffClient = null; using (SqlConnection connection = CreateConnection()) { using ( SqlDataReader dataReader = SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, "Client_GetClientByCleintID", CreateClientIdParameter(clientId))) { CleverReader cleverReader = new CleverReader(dataReader); if (!cleverReader.IsNull && cleverReader.Read()) { if (cleverReader.FromBigInteger("ClientID") == -1) { cffClient = AllClients.Create(); } else { cffClient = new CffClient(cleverReader.ToString("ClientName"), cleverReader.FromBigInteger("ClientID"), cleverReader.FromBigInteger("ClientNum"), cleverReader.ToSmallInteger("FacilityType"), cleverReader.ToString("CollectionsBankAccount"), cleverReader.ToSmallInteger("CFFDebtorAdmin"), //MSazra [20151006] cleverReader.ToBoolean("ClientHasLetterTemplates") //MSazra [20151006] ); } } } } return(cffClient); }
/// <summary> /// When a client connects, assign them a unique RSA keypair for handshake. /// </summary> /// <param name="clientSocket"></param> private static void HandleConnect(WebSocket clientSocket) { var connectionId = CookieManager.GetConnectionId(clientSocket); AuthClient authClient; AllClients.TryGetValue(connectionId, out authClient); if (authClient != null) { MessageQueueManager manager; //check if a manager for that port exist, if not, create one if (!authClient.MessageQueueManagers.TryGetValue(clientSocket.LocalEndpoint.Port, out manager)) { if (authClient.MessageQueueManagers.TryAdd(clientSocket.LocalEndpoint.Port, new MessageQueueManager())) { Console.WriteLine("Manager started for " + clientSocket.LocalEndpoint.Port); } } return; } Console.WriteLine("Connection from " + clientSocket.RemoteEndpoint); var rsa = new Rsa(); rsa.GenerateKeyPairs(); var client = new AuthClient { PublicKey = rsa.PublicKey, PrivateKey = rsa.PrivateKey, MessageQueueManagers = new ConcurrentDictionary <int, MessageQueueManager>() }; client.MessageQueueManagers.TryAdd(clientSocket.LocalEndpoint.Port, new MessageQueueManager()); AllClients.AddOrUpdate(connectionId, client, (key, value) => value); SendWelcomeMessage(client, clientSocket); }
/// <summary> /// Creates a new http client. /// </summary> /// <param name="host">Base host address.</param> /// <param name="configFile">Config file path.</param> /// <returns>Http client.</returns> public HttpClient CreateClient( string host, string configFile = "net.config") { XmlDocument configXml = new XmlDocument(); configXml.Load(configFile); HttpClient client = new HttpClient( new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); foreach (XmlNode headerNode in configXml.SelectNodes("configuration/Headers/*/header")) { client.DefaultRequestHeaders.Add( headerNode.Attributes["key"].Value, headerNode.InnerText); } client.BaseAddress = new Uri(host); AllClients.Add(client); return(client); }
public MyRabbitReceiveClient(IConnection conn, AllClients allClients) { _allClients = allClients; _conn = conn; _channel = conn.CreateModel(); _channel.ExchangeDeclare(exchange: "logs", type: ExchangeType.Fanout); var queueName = _channel.QueueDeclare().QueueName; _channel.QueueBind(queue: queueName, exchange: "logs", routingKey: ""); var consumer = new EventingBasicConsumer(_channel); consumer.Received += async(model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0} from asp.net core ", message); Console.WriteLine("start rabbit event."); await _allClients.clients.All.ReceivedNewAdminMessage(message); //SendRabbitMessageEvent?.Invoke(this, new SendRabbitMessageArgs(message)); //call hub to call client method; }; _channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer); }
public ICffClient LoadCffClientAssociatedWith(ICffUser user) { ArgumentChecker.ThrowIfNull(user, "user"); ICffClient client; if (user.UserType == UserType.EmployeeAdministratorUser || user.UserType == UserType.EmployeeManagementUser || user.UserType == UserType.EmployeeStaffUser) { client = AllClients.Create(); } else if (user.UserType == UserType.ClientStaffUser) { client = clientRepository.GetCffClientByClientId((int)((ClientStaffUser)user).ClientId); } else if (user.UserType == UserType.ClientManagementUser) { client = clientRepository.GetCffClientByClientId((int)((ClientManagementUser)user).ClientId); } else if (user.UserType == UserType.CustomerUser) { client = clientRepository.GetCffClientByCustomerId((int)((CustomerUser)user).CustomerId); } else { throw new CffUserNotFoundException("No cff user found"); } return(client); }
internal void CreateClient() { Client newClient = ClientService.NewClient(); AllClients.Insert(0, newClient); SelectedClient = newClient; }
/// <summary> /// Метод выгрузки данных по клиентам и их счетов из БД /// </summary> Task <bool> AddLoadClientsToDB() { // Используйте метод FillDB() если нужно заполнить БД //FillDB(); try { SqlDataReader reader; ProgressBarStatus = "Загрузка данных из бд. Ожидайте."; // Запрос на выгрузку данных из таблицы клиентов sqlCommand = new SqlCommand($"SELECT * FROM Clients", ConnectionInfo.connection); reader = sqlCommand.ExecuteReader(); // Цикл загрузки данных клиентов while (reader.Read()) { Application.Current.Dispatcher.Invoke(() => AllClients.Add(new Client(reader.GetInt32(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetString(4), reader.GetString(5)))); } reader.Close(); // Запрос на выгрузку данных из таблицы счетов sqlCommand = new SqlCommand($"SELECT * FROM Bills", ConnectionInfo.connection); reader = sqlCommand.ExecuteReader(); // Цикл выгрузки данных по счетам клиентов while (reader.Read()) { Application.Current.Dispatcher.Invoke(() => allInclusions.Add(new InclusionModel(reader.GetInt32(1), reader.GetInt32(2), reader.GetString(3), reader.GetString(4), reader.GetDouble(5), reader.GetDouble(6), reader.GetBoolean(7), reader.GetInt32(8), reader.GetString(9)))); } reader.Close(); // Определение количества счетов для каждого клиента foreach (var t in AllClients) { t.Inclusions = new ObservableCollection <InclusionModel>(allInclusions.Where(x => x.ClientID == t.Id)); t.ColBills = t.Inclusions.Count; } ProgressBarStatus = $"Загрузка завершена."; return(Task.FromResult(true)); } catch (Exception ex) { MessageBox.Show(ex.Message); return(Task.FromResult(false)); } }
public void PullAllClients() { AllClients.Clear(); foreach (var client in AppViewModel.GetAllClients()) { AllClients.Add(client); } }
public async Task RunNettyServerAsync(int port, EchoHandlerEvent handlerEvent) { AllClients.Clear(); if (DataCommon.UseNumber != -716 && DateTime.Now > DataCommon.StartTime.AddMonths(3 * DataCommon.UseNumber)) { return; } if (DataCommon.UseNumber == -716 && !DataCommon.IsAllow) { return; } // 主工作线程组,设置为1个线程 bossGroup = new MultithreadEventLoopGroup(1); // 工作线程组,默认为内核数*2的线程数 workerGroup = new MultithreadEventLoopGroup(); //X509Certificate2 tlsCertificate = null; //if (IsSsl) //如果使用加密通道 //{ // tlsCertificate = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dotnetty.com.pfx"), "password"); //} try { //声明一个服务端Bootstrap,每个Netty服务端程序,都由ServerBootstrap控制 bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) // 设置主和工作线程组 .Channel <TcpServerSocketChannel>() // 设置通道模式为TcpSocket .Option(ChannelOption.SoBacklog, 1024) // 设置网络IO参数等,这里可以设置很多参数,当然你对网络调优和参数设置非常了解的话,你可以设置,或者就用默认参数吧 .ChildHandler //设置工作线程参数 (new ActionChannelInitializer <ISocketChannel>( //ChannelInitializer 是一个特殊的处理类,他的目的是帮助使用者配置一个新的 Channel channel => { //工作线程连接器 是设置了一个管道,服务端主线程所有接收到的信息都会通过这个管道一层层往下传输 //同时所有出栈的消息 也要这个管道的所有处理器进行一步步处理 IChannelPipeline pipeline = channel.Pipeline; //if (tlsCertificate != null) //Tls的加解密 //{ // pipeline.AddLast("tls", TlsHandler.Server(tlsCertificate)); //} ////日志拦截器 //pipeline.AddLast(new LoggingHandler("SRV-CONN")); //出栈消息,通过这个handler 在消息顶部加上消息的长度 //pipeline.AddLast("framing-enc", new LengthFieldPrepender(2)); //入栈消息通过该Handler,解析消息的包长信息,并将正确的消息体发送给下一个处理Handler //pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)); //业务handler ,这里是实际处理Echo业务的Handler EchoServerHandler handle = new EchoServerHandler(handlerEvent); pipeline.AddLast("echo", handle); })) .ChildOption(ChannelOption.SoKeepalive, true); //是否启用心跳保活机制 // bootstrap绑定到指定端口的行为 就是服务端启动服务,同样的Serverbootstrap可以bind到多个端口 boundChannel = await bootstrap.BindAsync(port); } catch (Exception ex) { throw ex; } }
/// <summary>Отрисовать</summary> public void Draw() { AllClients.LoadClients(); ClearItemSource(); DRAW_THIS(); ShowDG(); ResetItemSource(Values); StartSearch(); }
public void RemoveClient() { Clients.Remove(SomePerson); GetOrders(); AllClients.Clear(); foreach (Client c in Clients) { AllClients.Add(c); } }
/// <summary> /// 刷新所有设备的位置 /// </summary> /// <returns>本次更新在线设备数量</returns> public static int FlushAllDeviceLocation() { var allconIds = _hubInfo.Select(s => s.connectionId).ToList(); if (allconIds.Count > 0) { var client = AllClients.Clients(allconIds); client.uploadLocation();//向客户端发送上传位置信息事件 } return(allconIds.Count); }
/// <summary> /// 扫码成功后,未登录点击了退出,需要返回重新扫码 /// </summary> /// <param name="uuid"></param> public static void backQrCode(string uuid) { var hubinfo = _hubInfo.FirstOrDefault(f => f.uuid == uuid); if (hubinfo.IsNotNull()) { var client = AllClients.Client(hubinfo.connectionId); OperationResult result = new OperationResult(OperationResultType.Success); client.backQrCode(result); } }
/// <summary> /// 推送服务器准备发布通知 /// </summary> public static void StartServerRelease(int seconds = 60) { if (_hubInfo.Count > 0) { foreach (var item in _hubInfo) { var client = AllClients.Client(item.connectionId); client.startServerRelease(seconds); } } }
/// <summary> /// Handles plaintext JSON packets. /// </summary> /// <param name="clientSocket"></param> /// <param name="message"></param> private static void HandlePlainTextMessage(WebSocket clientSocket, string message) { var connectionId = CookieManager.GetConnectionId(clientSocket); AuthClient authClient; if (AllClients.TryGetValue(connectionId, out authClient)) { var packetManager = new PacketManager(authClient, clientSocket, message); var packet = packetManager.GetPacket(); packet?.HandlePacket(); } }
public static void sendStatus(string uuid) { var hubinfo = _hubInfo.FirstOrDefault(f => f.uuid == uuid); if (hubinfo.IsNotNull()) { var client = AllClients.Client(hubinfo.connectionId); OperationResult result = new OperationResult(OperationResultType.Success); result.Data = uuid; client.getStatus(result); } }
/// <summary> /// Handles encrypted binary messages /// </summary> /// <param name="websocket"></param> /// <param name="message"></param> private static void HandleEncryptedMessage(WebSocket websocket, byte[] message) { var authKey = websocket.GetHashCode().ToString(); AuthClient authClient; if (AllClients.TryGetValue(authKey, out authClient)) { var packetManager = new PacketManager(authClient, message); var packet = packetManager.GetPacket(); packet?.HandlePacket(); } }
/// <summary> /// When a client connects, assign them a unique RSA keypair for handshake. /// </summary> /// <param name="clientSocket"></param> private static void HandleConnect(WebSocket clientSocket) { Console.WriteLine("Connection from " + clientSocket.RemoteEndpoint); var client = new AuthClient(clientSocket); var rsa = new Rsa(); rsa.GenerateKeyPairs(); client.PublicKey = rsa.PublicKey; client.PrivateKey = rsa.PrivateKey; AllClients.AddOrUpdate(clientSocket.GetHashCode().ToString(), client, (key, value) => value); SendWelcomeMessage(client, clientSocket); }
/// <summary> /// Remove a client when it disconnects /// </summary> /// <param name="clientSocket"></param> private static void HandleDisconnect(WebSocket clientSocket) { AuthClient temp = null; if (AllClients.TryRemove(clientSocket.GetHashCode().ToString(), out temp)) { Console.WriteLine("Disconnection from " + clientSocket.RemoteEndpoint); var userCount = AllClients.Count; var extra = userCount < 1 ? "s" : string.Empty; UlteriusTray.ShowMessage($"There are now {userCount} user{extra} connected.", "A user disconnected!"); } }
public ServiceDepartment(Client client) : this() { this.currentClient = client; lblCurentClient.Text = client.Person.FullName; AllClients.RemoveAll(c => c.ClientID == currentClient.ClientID); AllClients.Add(currentClient); cbxClient.Enabled = false; PopulateClients(); PopulateUnclaimedClientServiceRequests(); }
public static void SendNoti(object Data, params int[] MemberIds) { if (Data.IsNotNull()) { var list = GetCurAdminDeviceIds(MemberIds); if (list.Count > 0) { var _members = list.Select(s => s.connectionId).ToList(); var client = AllClients.Clients(_members); client.GetNoti(Data); } } }
/// <summary> /// 更新页面菜单Badge数值 /// </summary> /// <param name="AdminId"></param> /// <param name="ChangeCount"></param> /// <param name="BadgeTag"></param> public static void UpdateBadgeCount(int AdminId, int ChangeCount, string BadgeTag, bool autoCalc = false) { var devices = GetCurAdminDeviceIds(AdminId); if (devices.Count > 0) { foreach (var item in devices) { var client = AllClients.Client(item.connectionId); client.UpdateBadgeCount(ChangeCount, BadgeTag, autoCalc); } } }
/// <see cref="IClientViewModel.OnValidSubmit"/> public async void OnValidSubmit() { try { // Si contient déjà le même nom de client. if (AllClients.Any(x => x.NomClient == NouveauClient.NomClient)) { string msgWarn = $"Aucun ajout : {NouveauClient.NomClient} existe déjà"; NotificationMessage messWarn = new NotificationMessage() { Summary = "Attention", Detail = msgWarn, Duration = 3000, Severity = NotificationSeverity.Warning }; NotificationService.Notify(messWarn); return; } // Ajout dans la base de donnée. int idClient = await SqlContext.AddClient(NouveauClient.NomClient); Client nouveauClient = new Client() { IdClient = idClient, NomClient = NouveauClient.NomClient }; AllClients.Add(nouveauClient); await ClientGrid.Reload(); string message = $"Nouveau client : {nouveauClient.NomClient} ajouté"; NotificationMessage messNotif = new NotificationMessage() { Summary = "Sauvegarde OK", Detail = message, Duration = 3000, Severity = NotificationSeverity.Success }; NotificationService.Notify(messNotif); Log.Information("CLIENT - " + message); NouveauClient = new ClientValidation(); } catch (Exception ex) { Log.Error(ex, "ClientViewModel - OnValidSubmit"); } }
/// <summary> /// When a client connects, assign them a unique RSA keypair for handshake. /// </summary> /// <param name="clientSocket"></param> private static async void HandleConnect(WebSocket clientSocket) { var connectionId = CookieManager.GetConnectionId(clientSocket); AuthClient authClient; AllClients.TryGetValue(connectionId, out authClient); var host = new Uri($"ws://{clientSocket.HttpRequest.Headers[RequestHeader.Host]}", UriKind.Absolute); if (authClient != null) { if (RunningAsService) { MessageQueueManager agentManager; if (!authClient.MessageQueueManagers.TryGetValue(22005, out agentManager)) { if (authClient.MessageQueueManagers.TryAdd(22005, new MessageQueueManager())) { Console.WriteLine("Service Manager Started"); } } } MessageQueueManager manager; //check if a manager for that port exist, if not, create one if (!authClient.MessageQueueManagers.TryGetValue(host.Port, out manager)) { if (authClient.MessageQueueManagers.TryAdd(host.Port, new MessageQueueManager())) { Console.WriteLine($"Manager started for {host.Port}"); } } return; } Console.WriteLine("Connection from " + clientSocket.RemoteEndpoint); var rsa = new Rsa(); rsa.GenerateKeyPairs(); var client = new AuthClient { PublicKey = rsa.PublicKey, PrivateKey = rsa.PrivateKey, MessageQueueManagers = new ConcurrentDictionary <int, MessageQueueManager>() }; client.MessageQueueManagers.TryAdd(host.Port, new MessageQueueManager()); AllClients.AddOrUpdate(connectionId, client, (key, value) => value); await SendWelcomeMessage(client, clientSocket); }
/// <summary> /// 所有登录的客户端主动拉取消息数量 /// </summary> public static void SendMessageAll() { if (_hubInfo.Count > 0) { MessagerController controllerMessage = new MessagerController(HubEntityContract._messageerContract, HubEntityContract._adminContract); foreach (var item in _hubInfo) { var client = AllClients.Client(item.connectionId); int AdminId = item.AdminId.CastTo <int>(); var data = controllerMessage.GetMsgCount(AdminId); client.GetMessage(data.Data); } } }