Пример #1
0
        public async Task GetTagById_WithValidData_ShouldReturnCorrectValues()
        {
            // arrange
            const int id = 188527;
            var       expectedRequestUri = new Uri("/api/client-tags/188527", UriKind.Relative);
            var       httpResponse       = "{\"client-tag\":{\"id\":\"188527\",\"name\":\"Testag\",\"client_id\":\"796650\",\"customfield\":\"\"}}";
            var       expected           = new ClientTag
            {
                Id       = id,
                Name     = "Testag",
                ClientId = 796650
            };

            var http = A.Fake <IHttpClient>();

            A.CallTo(() => http.GetAsync(expectedRequestUri, A <CancellationToken> .Ignored))
            .Returns(Task.FromResult(httpResponse));

            var sut = GetSystemUnderTest(http);

            // act and assert
            var result = await sut.GetTagById(id);

            A.CallTo(() => http.GetAsync(expectedRequestUri, A <CancellationToken> .Ignored))
            .MustHaveHappenedOnceExactly();

            //result.Should().BeEquivalentTo(expected, new ClientTagEqualityComparer());
        }
Пример #2
0
        public async Task <bool> Update(ClientTag clienTag)
        {
            var currentclient = await GetById(clienTag.ClientTag_Id);

            currentclient.Client_Id = clienTag.Client_Id;
            currentclient.Tag_Id    = clienTag.Tag_Id;

            int rows = await _context.SaveChangesAsync();

            return(rows > 0);
        }
        public async Task CreateTagAsyncWhenNotAuthorized()
        {
            Configuration.ApiKey = "ajfkjeinodafkejlkdsjklj";

            var tag = new ClientTag
            {
                ClientId = 796659,
                Name     = "Testag"
            };

            await Assert.ThrowsAsync <NotAuthorizedException>(() => SystemUnderTest.CreateAsync(tag));
        }
        public async Task CreateTagAsync()
        {
            var tag = new ClientTag
            {
                ClientId = 796659,
                Name     = "Testag"
            };

            var result = await SystemUnderTest.CreateAsync(tag);

            Assert.NotNull(result);
            //await SystemUnderTest.DeleteTagAsync(result.Id);
        }
Пример #5
0
        public static Response AddStop(string clientId, string direction)
        {
            var clientState  = GetClientState(clientId);
            var directionUrl = (direction == "1" || direction == "первое")
                ? clientState.BufferDirections.First().Value
                : clientState.BufferDirections.Last().Value;
            var stopLink = Parser.GetStop(directionUrl, clientState.BufferStopName);

            if (stopLink == null)
            {
                return(ReturnDefaultState(clientId, "Я не смогла найти остановку с таким названием по указанному вами маршруту."));
            }
            var  stopUri = new Uri(stopLink);
            var  stopId  = HttpUtility.ParseQueryString(stopUri.Query).Get("st_id");
            Stop stop;

            using (ClientDataContext db = new ClientDataContext())
            {
                stop = db.Stops.Where(s => s.Id == stopId).FirstOrDefault();
                if (stop == null)
                {
                    stop = new Stop(stopId, clientState.BufferStopName, stopLink);
                    db.Stops.Add(stop);
                }
                if (GetClientTag(clientId, clientState.BufferTagName) != null)
                {
                    return(ReturnDefaultState(clientId, $"У вас уже есть такая остановка с тэгом {clientState.BufferTagName}"));
                }

                var clientTag = new ClientTag(clientId, clientState.BufferTagName, stopId);
                clientTag.Routes.Add(clientState.BufferRouteName);
                db.ClientTags.Add(clientTag);
                ReturnDefaultState(clientId, null);
                db.SaveChanges();
            }
            var timeIntervals = Parser.GetTime(stop, new List <string> {
                clientState.BufferRouteName
            });
            string result = $"Я добавила эту остановку по тегу {clientState.BufferTagName}. " +
                            "А вот и заодно время прибытия транспорта:\n";

            result += $"{string.Join("\n", timeIntervals[clientState.BufferRouteName])}";
            return(new Response($"{result}\n"));
        }
Пример #6
0
        /// <summary>
        /// Handles when a player has joined this server
        /// </summary>
        /// <param name="clientTag">The client's tag</param>
        /// <param name="connection">The connection for the new client</param>
        private void PlayerJoined(ClientTag clientTag, NetConnection connection)
        {
            // Get the ID of the new player
            int id = myPlayers.GetNextAvailableId();

            // Check to see if the server is full
            if (id != -1)
            {
                // Create the serverside player isntance
                Player player = new Player(clientTag, connection, (byte)id);

                player.OnCardAddedToHand     += PlayerGainedCard;
                player.OnCardRemovedFromHand += PlayerRemovedCard;

                // If this is the first player, they are immediately the host
                if (id == 0)
                {
                    myGameHost    = player;
                    player.IsHost = true;
                    Log("Setting host to \"{0}\"", player.Name);
                }

                // Client can connect
                connection.Approve();

                // Notify other players
                NotifyPlayerJoined(player);

                // Add the player to the player list
                myPlayers[player.PlayerId] = player;

                // Update the tag
                myTag.PlayerCount = myPlayers.PlayerCount;
            }
            else
            {
                // Deny the connection
                connection.Deny("Server is full");
            }
        }
Пример #7
0
        async private void UpdateClients()
        {
            if (!socket.Connected)
            {
                UpdateConnectionState(false);
                return;
            }
            string str = await socket.SendCommand("GetConfig");

            if (str == "")
            {
                UpdateConnectionState(false);
                return;
            }
            logText.Text = str.Replace("\n", "\r\n");

            var configs = ParsePacket(str);

            if (configs["Connected"] == "1")
            {
                // Connected
                UpdateConnectionState(true, configs["ClientName"] + " " + configs["Client"] + " " + configs["RefreshRate"]);

                connectedLabel.Text = "Connected!\r\n\r\n" + configs["ClientName"] + "\r\n"
                                      + configs["Client"] + "\r\n" + configs["RefreshRate"] + " FPS";

                autoConnectCheckBox.CheckedChanged -= autoConnectCheckBox_CheckedChanged;
                autoConnectCheckBox.Checked         = clientList.InAutoConnectList(configs["ClientName"], configs["Client"]);
                autoConnectCheckBox.CheckedChanged += autoConnectCheckBox_CheckedChanged;
                ShowConnectedPanel();

                UpdateClientStatistics();
                return;
            }
            UpdateConnectionState(false);
            ShowFindingPanel();

            var clients = clientList.ParseRequests(await socket.SendCommand("GetRequests"));

            foreach (var row in dataGridView1.Rows.Cast <DataGridViewRow>())
            {
                // Mark as old data
                ((ClientTag)row.Tag).updated = false;
            }

            foreach (var client in clients)
            {
                DataGridViewRow found = null;
                foreach (var row in dataGridView1.Rows.Cast <DataGridViewRow>())
                {
                    ClientTag tag1 = ((ClientTag)row.Tag);
                    if (tag1.client.Equals(client))
                    {
                        found        = row;
                        tag1.client  = client;
                        tag1.updated = true;
                    }
                }
                if (found == null)
                {
                    int index = dataGridView1.Rows.Add();
                    found = dataGridView1.Rows[index];
                    ClientTag tag2 = new ClientTag();
                    found.Tag    = tag2;
                    tag2.client  = client;
                    tag2.updated = true;
                }

                Color color = Color.Black;
                if (!client.Online)
                {
                    color = Color.DarkGray;
                }
                found.Cells[0].Style.ForeColor          = color;
                found.Cells[0].Style.SelectionForeColor = color;
                found.Cells[1].Style.ForeColor          = color;
                found.Cells[1].Style.SelectionForeColor = color;
                found.Cells[2].Style.ForeColor          = color;
                found.Cells[2].Style.SelectionForeColor = color;

                found.Cells[0].Value = client.Name;
                found.Cells[1].Value = client.Address;
                found.Cells[2].Value = client.Online ? (client.RefreshRate + " FPS") : "Offline";

                string buttonLabel = "Connect";
                if (!client.Online)
                {
                    buttonLabel = "Remove";
                }
                else if (!client.VersionOk)
                {
                    buttonLabel = "Wrong version";
                }

                if ((string)found.Cells[3].Value != buttonLabel)
                {
                    found.Cells[3].Value = buttonLabel;
                }
            }
            for (int j = dataGridView1.Rows.Count - 1; j >= 0; j--)
            {
                // Remove old row
                ClientTag tag3 = ((ClientTag)dataGridView1.Rows[j].Tag);
                if (!tag3.updated)
                {
                    dataGridView1.Rows.RemoveAt(j);
                }
            }
            noClientLabel.Visible = dataGridView1.Rows.Count == 0;

            var autoConnect = clientList.GetAutoConnectableClient();

            if (autoConnect != null)
            {
                await clientList.Connect(socket, autoConnect);
            }
        }
Пример #8
0
        private void UpdateClients()
        {
            clientList.Refresh();

            foreach (var row in dataGridView1.Rows.Cast <DataGridViewRow>())
            {
                // Mark as old data
                ((ClientTag)row.Tag).updated = false;
            }

            foreach (var client in clientList)
            {
                DataGridViewRow found = null;
                foreach (var row in dataGridView1.Rows.Cast <DataGridViewRow>())
                {
                    ClientTag tag1 = ((ClientTag)row.Tag);
                    if (tag1.client.Equals(client))
                    {
                        found        = row;
                        tag1.client  = client;
                        tag1.updated = true;
                    }
                }
                if (found == null)
                {
                    int index = dataGridView1.Rows.Add();
                    found = dataGridView1.Rows[index];
                    ClientTag tag2 = new ClientTag();
                    found.Tag    = tag2;
                    tag2.client  = client;
                    tag2.updated = true;
                }

                Color color = Color.Black;
                if (!client.Online)
                {
                    color = Color.DarkGray;
                }
                found.Cells[0].Style.ForeColor          = color;
                found.Cells[0].Style.SelectionForeColor = color;
                found.Cells[1].Style.ForeColor          = color;
                found.Cells[1].Style.SelectionForeColor = color;
                found.Cells[2].Style.ForeColor          = color;
                found.Cells[2].Style.SelectionForeColor = color;

                found.Cells[0].Value = client.DeviceName;
                found.Cells[1].Value = client.ClientAddr.ToString();
                found.Cells[2].Value = client.Online ? (client.RefreshRates[0] + " FPS") : "Offline";

                string buttonLabel = "Connect";
                if (!client.Online)
                {
                    buttonLabel = "Remove";
                }
                else if (client.Version != HelloListener.ALVR_PROTOCOL_VERSION)
                {
                    buttonLabel = "Wrong version";
                }

                if ((string)found.Cells[3].Value != buttonLabel)
                {
                    found.Cells[3].Value = buttonLabel;
                }
            }
            for (int j = dataGridView1.Rows.Count - 1; j >= 0; j--)
            {
                // Remove old row
                ClientTag tag3 = ((ClientTag)dataGridView1.Rows[j].Tag);
                if (!tag3.updated)
                {
                    dataGridView1.Rows.RemoveAt(j);
                }
            }
            noClientLabel.Visible = dataGridView1.Rows.Count == 0;

            var autoConnect = clientList.GetAutoConnectableClient();

            if (autoConnect != null)
            {
                Connect(autoConnect);
            }
        }
Пример #9
0
        /// <summary>
        /// Creates a new game client with the given client tag
        /// </summary>
        /// <param name="tag">The client tag for this game client</param>
        public GameClient(ClientTag tag)
        {
            myTag = tag;

            Initialize();
        }
Пример #10
0
        /// <summary>
        /// Handles when the server has received a message
        /// </summary>
        private void MessageReceived(object peer)
        {
            // Get the incoming message
            NetIncomingMessage inMsg = ((NetPeer)peer).ReadMessage();

            // We don't want the server to crash on one bad packet
            try
            {
                // Determine the message type to correctly handle it
                switch (inMsg.MessageType)
                {
                // Handle when a client's status has changed
                case NetIncomingMessageType.StatusChanged:
                    // Gets the status and reason
                    NetConnectionStatus status = (NetConnectionStatus)inMsg.ReadByte();
                    string reason = inMsg.ReadString();

                    // Depending on the status, we handle players joining or leaving
                    switch (status)
                    {
                    // A player has disconnected
                    case NetConnectionStatus.Disconnected:
                        PlayerLeft(myPlayers[inMsg.SenderConnection], reason);
                        break;

                    // A player is connecting
                    case NetConnectionStatus.Connected:
                        // Send the welcome packet
                        SendWelcomePacket(myPlayers[inMsg.SenderConnection].PlayerId);
                        break;
                    }

                    // Log the message
                    Log("Connection status updated for connection from {0}: {1}", inMsg.SenderEndPoint, status);

                    break;

                // Handle when a player is trying to join
                case NetIncomingMessageType.ConnectionApproval:

                    if (IsSinglePlayerMode & (inMsg.SenderEndPoint.Address.ToString() != myAddress.ToString() || myPlayers.Where(X => !X.IsBot).Count() > 0))
                    {
                        inMsg.SenderConnection.Deny("Server is in singleplayer mode");
                        break;
                    }


                    // Get the client's info an hashed password from the packet
                    ClientTag clientTag  = ClientTag.ReadFromPacket(inMsg);
                    string    hashedPass = inMsg.ReadString();

                    // Make sure we are in the lobby when joining new players
                    if (myState == ServerState.InLobby)
                    {
                        // Check the password if applicable
                        if ((myTag.PasswordProtected && myPassword.Equals(hashedPass)) | (!myTag.PasswordProtected))
                        {
                            // Check to see if the lobby is full
                            if (myPlayers.GetNextAvailableId() != -1)
                            {
                                // Go ahead and try to join that playa
                                PlayerJoined(clientTag, inMsg.SenderConnection);
                                Log("Player \"{0}\" joined from {1}", clientTag.Name, clientTag.Address);
                            }
                            else
                            {
                                // Deny connection if lobby is full
                                inMsg.SenderConnection.Deny("Game is full");
                                Log("Player \"{0}\" was denied access to full game from {1}", clientTag.Name, clientTag.Address);
                            }
                        }
                        else
                        {
                            // F**k you brah!
                            inMsg.SenderConnection.Deny("Password authentication failed");

                            Log("Player \"{0}\" failed to connect (password failed) from {1}", clientTag.Name, clientTag.Address);
                        }
                    }
                    else
                    {
                        // We are mid-way through a game
                        inMsg.SenderConnection.Deny("Game has already started");

                        Log("Player \"{0}\" attempted to connect mid game from {1}", clientTag.Name, clientTag.Address);
                    }
                    break;

                // Handle when the server has received a discovery request
                case NetIncomingMessageType.DiscoveryRequest:

                    // Make sure our tag is up to date
                    myTag.PlayerCount          = myPlayers.PlayerCount;
                    myTag.SupportedPlayerCount = myPlayers.Count;

                    if (!IsSinglePlayerMode && State == ServerState.InLobby)
                    {
                        // Prepare the response
                        NetOutgoingMessage msg = myServer.CreateMessage();
                        // Write the tag to the response
                        myTag.WriteToPacket(msg);
                        // Send the response
                        myServer.SendDiscoveryResponse(msg, inMsg.SenderEndPoint);

                        Log("Pinged discovery response to {0}", inMsg.SenderEndPoint);
                    }

                    break;

                // Handles when the server has received data
                case NetIncomingMessageType.Data:
                    HandleMessage(inMsg);
                    break;
                }
            }
            // An exception has occured parsing the packet
            catch (Exception e)
            {
                // Log the exception
                Log("Encountered exception parsing packet from {0}:\n\t{1}", inMsg.SenderEndPoint, e);
                Logger.Write(e);
            }

            PumpMessages();
        }
Пример #11
0
 public async Task Add(ClientTag clienTag)
 {
     _context.ClientTag.Add(clienTag);
     await _context.SaveChangesAsync();
 }
        public async Task CreateTagAsyncWhenArgumentException()
        {
            var tag = new ClientTag();

            await Assert.ThrowsAsync <ArgumentException>(() => SystemUnderTest.CreateAsync(tag));
        }
        public async Task <bool> Update(ClientTag clienTag)
        {
            await _clientTagRepository.Update(clienTag);

            return(true);
        }
 public async Task Add(ClientTag clienTag)
 {
     await _clientTagRepository.Add(clienTag);
 }