예제 #1
0
        public void ShouldCreateIClient(string name, string email)
        {
            IClient client = _clientFactory.Create(name, email);

            client.Name.Should().Be(name);
            client.Email.Should().Be(email);
        }
예제 #2
0
        public void Create_ShouldReturnNullWhenServiceEndpointIsNull()
        {
            ServiceEndpoint endpoint = null;
            var             result   = _clientFactory.Create(endpoint);

            result.Should().BeNull();
        }
예제 #3
0
        public async Task <decimal> GetBalance()
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var client = clientFactory.Create();

            return(await client.GetGrain <IAccount>(Int64.Parse(userId)).GetBalance());
        }
        public async Task <ServerInfo> Query(string host, int port, int timeout, CancellationTokenSource source)
        {
            logger.Status($"Reading DayZ server status at {host}:{port}");
            try
            {
                using (IClient client = clientFactory.Create(host, port))
                {
                    List <byte> request = new List <byte>(new byte[] { 0xff, 0xff, 0xff, 0xff, 0x54 });
                    request.AddRange(Encoding.UTF8.GetBytes("Source Engine Query"));
                    request.Add(0);

                    byte[] response = await client.Request(request.ToArray(), timeout, source);

                    ServerInfo info = ServerInfo.Parse(host, port, response);

                    logger.Status($"Finished reading DayZ server status at {host}:{port}");
                    return(info);
                }
            }
            catch (Exception e)
            {
                logger.Error("Error reading DayZ server status", e);
                return(null);
            }
        }
예제 #5
0
        public async Task Execute()
        {
            var totalDeletedUsers = 0;

            _logger.LogInformation("Get all users marked for deletion in database.");
            var purgedUserData = _userStorage.GetPurgedUsers().Result;

            _logger.LogInformation($"Total {purgedUserData.Count} user records are marked for deletion.");
            var purgedUsers = purgedUserData.GroupBy(x => new { x.SubscriptionId, x.AppApiKey, x.OwnerAccessKey, x.SigningKey });

            _logger.LogInformation("Initialize the dashboard client and, retrieve all the purged users.");

            foreach (var usersToDelete in from user in purgedUsers
                     let client = _clientFactory.Create(Convert.ToBoolean(Configuration["Settings.Sandbox"]), user.Key.AppApiKey, user.Key.SigningKey, user.Key.OwnerAccessKey)
                                  let purgedUsers = client.ListUsers(null, StatusFilter.Deleted)
                                                    select user.Where(x => !purgedUsers.Select(y => y.user_id.ToString()).Contains(x.UserId)).ToList() into usersToDelete
                                                    where usersToDelete.Count > 0
                                                    select usersToDelete)
            {
                await _userStorage.DeleteUsers(usersToDelete);

                totalDeletedUsers += usersToDelete.Count;

                _logger.LogInformation($" {usersToDelete.Count} users part of ({usersToDelete.First().SubscriptionId}) marked for clean up.");
            }

            _logger.LogInformation($"{totalDeletedUsers} users deleted sucessfully from the database.");
        }
예제 #6
0
        private void Accept(Socket socket)
        {
            IClient client = clientFactory.Create(socket);

            client.Start();
            clients.Add(client);
        }
예제 #7
0
        public async Task <SocialNetworkStatus> CreateStatusAsync(ClientType clientType)
        {
            IClient client      = _clientFactory.Create(clientType);
            string  termMessage = _termMessage.Compose();

            return(await client.CreateStatusAsync(termMessage));
        }
예제 #8
0
        public async Task <Server> FindDayZServerInRegion(
            string host, int port, byte region, int timeout, CancellationTokenSource source)
        {
            try
            {
                logger.Status($"Finding server {host}:{port} in master server list");
                using (IClient client = factory.Create(MASTER_SERVER_HOST, MASTER_SERVER_PORT))
                {
                    List <byte> request = new List <byte>(new byte[] { 0x31, region });
                    request.AddRange(Encoding.UTF8.GetBytes("0.0.0.0:0"));
                    request.Add(0);
                    request.AddRange(Encoding.UTF8.GetBytes(@"\game\DayZ\gameaddr\"));
                    request.AddRange(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", host, port)));
                    request.Add(0);

                    byte[] response = await client.Request(request.ToArray(), timeout, source);

                    MessageParser parser = new MessageParser(response);
                    _ = parser.GetBytes(6);
                    IPAddress ip        = parser.GetIPAddress();
                    int       queryPort = parser.GetPort();
                    if (ip.Equals(IPAddress.Any) && queryPort == 0)
                    {
                        return(null);
                    }
                    return(new Server(ip.ToString(), queryPort));
                }
            }
            catch (Exception e)
            {
                logger.Error("Error querying master server", e);
                return(null);
            }
        }
 public DiscoveryClientTests()
 {
     _config = Substitute.For <IClientConfig>();
     _config.ConsumerKey.Returns("K1uJLzJ5mdt3oBKNSzjcEEEzxHuJJXiX");
     _config.ApiRootUrl.Returns("https://app.ticketmaster.com/discovery/");
     _factory = new ClientFactory();
     _sut     = _factory.Create <DiscoveryApi>(_config);
 }
예제 #10
0
 public override Task Tell(byte[] wrapBytes, byte[] dataBytes, object data, MessageInfo msg)
 {
     if (data is IEventBase <long> evt)
     {
         return(clientFactory.Create().GetGrain <IAccountDb>(evt.StateId).ConcurrentTell(wrapBytes));
     }
     return(Task.CompletedTask);
 }
예제 #11
0
        public void Should_Create_Client()
        {
            var connectionUid = Guid.NewGuid();

            var client = ClientFactory.Create(connectionUid);

            Assert.AreEqual(client.ConnectionUid, connectionUid);
        }
예제 #12
0
파일: Server.cs 프로젝트: vitalyo7/Rasa.NET
 private void OnLogin(LoginClient client)
 {
     lock (Clients)
     {
         var newClient = _clientFactory.Create(client.Socket, client.Data, this);
         Clients.Add(newClient);
     }
 }
예제 #13
0
        public GameClient CreateClient()
        {
            var client = _ClientFactory.Create();

            _ClientList.RegisterClient(client);

            //return new ArenaClient().BaseClient; //new ScriptClient().BaseClient;
            return(client.BaseClient);
        }
예제 #14
0
        public IEnumerable <Restaurant> GetRestaurantsByOutcode(string outcode)
        {
            var client  = _clientFactory.Create();
            var request = _requestFactory.GetRestaurantRequestByOutcode(outcode);

            var response = client.Execute <RestaurantsRoot>(request);

            return(IsResponseCorrect(response) ? response.Data.Restaurants : new List <Restaurant>());
        }
예제 #15
0
 public async Task <TResult> CallAsync <TResult>(Func <T, Task <TResult> > method, params string[] endPointNames)
 {
     using (ILifetimeScope scope = container.BeginLifetimeScope())
     {
         IClientFactory <T> factory = scope.Resolve <IClientFactory <T> >();
         T client = factory.Create(endPointNames);
         return(await method(client));
     }
 }
예제 #16
0
 public void Call(Action <T> method, params string[] endPointNames)
 {
     using (ILifetimeScope scope = container.BeginLifetimeScope())
     {
         IClientFactory <T> factory = scope.Resolve <IClientFactory <T> >();
         T client = factory.Create(endPointNames);
         method(client);
     }
 }
예제 #17
0
        public async Task <IActionResult> Create([FromBody] ClientCredentialRequest client)
        {
            IActionResult result = null;

            try
            {
                if (result == null && client == null)
                {
                    result = BadRequest("Missing client data");
                }
                if (result == null && string.IsNullOrEmpty(client.Name))
                {
                    result = BadRequest("Missing client name value");
                }
                if (result == null && (!client.AccountId.HasValue || client.AccountId.Value.Equals(Guid.Empty)))
                {
                    result = BadRequest("Missing account id value");
                }
                if (result == null && !UserCanAccessAccount(client.AccountId.Value))
                {
                    result = StatusCode(StatusCodes.Status401Unauthorized);
                }
                if (result == null && string.IsNullOrEmpty(client.Secret))
                {
                    result = BadRequest("Missing secret value");
                }
                if (result == null && client.Secret.Trim().Length < 16)
                {
                    result = BadRequest("Client secret must be at least 16 characters in lenth");
                }
                if (result == null)
                {
                    using ILifetimeScope scope = _container.BeginLifetimeScope();
                    IClientFactory clientFactory = scope.Resolve <IClientFactory>();
                    IClient        innerClient   = await clientFactory.Create(client.AccountId.Value, client.Secret);

                    IMapper mapper = MapperConfigurationFactory.CreateMapper();
                    mapper.Map <Client, IClient>(client, innerClient);
                    SettingsFactory settingsFactory = scope.Resolve <SettingsFactory>();
                    CoreSettings    settings        = settingsFactory.CreateAccount(_settings.Value);
                    IClientSaver    saver           = scope.Resolve <IClientSaver>();
                    await saver.Create(settings, innerClient);

                    result = Ok(mapper.Map <Client>(innerClient));
                }
            }
            catch (Exception ex)
            {
                using (ILifetimeScope scope = _container.BeginLifetimeScope())
                {
                    await LogException(ex, scope.Resolve <IExceptionService>(), scope.Resolve <SettingsFactory>(), _settings.Value);
                }
                result = StatusCode(StatusCodes.Status500InternalServerError);
            }
            return(result);
        }
예제 #18
0
        public void Add(ClientSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            // cacheLock handled in Add(string, IClient)
            Add(settings.Name, _factory.Create(settings));
        }
        public async Task <IClient> Create(ClientCreateRequest request)
        {
            IClient client = _clientFactory.Create(request.Name, request.Email);

            _clientRepository.Create(client);

            await _unitOfWork.CommitAsync().ConfigureAwait(false);

            return(client);
        }
예제 #20
0
        public string Execute(string[] inputArgs)
        {
            string clientType = inputArgs[0];
            string username   = inputArgs[1];
            var    client     = _clientFactory.Create(clientType, username);

            _clientRepository.Add(client);

            string result = string.Format(SuccessfullyAddedMessage, username);

            return(result);
        }
        public async Task Events_SearchEventsAsync_ShouldReturnResult()
        {
            SearchEventsResponse result;

            using (var sut = _factory.Create <DiscoveryApi>(_config))
            {
                result = await sut.Events.SearchEventsAsync(new SearchEventsRequest());
            }

            Assert.NotNull(result);
            Assert.NotNull(result._embedded);
            Assert.NotEmpty(result._embedded.Events);
        }
        /// <summary>
        /// Adds a new client and starts to recieve his messages.
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public TClient AddClient(WebSocket socket)
        {
            var newClient = _clientFactory.Create(socket);

            lock (_playersLock)
            {
                Players.Add(newClient.Guid, newClient);
                _events.Add(newClient.ReceiveAsync());
                _src.Cancel();
            }

            return(newClient);
        }
예제 #23
0
        private HttpClient BuildNextClient()
        {
            HttpClient      nextClient = null;
            ServiceEndpoint test;

            if (AvailableEndpoints.TryPeek(out test) == false)
            {
                throw new NoAvailableServiceEndpointException();
            }

            nextClient = _clientFactory.Create(AvailableEndpoints.Pop());

            return(nextClient);
        }
예제 #24
0
        /// <summary>
        /// Gets the most popular toppings from the service
        /// </summary>
        /// <param name="rank">The rank.</param>
        /// <returns>A ranked list of the most popular toppings with a total</returns>
        public List <Rank> MostPopularToppings(int rank)
        {
            var client  = _client.Create();
            var request = _request.GetAllToppings();

            var pizzas = client
                         .Execute <List <Pizza> >(request)
                         .Data;

            return(pizzas
                   .SelectMany(pizza => pizza.Toppings)
                   .GroupBy(topping => topping)
                   .Select(topping => new Rank {
                Topping = topping.Key, Total = topping.Count()
            })
                   .OrderByDescending(topping => topping.Total)
                   .Take(rank)
                   .ToList());
        }
예제 #25
0
        public IRequest Create(string resource, HttpMethod method = HttpMethod.Get)
        {
            var client = _clientFactory.Create();

            switch (method)
            {
            case HttpMethod.Get:
                return(new Requiest(client, resource));

            case HttpMethod.Post:
                return(new Requiest(client, resource, Method.POST));

            case HttpMethod.Put:
                return(new Requiest(client, resource, Method.PUT));

            default:
                throw new Exception($"Unsupported HTTP method. Method='{method}'");
            }
        }
예제 #26
0
        public async Task Execute(string appApiKey, string ownerAccessKey, string signingKey, string subscriptionId)
        {
            var userRecords = new List <UserRecord>();

            _logger.LogInformation("Initialize the dashboard client and create users in Users Database.");

            var client = _clientFactory.Create(Convert.ToBoolean(Configuration["Settings.Sandbox"]), appApiKey,
                                               signingKey, ownerAccessKey);

            var activeUsers = client.ListUsers(null, StatusFilter.Active);

            if (activeUsers.Count <= 0)
            {
                _logger.LogInformation($"No active or suspended users exist for ({subscriptionId}).");
            }
            else
            {
                var activeUsersInDb = _userStorage.GetUsersBySubscriptionId(subscriptionId).Result;

                var usersToCreate = activeUsers.Where(u =>
                                                      !activeUsersInDb.Any(x =>
                                                                           x.UserId == u.user_id.ToString() && x.SubscriptionId.Equals(subscriptionId)))
                                    .ToList();

                if (usersToCreate.Count > 0)
                {
                    foreach (var user in usersToCreate)
                    {
                        userRecords.Add(new UserRecord
                        {
                            UserId = user.user_id.ToString(),
                            Email  = user.email,
                            Phone  = user.cellphone
                        });
                    }

                    await _userStorage.AddUsers(userRecords, subscriptionId);
                }

                _logger.LogInformation($" {usersToCreate.Count} users part of ({subscriptionId}) are created.");
            }
        }
예제 #27
0
        public async ValueTask RegisterConnectionAsync(IHazelConnection connection, string name, int clientVersion, ISet <Mod>?mods)
        {
            if (!SupportedVersions.Contains(clientVersion))
            {
                using var packet = MessageWriter.Get(MessageType.Reliable);
                Message01JoinGameS2C.SerializeError(packet, false, DisconnectReason.IncorrectVersion);
                await connection.SendAsync(packet);

                return;
            }

            if (name.Length > 10)
            {
                using var packet = MessageWriter.Get(MessageType.Reliable);
                Message01JoinGameS2C.SerializeError(packet, false, DisconnectReason.Custom, DisconnectMessages.UsernameLength);
                await connection.SendAsync(packet);

                return;
            }

            if (string.IsNullOrWhiteSpace(name) || !name.All(TextBox.IsCharAllowed))
            {
                using var packet = MessageWriter.Get(MessageType.Reliable);
                Message01JoinGameS2C.SerializeError(packet, false, DisconnectReason.Custom, DisconnectMessages.UsernameIllegalCharacters);
                await connection.SendAsync(packet);

                return;
            }

            var client = _clientFactory.Create(connection, name, clientVersion, mods ?? new HashSet <Mod>(0));
            var id     = NextId();

            client.Id = id;
            _logger.LogTrace("Client connected.");
            _clients.TryAdd(id, client);

            using var writer = MessageWriter.Get(MessageType.Reliable);
            ModdedHandshakeS2C.Serialize(writer, ServerBrand);
            await connection.SendAsync(writer);
        }
예제 #28
0
        public async ValueTask RegisterConnectionAsync(IHazelConnection connection, string name, int clientVersion)
        {
            if (!SupportedVersions.Contains(clientVersion))
            {
                using var packet = MessageWriter.Get(MessageType.Reliable);
                Message01JoinGameS2C.SerializeError(packet, false, DisconnectReason.IncorrectVersion);
                await connection.SendAsync(packet);

                return;
            }

            if (name.Length > 10)
            {
                using var packet = MessageWriter.Get(MessageType.Reliable);
                Message01JoinGameS2C.SerializeError(packet, false, DisconnectReason.Custom, DisconnectMessages.UsernameLength);
                await connection.SendAsync(packet);

                return;
            }

            if (string.IsNullOrWhiteSpace(name) || !name.All(TextBox.IsCharAllowed))
            {
                using var packet = MessageWriter.Get(MessageType.Reliable);
                Message01JoinGameS2C.SerializeError(packet, false, DisconnectReason.Custom, DisconnectMessages.UsernameIllegalCharacters);
                await connection.SendAsync(packet);

                return;
            }

            var client = _clientFactory.Create(connection, name, clientVersion);
            int id     = NextId();

            client.Id = id;
            _logger.LogTrace("Client connected.");
            _clients.TryAdd(id, client);

            await _eventManager.CallAsync(new ClientConnectedEvent(connection, client));
        }
예제 #29
0
        protected override Task SendToAsyncGrain(byte[] bytes, IEventBase <long> evt)
        {
            var client = clientFactory.Create();

            return(client.GetGrain <IAccountFlow>(evt.StateId).ConcurrentTell(bytes));
        }
예제 #30
0
        public IRequest Create(string resource, Method method, bool authenticate = true)
        {
            var client = _clientFactory.Create(authenticate);

            return(new Request(resource, method, client));
        }