public async Task <ConnectionCode> CreateGame(Player player, ImmutableArray <Ship> ships) { var completionSource = new TaskCompletionSource <ConnectionCode>(); IDisposable subscription = null; subscription = _socket.MessageReceived.Subscribe(msg => { var connectionResult = _serializer.DeserializeDynamic(msg.Text); switch ((string)connectionResult["message_type"]) { case "connection_code": var connectionCode = _serializer.DeserializeObject <ConnectionCode>(connectionResult); completionSource.SetResult(connectionCode); break; case "game_connected": var result = _serializer.DeserializeObject <ConnectionToGameResult>(connectionResult); subscription.Dispose(); _reconnectSubscription.Dispose(); GameCreated?.Invoke(this, new(_socket, result.Go, result.Enemy)); break; default: throw new("Unexpected message type"); } }); await Connect(); var message = new CreateGameMessage(new(player, ships, null)); var text = _serializer.Serialize(message); _socket.Send(text); return(await completionSource.Task); }
private void GetEnemyShot(ResponseMessage msg) { if (IsPlayerGoing) { return; } var result = _serializer.DeserializeDynamic(msg.Text); switch ((string)result["message_type"]) { case "get_enemy_shot": var enemyShot = _serializer.DeserializeObject <GetEnemyShot>(result); OnGetEnemyShot?.Invoke(this, new(enemyShot)); break; case "get_enemy_answer": var enemyAnswer = _serializer.DeserializeObject <GetEnemyAnswer>(result); OnGetEnemyAnswer?.Invoke(this, new(enemyAnswer)); break; case "player_turn": IsPlayerGoing = true; OnPlayerTurn?.Invoke(this, EventArgs.Empty); break; default: throw new("Unexpected message type"); } }
public async Task <FcmMessageResponse> SendAsync(FcmMessage message, CancellationToken cancellationToken = default(CancellationToken)) { if (message == null) { throw new ArgumentNullException("message"); } string url = $"https://fcm.googleapis.com/v1/projects/{settings.Project}/messages:send"; // Construct the HTTP Message: HttpRequestMessageBuilder httpRequestMessageBuilder = new HttpRequestMessageBuilder(url, HttpMethod.Post) .SetStringContent(serializer.SerializeObject(message), Encoding.UTF8, MediaTypeNames.ApplicationJson); try { return(await httpClient.SendAsync <FcmMessageResponse>(httpRequestMessageBuilder, cancellationToken).ConfigureAwait(false)); } catch (FcmHttpException exception) { // Get the Original HTTP Response: var response = exception.HttpResponseMessage; // Read the Content: var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // Parse the Error: var error = serializer.DeserializeObject <FcmMessageErrorResponse>(content); // Throw the Exception: throw new FcmMessageException(error, content); } }
public async Task <TResponseType> SendAsync <TResponseType>(HttpRequestMessageBuilder builder, HttpCompletionOption completionOption, CancellationToken cancellationToken) { // Add Authorization Header: var accessToken = await CreateAccessTokenAsync(cancellationToken).ConfigureAwait(false); builder.AddHeader("Authorization", $"Bearer {accessToken}"); // Build the Request Message: var httpRequestMessage = builder.Build(); // Invoke actions before the Request: OnBeforeRequest(httpRequestMessage); // Invoke the Request: HttpResponseMessage httpResponseMessage = await client .SendAsync(httpRequestMessage, completionOption, cancellationToken) .ConfigureAwait(false); // Invoke actions after the Request: OnAfterResponse(httpRequestMessage, httpResponseMessage); // Apply the Response Interceptors: EvaluateResponse(httpResponseMessage); // Now read the Response Content as String: string httpResponseContentAsString = await httpResponseMessage.Content .ReadAsStringAsync() .ConfigureAwait(false); // And finally return the Object: return(serializer.DeserializeObject <TResponseType>(httpResponseContentAsString)); }
public T Get <T>(string key, T defaultValue = default(T)) { var query = @"select s.Value from Setting s where s.Key = @Key"; var result = _connection.Query <string>(query, new { Key = key }).FirstOrDefault(); if (result == null) { return(defaultValue); } return(_jsonSerializer.DeserializeObject <T>(result)); }
/// <summary> /// Mock de "Execute" con un body JSON y callback utilizando objetos (la de/serialización JSON se hace behind-the-scenes) /// </summary> public IRestClientExecuterMock ExecuteWithJsonContentMock <TRequestBody>(IJsonSerializer jsonConverter, Func <RestClientMockRequest <TRequestBody>, RestClientMockResponse> callback) { Setup(m => m.Execute(It.IsAny <Uri>(), It.IsAny <IRestRequest>())).Returns((Uri host, IRestRequest req) => { //Se crea el request del mock var mockReq = new RestClientMockRequest <TRequestBody>() { Host = host, Method = req.Method, Resource = req.Resource, Body = req.Body.Select(b => jsonConverter.DeserializeObject <TRequestBody>(b.Content)) }; //Se aplica la funcion var mockRes = callback(mockReq); //Se crea la respuesta final var res = new RestResponse() { ContentType = "application/json", StatusCode = mockRes.StatusCode, }; //Se setea el contenido solamente si viene if (mockReq.Body.HasValue) { res.Content = jsonConverter.SerializeObject(mockReq.Body.Value); } return(res); }); return(this); }
public async Task <TResponseType> PostAsync <TRequestType, TResponseType>(TRequestType request, HttpCompletionOption completionOption, CancellationToken cancellationToken) { // Now build the HTTP Request Message: HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, settings.FcmUrl); // Build the Content of the Request: StringContent content = new StringContent(serializer.SerializeObject(request), Encoding.UTF8, MediaTypeNames.ApplicationJson); // Append it to the Request: httpRequestMessage.Content = content; // Add the Authorization Header with the API Key: AddAuthorizationHeader(httpRequestMessage); // Invoke actions before the Request: OnBeforeRequest(httpRequestMessage); // Invoke the Request: HttpResponseMessage httpResponseMessage = await client.SendAsync(httpRequestMessage, completionOption, cancellationToken); // Invoke actions after the Request: OnAfterResponse(httpRequestMessage, httpResponseMessage); // Evaluate the Response: EvaluateResponse(httpResponseMessage); // Now read the Response Content as String: string httpResponseContentAsString = await httpResponseMessage.Content.ReadAsStringAsync(); // And finally return the Object: return(serializer.DeserializeObject <TResponseType>(httpResponseContentAsString)); }
public object[] Resolve(object requestParameters, IParameter[] targetParameters) { // Convert to array var parameters = ((IEnumerable)requestParameters).Cast <object>().ToArray(); // If length does not match, throw. if (parameters.Length != targetParameters.Length) { throw new ParameterLengthMismatchException(); } var result = new List <object>(); // Loop through and parse parameters for (var i = 0; i < parameters.Length; i++) { var request = parameters[i]; var target = targetParameters[i]; // If the target parameter is `object`, do not try to convert it. if (target.ParameterType == typeof(object)) { result.Add(request); } else { var serialized = _serializer.SerializeObject(request); var converted = _serializer.DeserializeObject(serialized, target.ParameterType); result.Add(converted); } } return(result.ToArray()); }
public T Get <T>(string key) where T : class { string redisValue = Db.StringGet(key); if (!string.IsNullOrEmpty(redisValue)) { return(_jsonSerializer.DeserializeObject <T>(redisValue)); } return(null); }
public JsonRpcRequest Parse(string json) { var request = _serializer.DeserializeObject <IDictionary <string, object> >(json); // Validate protocol version if (!request.ContainsKey("jsonrpc") || request["jsonrpc"].GetType() != typeof(string) || request["jsonrpc"].ToString() != "2.0") { throw new InvalidRequestException("Invalid protocol version."); } // Validate method if (!request.ContainsKey("method") || request["method"].GetType() != typeof(string)) { throw new InvalidRequestException("Invalid method name."); } // Validate id if (!(request.ContainsKey("id") && request["id"] != null) || !(request["id"] is int || request["id"] is long || request["id"] is string)) { throw new InvalidRequestException("Invalid id."); } var rpcRequest = new JsonRpcRequest { Id = request["id"], MethodName = request["method"].ToString(), ProtocolVersion = request["jsonrpc"].ToString() }; if (request.ContainsKey("params")) { rpcRequest.Parameters = request["params"]; } return(rpcRequest); }
private async Task <AsyncResult <T> > SendRequest <T>(HttpRequestMessage message) { try { var response = await _httpClient.SendAsync(message).ConfigureAwait(false); if (response.IsSuccessStatusCode) { return(new AsyncResult <T>(true, _serializer.DeserializeObject <T>(await response.Content.ReadAsStringAsync()))); } // hand 404's, 500's, etc return(new AsyncResult <T>(false)); } catch (Exception ex) { _logger.Warn($"An unexpected exception occurred making http request, error details - '{ex.Message}'", ex); return(new AsyncResult <T>(false)); } }
public object[] Resolve(object requestParameters, IParameter[] targetParameters) { var parameters = (IDictionary <string, object>)requestParameters; // If length does not match, throw. if (parameters.Keys.Count != targetParameters.Length) { throw new ParameterLengthMismatchException(); } var result = new List <object>(); // Loop through all keys and check if we have the parameter. foreach (var pair in parameters) { // Find the target parameter with a name equal to the one in the request var target = targetParameters.SingleOrDefault(tp => string.Equals(pair.Key, (string)tp.Name)); // We did not find a parameter with this name, throw. if (target == null) { throw new ParameterNameNotFoundException(); } if (target.ParameterType == typeof(object)) { result.Add(pair.Value); } else { var serialized = _serializer.SerializeObject(pair.Value); var converted = _serializer.DeserializeObject(serialized, target.ParameterType); result.Add(converted); } } return(result.ToArray()); }
public async Task <bool> Authenticate() { var uri = new Uri(Constants.AUTHENTICATIONSERVICE_URL); var body = new { userNameOrEmail = Constants.RESTSERVICE_USERNAME, password = Constants.RESTSERVICE_PASSWORD }; var json = jsonSerializer.SerializeObject(body); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync(uri, content); IEnumerable <Cookie> responseCookies = cookieContainer.GetCookies(uri).Cast <Cookie>(); var resultJson = await response.Content.ReadAsStringAsync(); var authenticationResult = jsonSerializer.DeserializeObject <AuthenticationWebserviceResult>(resultJson).D; if (authenticationResult != AuthenticationResult.Succeeded) { logger.Error($"RestClient authentication failed! AuthenticationResult: {authenticationResult}"); } return(authenticationResult == AuthenticationResult.Succeeded); }
public void Consume(Func <T, ulong, string, Task> onMessage) { try { if (!_connected) { _connection = _connectionFactory.CreateConnection(_consumerConfig.Name, _cancellationToken); _channel = _connection.CreateModel(); _channel.BasicQos(0, _queueConfiguration.MessagePrefetchCount, false); var consumer = new EventingBasicConsumer(_channel); consumer.Received += async(model, ea) => { var body = ea.Body; var deliveryTag = ea.DeliveryTag; var routingKey = ea.RoutingKey; try { var message = _serializer.DeserializeObject <T>(Encoding.UTF8.GetString(body)); _logger.Info($"Received message"); if (AcknowledgementBehaviour == AcknowledgementBehaviour.PreProcess) { _channel.BasicAck(deliveryTag, false); } await onMessage(message, deliveryTag, routingKey); _channel.BasicAck(deliveryTag, false); } catch (AlreadyClosedException ex) { _logger.Warn($"The connection to Rabbit was closed while processing message with deliveryTag '{deliveryTag}', error details - '{ex.Message}'."); } catch (Exception ex) { _logger.Warn($"An Exception occurred processing message with deliveryTag '{deliveryTag}', error details - '{ex.Message}'."); _channel.BasicNack(deliveryTag, false, false); } }; var dynamicQueue = $"{Resources.DynamicQueuePrefix}_{Guid.NewGuid().ToString()}"; // if the queue is not specified in the config then create a dynamic queue and bind to the exchange if (string.IsNullOrEmpty(_consumerConfig.QueueName)) { var queueDeclareResult = _channel.QueueDeclare(dynamicQueue, true, true, true, null); if (queueDeclareResult == null) { // TODO handle this result correctly } _channel.QueueBind(dynamicQueue, _consumerConfig.ExchangeName, _consumerConfig.RoutingKey); } _channel.BasicConsume(queue: !string.IsNullOrEmpty(_consumerConfig.QueueName) ? _consumerConfig.QueueName : dynamicQueue, autoAck: false, consumer: consumer); lock (_lock) { _connected = true; } } } catch (Exception ex) { _logger.Error($"An unexpected exception occurred, error details '{ex.Message}'", ex); lock (_lock) { _connected = false; } if (_channel != null) { _channel.Dispose(); } if (_connection != null) { _connection.Dispose(); } } }
private object ConvertPropertyValue(Type pType, string propertyName, string value) { Type type; var flag = IsTypeNullable(pType, out type); if (flag && string.IsNullOrEmpty(value)) { return(null); } object result; switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: if (string.IsNullOrEmpty(value)) { result = Activator.CreateInstance(type); return(result); } try { result = System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture); return(result); } catch (FormatException ex) { _logger.Error(ex); result = Activator.CreateInstance(type); return(result); } case TypeCode.DateTime: if (string.IsNullOrEmpty(value)) { result = DateTimeOffset.MinValue.DateTime; return(result); } result = _serializer.DeserializeObject <DateTimeOffset>("\"" + value + "\"").DateTime; return(result); case TypeCode.String: result = value; return(result); } throw new NotImplementedException(string.Format("Cannot populate fields of type {0} such as {1} on type {2}", type.FullName, propertyName, typeof(TDto).FullName)); }
/// <summary> /// public for testing - too lazy to show internals /// </summary> /// <param name="pType"></param> /// <param name="propertyName"></param> /// <param name="value"></param> /// <returns></returns> public object ConvertPropertyValue(Type pType, string propertyName, string value) { object convertedValue; Type propertyType; bool isNullable = IsTypeNullable(pType, out propertyType); if (isNullable && string.IsNullOrEmpty(value)) { convertedValue = null; } else { switch (Type.GetTypeCode(propertyType)) { case TypeCode.String: convertedValue = value; break; case TypeCode.DateTime: // Why are we converting from DateTimeOffset to DateTime? // and should we be checking for DateTimeOffset as a property type? if (string.IsNullOrEmpty(value)) { // not nullable but json is null - cannot throw because lightstreamer likes to send null updates // and DTO members are not alwasys nullable convertedValue = DateTimeOffset.MinValue.DateTime; } else { convertedValue = _serializer.DeserializeObject <DateTimeOffset>("\"" + value + "\"").DateTime; } break; case TypeCode.Boolean: case TypeCode.Byte: case TypeCode.Char: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: if (string.IsNullOrEmpty(value)) { // get a default value convertedValue = Activator.CreateInstance(propertyType); } else { try { convertedValue = System.Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture); } catch (FormatException formatException) { Log.Error(formatException); // get a default value convertedValue = Activator.CreateInstance(propertyType); } } break; case TypeCode.Empty: case TypeCode.Object: case TypeCode.DBNull: default: throw new NotImplementedException(string.Format("Cannot populate fields of type {0} such as {1} on type {2}", propertyType.FullName, propertyName, typeof(TDto).FullName)); } } return(convertedValue); }