public override async Task <ConfigurationMessage> GetAsync(int id, CancellationToken cancellationToken = default)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }
            var result = new ConfigurationMessage();

            object[] sqlParams =
            {
                new SqlParameter("@Id", id)
            };

            var sql = $@"SELECT * FROM {GetTableName()} WHERE [Id]=@Id";

            using var connection = new SqlConnection(_source.DbConnection);
            var reader = connection.ExecuteQuery(sql, sqlParams.ToArray());

            while (reader.Read())
            {
                result = new ConfigurationMessage
                {
                    Id          = Convert.ToInt32(reader["Id"]),
                    Key         = reader["Key"].ToString(),
                    Value       = reader["Value"].ToString(),
                    Description = reader["Description"].ToString(),
                    Environment = reader["Environment"].ToString(),
                    NameSpace   = reader["NameSpace"].ToString(),
                    CreateTime  = Convert.ToDateTime(reader["CreateTime"].ToString()),
                    UpdateTime  = Convert.ToDateTime(reader["UpdateTime"].ToString()),
                    UtcTime     = Convert.ToDateTime(reader["UtcTime"].ToString())
                };
            }
            return(await Task.FromResult(result));
        }
Exemple #2
0
        public override async Task <ConfigurationMessage> GetAsync(string id, CancellationToken cancellationToken = default)
        {
            var result = new ConfigurationMessage();

            if (cancellationToken.IsCancellationRequested)
            {
                return(result);
            }
            object[] sqlParams =
            {
                new NpgsqlParameter("@Id", id),
            };
            var sql = $@"SELECT * FROM {GetTableName()} WHERE Id=@Id";

            using var connection = new NpgsqlConnection(_source.DbConnectionStr);
            var reader = connection.ExecuteQuery(sql, sqlParams);

            while (reader.Read())
            {
                result = new ConfigurationMessage
                {
                    Id          = reader["Id"].ToString(),
                    Key         = reader["Key"].ToString(),
                    Value       = reader["Value"].ToString(),
                    Description = reader["Description"].ToString(),
                    CreateTime  = Convert.ToDateTime(reader["CreateTime"].ToString()),
                    UtcTime     = Convert.ToDateTime(reader["UtcTime"].ToString())
                };
            }
            return(await Task.FromResult(result));
        }
        private void SendConfigurationIfRequired()
        {
            var configForExternalProcess = ConfigForExternalProcess;

            if (configForExternalProcess != null)
            {
                var id = Guid.NewGuid();

                try
                {
                    var request = new ConfigurationMessage
                    {
                        Id     = id,
                        Config = ConfigForExternalProcess,
                    };
                    var payload = ExtProtocolConvert.Encode(request);

                    _process.StandardInput.WriteLine(payload);
                }
                catch (Exception e)
                {
                    XuaLogger.AutoTranslator.Error(e, $"An error occurred while sending configuration to external process for '{GetType().Name}'.");
                }
            }
        }
Exemple #4
0
        public override async Task AddAsync(ConfigurationMessage message, CancellationToken cancellationToken = default)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }
            object[] sqlParams =
            {
                new NpgsqlParameter("@Id",          message.Id),
                new NpgsqlParameter("@Key",         message.Key),
                new NpgsqlParameter("@Value",       message.Value),
                new NpgsqlParameter("@Description", message.Description),
                new NpgsqlParameter("@CreateTime",  message.CreateTime),
                new NpgsqlParameter("@UtcTime",     message.UtcTime)
            };

            var sql = $@"INSERT INTO {GetTableName()} (Id,Key,Value,Description,CreateTime,UtcTime) 
VALUES (@Id,@Key,@Value,@Description,@CreateTime,@UtcTime);";

            using (var connection = new NpgsqlConnection(_source.DbConnectionStr))
                connection.ExecuteNonQuery(sql, sqlParams);

            Events.Enqueue(new Event(EventType.Add, message.Key, message.Value));
            await Task.CompletedTask;
        }
        protected override async Task OnInitializedAsync()
        {
            try
            {
                await _user.ConnectAsync(new Uri(@"ws://localhost:5001/ws"));
            }
            catch (Exception)
            {
                return;
            }

            await _user.SendAsync(new InitialMessage());

            ConfigurationMessage msg = new ConfigurationMessage();

            msg.AddBinding(1, typeof(NotificatorControllerEvent));
            await _user.SendAsync(msg);

            await _user.SendAsync(new NotificatorControllerEvent("notifcator", "non", 1));

            while (_user.IsConnected)
            {
                HandleMessage(await _user.ReceiveAsync());
            }
        }
Exemple #6
0
        private async Task HandleMessage(InfoControllerEvent info, ClientManager <MyPlayer> manager)
        {
            if (info.Event is NotificatorControllerEvent)
            {
                manager.GetClient(info.Sender).Entity = EntityType.Watcher;

                await manager.GetClient(info.Sender).SendAsync(new InitialMessage());

                ConfigurationMessage message = new ConfigurationMessage();
                message.AddBinding(1, typeof(NotificatorControllerEvent));
                await manager.GetClient(info.Sender).SendAsync(message);

                return;
            }

            if (info.Event is TextBoxControllerEvent textBox)
            {
                manager.GetClient(info.Sender).Name   = textBox.Text;
                manager.GetClient(info.Sender).Entity = EntityType.Player;
                return;
            }

            if (info.Event is ButtonControllerEvent button)
            {
                var send = MakeMessage(info, manager);

                foreach (var client in manager.Players)
                {
                    if (client.Value.Entity == EntityType.Watcher)
                    {
                        await manager.SendAsync(client.Key, send);
                    }
                }
            }
        }
Exemple #7
0
        public void SendConfigurationMessage(Slave slave, ConfigurationMessage configurationMessage)
        {
            var startAddress = GetStartAddress(slave.DeviceNumber, 12);
            var valueConfigurationMessage = GetValueToConfigurationMessage(configurationMessage);

            _modbusSerial.WriteSingleRegister(slave.SlaveId, startAddress, valueConfigurationMessage);
        }
        private void AddElementMessage(ConfigurationMessage ce, Panel p, ref int y)
        {
            AddElementLabel(ce, p, ref y);
            Label c = new Label();

            c.Text        = ce.Message;
            c.BorderStyle = BorderStyle.FixedSingle;
            c.MaximumSize = new Size(p.ClientSize.Width - 28, int.MaxValue);
            c.MinimumSize = new Size(c.MaximumSize.Width, 0);
            c.Left        = 14;
            c.AutoSize    = true;
            FinishElement(c, ce, p, ref y);
            switch (ce.Type)
            {
            case ConfigurationMessage.MessageType.ERROR:
                c.BackColor = Color.FromArgb(255, 200, 200);
                break;

            case ConfigurationMessage.MessageType.INFO:
                c.BackColor = Color.FromArgb(255, 255, 255);
                break;

            case ConfigurationMessage.MessageType.WARNING:
                c.BackColor = Color.PaleGoldenrod;
                break;
            }
        }
Exemple #9
0
        private static ushort GetValueToConfigurationMessage(ConfigurationMessage configurationMessage)
        {
            ushort value = 0;

            value += (ushort)configurationMessage.TresholdAndHysteresis;
            value += (ushort)(configurationMessage.BaselineFilter << 3);
            value += (ushort)(configurationMessage.SampleRate << 5);
            value += (ushort)(configurationMessage.ReportRate << 8);
            value += (ushort)(configurationMessage.SampleCounter << 10);
            value += (ushort)(configurationMessage.LowPassFilter << 13);
            return(value);
        }
Exemple #10
0
        internal ClientConnection(ServerView father, TcpClient textTcp, String password, ArrayList name)
        {
            this._father = father;
            this._textTcp = textTcp;
            ChallengeMessage auth = new ChallengeMessage();
            auth.salt = new Random().Next().ToString();
            auth.sendMe(textTcp.GetStream()); //mando il sale
            ResponseChallengeMessage respo = ResponseChallengeMessage.recvMe(textTcp.GetStream());

            if (name.Contains(respo.username))
            {
                //connessione fallita
                ConfigurationMessage fail = new ConfigurationMessage("Nome utente già utilizzato");
                fail.sendMe(textTcp.GetStream());
                throw new ClientConnectionFail("Un client ha fornito un nome utente già utilizzato");
            }
            this._username = respo.username;
            if (Pds2Util.createPswMD5(password, auth.salt).Equals(respo.pswMd5))
            {
                //creo le connessioni per i socket clipboard e video
                IPAddress localadd = ((IPEndPoint)textTcp.Client.LocalEndPoint).Address;
                TcpListener lvideo = new TcpListener(localadd, 0);
                lvideo.Start();
                IAsyncResult videores = lvideo.BeginAcceptTcpClient(null, null);
                TcpListener lclip = new TcpListener(localadd, 0);
                lclip.Start();
                IAsyncResult clipres = lclip.BeginAcceptTcpClient(null, null);
                int porta_video = ((IPEndPoint)lvideo.LocalEndpoint).Port;
                int clip_video = ((IPEndPoint)lclip.LocalEndpoint).Port;
                new ConfigurationMessage(porta_video, clip_video, "Benvenuto")
                    .sendMe(textTcp.GetStream());
                _clipTcp = lclip.EndAcceptTcpClient(clipres);
                _videoTcp = lvideo.EndAcceptTcpClient(videores);
                //now the client is connected
                _textReceiver = new Thread(_receiveText);
                _textReceiver.IsBackground = true;
                _textReceiver.Start();
                _clipReceiver = new Thread(_receiveClipboard);
                _clipReceiver.IsBackground = true;
                _clipReceiver.Start();
            }
            else
            {
                //connessione fallita
                ConfigurationMessage fail = new ConfigurationMessage("password sbagliata");
                fail.sendMe(textTcp.GetStream());
                throw new ClientConnectionFail("Un client ha fornito una password sbagliata");
            }
        }
Exemple #11
0
        private byte[] CreateMultiDeviceConfigurationContent(ConfigurationMessage configurationMessage)
        {
            Content content             = new Content {
            };
            SyncMessage   syncMessage   = CreateSyncMessage();
            Configuration configuration = new Configuration();

            if (configurationMessage.ReadReceipts != null)
            {
                configuration.ReadReceipts = configurationMessage.ReadReceipts.Value;
            }

            syncMessage.Configuration = configuration;
            content.SyncMessage       = syncMessage;
            return(content.ToByteArray());
        }
        protected override async Task OnInitializedAsync()
        {
            try
            {
                await _user.ConnectAsync(new Uri(@"ws://localhost:5001/ws"));
            }
            catch (Exception)
            {
                return;
            }
            await _user.SendAsync(new InitialMessage());

            ConfigurationMessage msg = new ConfigurationMessage();

            msg.AddBinding(1, typeof(TextBoxControllerEvent));
            await _user.SendAsync(msg);
        }
Exemple #13
0
        public override async Task UpdateAsync(ConfigurationMessage message, CancellationToken cancellationToken = default)
        {
            object[] sqlParams =
            {
                new NpgsqlParameter("@Id",          message.Id),
                new NpgsqlParameter("@Key",         message.Key),
                new NpgsqlParameter("@Value",       message.Value),
                new NpgsqlParameter("@Description", message.Description)
            };
            var sql = $@"UPDATE {GetTableName()} 
SET Key=@Key,Value=@Value,Description=@Description
WHERE Id=@Id";

            using (var connection = new NpgsqlConnection(_source.DbConnectionStr))
                connection.ExecuteNonQuery(sql, sqlParams);

            Events.Enqueue(new Event(EventType.Update, message.Key, message.Value));
            await Task.CompletedTask;
        }
        private async Task OnNameChose(TextBoxControllerEvent @event)
        {
            isNameChose = true;
            StateHasChanged();

            while (!_user.IsConnected)
            {
                await Task.Delay(1000);
            }

            await _user.SendAsync(@event);

            ConfigurationMessage msg = new ConfigurationMessage();

            msg.AddBinding(1, typeof(ButtonControllerEvent));
            msg.AddBinding(2, typeof(ButtonControllerEvent));
            msg.AddBinding(3, typeof(ButtonControllerEvent));
            await _user.SendAsync(msg);
        }
        private byte[] CreateMultiDeviceConfigurationContent(ConfigurationMessage configuration)
        {
            Content content                    = new Content {
            };
            SyncMessage   syncMessage          = CreateSyncMessage();
            Configuration configurationMessage = new Configuration();

            if (configuration.ReadReceipts != null)
            {
                configurationMessage.ReadReceipts = configuration.ReadReceipts.Value;
            }

            if (configuration.UnidentifiedDeliveryIndicators is bool unidentifiedDeliveryIndicators)
            {
                configurationMessage.UnidentifiedDeliveryIndicators = unidentifiedDeliveryIndicators;
            }

            syncMessage.Configuration = configurationMessage;
            content.SyncMessage       = syncMessage;
            return(content.ToByteArray());
        }
        public void StartSessions()
        {
            if (tcpClients.Count == 0)
            {
                Console.WriteLine("No clients are connected.");
                return;
            }

            for (int i = 0; i < scenarios.sessions.Count; ++i)
            {
                SessionDescription session = scenarios.sessions[i];
                Console.WriteLine("Starting new session: Browser: " + session.browser + " Connection: " + session.connection + " Clients: " + session.clients + " PPS: " + session.pps + " Payload size (bytes): " + session.payloadSize + " Duration (seconds): " + session.duration);

                // Set up the configuration message for the clients
                int instancesPerClient = session.clients / tcpClients.Count;
                ConfigurationMessage msgObj = new ConfigurationMessage();
                msgObj.type = "start";
                msgObj.address = scenarios.connectionInfo.ipAddr + ":" + scenarios.connectionInfo.port;
                msgObj.session = session;

                // Start up NodeJS
                Console.WriteLine("Starting NodeJS");
                Process nodejsProcess = new Process();
                nodejsProcess.StartInfo.FileName = "nodejs";
                nodejsProcess.StartInfo.Arguments = "simulation.js ";
                nodejsProcess.StartInfo.Arguments += scenarios.connectionInfo.ipAddr + " ";

                switch (session.connection)
                {
                    case "websocket":
                        nodejsProcess.StartInfo.Arguments += "--disable-securewebsockets --disable-webrtc --disable-native ";
                        break;
                    case "securewebsocket":
                        nodejsProcess.StartInfo.Arguments += "--disable-websockets --disable-webrtc --disable-native";
                        break;
                    case "webrtc - reliable":
                    case "webrtc - unreliable":
                        nodejsProcess.StartInfo.Arguments += "--disable-securewebsockets --disable-websockets --disable-native ";
                        break;
                    case "unity - reliable":
                    case "unity - unreliable":
                        nodejsProcess.StartInfo.Arguments += "--disable-securewebsockets --disable-websockets --disable-webrtc ";
                        break;
                }

                // Check first whether the directories exist
                string dirPath = "Results/session_" + session.sessionNr.ToString() + "/" + session.browser;
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }

                nodejsProcess.StartInfo.Arguments += "--config " + scenariosFileName + " " + i.ToString();
                nodejsProcess.Start();

                // Start up WireShark
                if (session.wireshark && (session.simulationType == "interval"))
                {
                    int duration = session.duration + ((session.clients + 1) * 3) + 30;

                    Console.WriteLine("Starting Wireshark");
                    string wiresharkFilename = dirPath
                    + "/wireshark_server_"
                    + session.connection.Replace(" ", "") + "_"
                    + session.clients + "clients_"
                    + session.pps + "pps_"
                    + session.payloadSize + "bytes_"
                    + session.duration + "seconds.pcapng";
                    wiresharkProcess = new Process();
                    wiresharkProcess.StartInfo.FileName = "tshark";
                    wiresharkProcess.StartInfo.Arguments = "-i 1 -a duration:" + duration + " -w " + wiresharkFilename;
                    wiresharkProcess.Start();
                }

                // Send the configuration to the clients
                Console.WriteLine("Sending settings to clients");
                string msg = JsonConvert.SerializeObject(msgObj);
                foreach (TcpClient tcpClient in tcpClients)
                {
                    byte[] binary = Encoding.UTF8.GetBytes(msg);
                    tcpClient.GetStream().BeginWrite(binary, 0, binary.Length, new AsyncCallback(EndSending), tcpClient);
                }

                // Sleep for a while
                if (wiresharkProcess != null)
                {
                    Thread.Sleep((session.duration + ((session.clients + 1) * 3) + 45) * 1000);
                }
                else
                {
                    UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11001));
                    IPEndPoint nodejsEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11002);
                    udpClient.Receive(ref nodejsEndPoint);
                    Console.WriteLine("Received closing signal from Node js.");
                }

                // Kill the external processes
                Console.WriteLine("Closing NodeJS");
                nodejsProcess.CloseMainWindow();
                nodejsProcess.Close();

                if (wiresharkProcess != null)
                {
                    Console.WriteLine("closing Wireshark");
                    wiresharkProcess.Close();
                    wiresharkProcess = null;
                }

                // Let the clients know they need to close off the browsers
                Console.WriteLine("Stopping client");
                msgObj = new ConfigurationMessage();
                msgObj.type = "stop";
                msgObj.session = session;

                msg = JsonConvert.SerializeObject(msgObj);
                foreach (TcpClient tcpClient in tcpClients)
                {
                    byte[] binary = Encoding.UTF8.GetBytes(msg);
                    tcpClient.GetStream().BeginWrite(binary, 0, binary.Length, new AsyncCallback(EndSending), tcpClient);
                }

                // Sleep for a while to give the clients some time
                Thread.Sleep(5000);
            }
        }