Example #1
0
        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);
            }
        }
Example #2
0
        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 string GetSwaggerApiList()
        {
            var allApiControllers       = _swaggerDocumentationAssemblyTools.GetApiControllerTypes(typeof(TBaseApiControllerType));
            var pertinentApiControllers = _swaggerDocumentationAssemblyTools.GetTypesThatAreDecoratedWithApiDocumentationAttribute(allApiControllers);
            var swaggerContents         = _swaggerDocumentationCreator.GetSwaggerResourceList(pertinentApiControllers);

            return(_jsonSerializer.SerializeObject(swaggerContents));
        }
Example #4
0
        public bool SerializeObject(object value, System.Text.StringBuilder builder)
        {
            var text = _jsonSerializer.SerializeObject(value);

            if (text == null)
            {
                return(false);
            }
            builder.Append(text);
            return(true);
        }
Example #5
0
        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());
        }
Example #6
0
        /// <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);
        }
Example #7
0
        public void AndroidConfigSerializationDeserializationTest()
        {
            AndroidConfig config = new AndroidConfig()
            {
                CollapseKey = "collapse_key",
                Data        = new Dictionary <string, string>()
                {
                    { "A", "B" }
                },
                Priority     = AndroidMessagePriorityEnum.HIGH,
                Notification = new AndroidNotification()
                {
                    BodyLocArgs  = new[] { "1", "2" },
                    Body         = "body",
                    Color        = "color",
                    Tag          = "tag",
                    BodyLocKey   = "body_loc_key",
                    ClickAction  = "click_action",
                    Sound        = "sound",
                    Icon         = "icon",
                    Title        = "title",
                    TitleLocArgs = new [] { "3", "4" },
                    TitleLocKey  = "title_loc_key"
                },
                TimeToLive            = TimeSpan.FromSeconds(10),
                RestrictedPackageName = "restricted_package_name"
            };

            var result = serializer.SerializeObject(config);

            Assert.IsNotNull(result);
        }
Example #8
0
 private void CallPutRabbitMqApi(BrokerConfiguration cfg, string call, object body = null)
 {
     HTTPCall(cfg, () =>
     {
         var content = new StringContent(body != null ? _jsonSerializer.SerializeObject(body) : "", Encoding.UTF8, "application/json");
         return(_httpConnector.Put <string>(call, content));
     });
 }
Example #9
0
        public void SetMany(IDictionary <string, object> items)
        {
            if (items == null || !items.Any())
            {
                return;
            }

            var query = @"insert or replace into Setting(Key, Value) values(@Key, @Value);";
            var model = (from item in items
                         select new
            {
                item.Key,
                Value = _jsonSerializer.SerializeObject(item.Value)
            }).ToArray();

            _connection.Execute(query, model);
            _messageBus.Publish(new KeyValueChangedMessage(items.Keys.ToArray()));
        }
Example #10
0
        public void AddCar(Car car)
        {
            var stringBuilder   = new StringBuilder();
            var serializeObject = _jsonSerialize.SerializeObject(car);

            DbC.Require(() => serializeObject != null, "No se ha serializado");

            stringBuilder.Append(serializeObject);

            FileUtilities.CreateFolderIfNotExists(_path);

            File.AppendAllText(Path.Combine(_path, "data.txt"), stringBuilder.ToString());
            stringBuilder.Clear();
        }
Example #11
0
        public bool SendGroupMessage(string fromId, string groupId, string content)
        {
            var message   = new { username = "", id = groupId, type = "group", content = content, system = true };// ["username", "avatar", "id", "type", "content"]
            var json      = serializer.SerializeObject(message);
            var parameter = new Dictionary <string, object> {
                { "fromUserId", 0 },
                { "toGroupId", groupId },
                { "objectName", "LAYIM:CHAT" },
                { "content", json }
            };
            var result = Execute <RongCloudRequestResult>("/message/group/publish.json", Method.POST, parameter);

            return(result?.code == 200);
        }
Example #12
0
        private HttpRequestMessage ConfigureRequest <T>(HttpMethod httpMethod, string resourceUri, T request, string apiVersion)
        {
            var message = new HttpRequestMessage(httpMethod, resourceUri);

            // add api version header
            message.Headers.Add("X-Version", apiVersion);

            if (request != null)
            {
                var content = _serializer.SerializeObject(request);
                message.Content = new StringContent(content, Encoding.UTF8, "application/json");
            }

            return(message);
        }
Example #13
0
        public void Publish(T message, string routingKey = null)
        {
            // TODO connection persistence, stop lots of connections
            try
            {
                if (!_connected)
                {
                    _connection = _connectionFactory.CreateConnection(_publisherConfig.Name, _cancellationToken);

                    _channel = _connection.CreateModel();

                    lock (_lock)
                    {
                        _connected = true;
                    }
                }

                var body = Encoding.UTF8.GetBytes(_serializer.SerializeObject(message));

                _channel.BasicPublish(exchange: _publisherConfig.ExchangeName,
                                      routingKey: !string.IsNullOrEmpty(routingKey) ? routingKey : _publisherConfig.RoutingKey,
                                      basicProperties: null,
                                      body: body);
                _logger.Info($"Sent message");
            }
            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();
                }
            }
        }
Example #14
0
        public JsonRpcModule(IJsonSerializer jsonSerializer,
                             IJsonRpcRequestParser requestParser,
                             IRequestHandler requestHandler)
        {
            Post["/jsonrpc"] = _ =>
            {
                this.RequiresAuthentication();

                using (var ms = new MemoryStream())
                {
                    Request.Body.CopyTo(ms);

                    var json     = Encoding.UTF8.GetString(ms.ToArray());
                    var request  = requestParser.Parse(json);
                    var response = requestHandler.Handle(request);

                    return(Response.AsText(jsonSerializer.SerializeObject(response), "application/json"));
                }
            };
        }
Example #15
0
        public JsonRpcModule(IJsonSerializer jsonSerializer,
            IJsonRpcRequestParser requestParser,
            IRequestHandler requestHandler)
        {
            Post["/jsonrpc"] = _ =>
            {
                this.RequiresAuthentication();

                using (var ms = new MemoryStream())
                {
                    Request.Body.CopyTo(ms);

                    var json = Encoding.UTF8.GetString(ms.ToArray());
                    var request = requestParser.Parse(json);
                    var response = requestHandler.Handle(request);

                    return Response.AsText(jsonSerializer.SerializeObject(response), "application/json");
                }
            };
        }
Example #16
0
        public void ApnsConfigSerializationTest()
        {
            ApnsConfig config = new ApnsConfig()
            {
                Payload = new ApnsConfigPayload()
                {
                    Aps = new Aps()
                    {
                        Badge = "badge",
                        Alert = new ApsAlert()
                        {
                            TitleLocKey  = "title_loc_key",
                            ActionLocKey = "action_loc_key",
                            TitleLocArgs = new[] { "1", "2" },
                            Title        = "Title",
                            Body         = "Body",
                            LaunchImage  = "LaunchImage",
                            LocArgs      = new[] { "3", "4" },
                            LocKey       = "LocKey"
                        },
                        Category   = "category",
                        Sound      = "sound",
                        CustomData = new Dictionary <string, object>()
                        {
                            { "CustomKey1", "CustomValue1" }
                        },
                        ContentAvailable = true,
                        MutableContent   = true,
                        ThreadId         = "1"
                    },
                    CustomData = new Dictionary <string, object>()
                    {
                        { "CustomKey2", "CustomValue2" }
                    }
                }
            };

            string result = serializer.SerializeObject(config);

            Assert.IsNotNull(result);
        }
Example #17
0
        public string SerializeSubRequest(SubRequest request)
        {
            string requestBody = serializer.SerializeObject(request.Body);

            StringBuilder messagePayload = new StringBuilder()
                                           .Append($"POST {request.Url} HTTP/1.1\r\n")
                                           .Append($"Content-Length: {requestBody.Length}\r\n")
                                           .Append("Content-Type: application/json; charset=UTF-8\r\n");

            if (request.Headers != null)
            {
                foreach (var header in request.Headers)
                {
                    messagePayload.Append($"{header.Key}: {header.Value}\r\n");
                }
            }
            messagePayload.Append("\r\n");
            messagePayload.Append(requestBody);

            return(messagePayload.ToString());
        }
Example #18
0
        public void Mutate <TSourceType>(TSourceType source)
        {
            // Create a new Dgrapg Client:
            using (var client = Clients.NewDgraphClient())
            {
                // Connects to the DGraph Instance:
                client.Connect(settings.ConnectionString);

                using (var transaction = client.NewTransaction())
                {
                    // Serializes the Object(s) into JSON:
                    var json = serializer.SerializeObject(source);

                    // Mutate the Data:
                    transaction.Mutate(json);

                    // And finally try to commit the Transaction:
                    transaction.Commit();
                }
            }
        }
Example #19
0
        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());
        }
Example #20
0
        public override void BuildPayload()
        {
            string deviceIdString = SerialNumberValue;
            string rssiString     = RssiValue;
            string snrString      = SnrValue;
            string buttonStatus   = CommandTypeValue;
            double tempValue      = Convert.ToDouble(TempValue);
            double batValue       = Convert.ToDouble(BatValue);

            TelemetryModel model = new TelemetryModel()
            {
                deviceid      = deviceIdString,
                correlationId = Guid.NewGuid(),
                timestamp     = DateTime.Now,
                buttonStatus  = buttonStatus,
                batValue      = batValue,
                tempValue     = tempValue,
                rssi          = rssiString,
                snr           = snrString,
            };

            Message = _jsonSerializer.SerializeObject(model);
        }
    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);
    }
Example #22
0
        public void Add(string key, object o, DateTimeOffset expiration, string dependsOnKey = null)
        {
            var timeSpan = expiration.DateTime.Subtract(DateTime.Now);

            Db.StringSet(key, _jsonSerializer.SerializeObject(o), timeSpan);
        }
Example #23
0
        public void Publish(T message, IDictionary <string, object> headers, string dynamicRoutingKey)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            try
            {
                // Validate message
                string validationErrors;
                if (!_validationHelper.TryValidate(message, out validationErrors))
                {
                    throw new ValidationException(validationErrors);
                }

                // serialise object...
                string messageBody = _serializer.SerializeObject(message);

                // Determine routing key
                var routingKey = dynamicRoutingKey ?? _publisherConfig.RoutingKey;

                _logger.DebugFormat(Resources.PublishingMessageLogEntry, _publisherConfig.ExchangeName, routingKey, messageBody);

                lock (_lock)
                {
                    if (!_connected)
                    {
                        _connection = _connectionFactory.CreateConnection(_publisherConfig.Name, _cancellationToken);

                        _channel = _connection.CreateModel();

                        _connected = true;
                    }
                }

                // Create message properties
                var basicProperties = CreateBasicProperties(headers);

                _channel.BasicPublish(_publisherConfig.ExchangeName,
                                      routingKey,
                                      true,
                                      basicProperties,
                                      Encoding.UTF8.GetBytes(messageBody));

                _logger.Info($"Sent message");
            }
            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();
                }
            }
        }
Example #24
0
        public async Task <IActionResult> PostMqttOnDemandAsync()
        {
            IPHostEntry hostInfo = Dns.Resolve(Dns.GetHostName());

            TelemetryModel model = new TelemetryModel()
            {
                deviceid  = Guid.NewGuid().ToString(),
                timestamp = DateTime.Now,
                tempValue = 23.7,
                rssi      = "100",
                snr       = "5",
            };

            var onDemandMessageWasSent = await _awsIoTProcessor.OnDemandMessageAsync(_environment.WebRootPath, _jsonSerializer.SerializeObject(model));

            return(Ok(onDemandMessageWasSent));
        }
 public string SerializeObject(object obj)
 {
     return(_jsonSerializer.SerializeObject(obj));
 }