Пример #1
0
        public async Task PostAsJson_WithRequest()
        {
            var client = new HttpClientInstance("https://postman-echo.com/post");

            var request = BuildRequest();
            await client.PostAsync(request).ConfigureAwait(false);
        }
Пример #2
0
        private async Task Login()
        {
            try
            {
                HubConnection = new HubConnectionBuilder()
                                .WithUrl($"{BaseUrl}/chat", options =>
                {
                    var stringData = JsonConvert.SerializeObject(new { Email, Password });

                    options.AccessTokenProvider = async() =>
                    {
                        var content = new StringContent(stringData);
                        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        var response = await HttpClientInstance.PostAsync($"{BaseUrl}/api/token", content);
                        response.EnsureSuccessStatusCode();
                        return(await response.Content.ReadAsStringAsync());
                    };
                })
                                .Build();

                UpdateConnectionState(ConnectionState.Connected);

                HubConnection.On <string, string>("newMessage", ReceiveMessage);

                await HubConnection.StartAsync();

                UpdateConnectionState(ConnectionState.Connected);
            }
            catch (Exception ex)
            {
                UpdateConnectionState(ConnectionState.Disconnected);
                await PageDialogService.DisplayAlertAsync("Connection Error", ex.Message, "OK", null);
            }
        }
Пример #3
0
        private async Task Login()
        {
            try
            {
                HubConnection = new HubConnectionBuilder()
                                .WithUrl($"{Constants.BASE_URL}/chat", options =>
                {
                    var stringData = JsonConvert.SerializeObject(new { Username, Password });

                    options.AccessTokenProvider = async() =>
                    {
                        var content = new StringContent(stringData);
                        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        var response = await HttpClientInstance.PostAsync($"{Constants.BASE_URL}/api/token", content);
                        response.EnsureSuccessStatusCode();
                        return(await response.Content.ReadAsStringAsync());
                    };
                })
                                .Build();

                Email = Username;

                await _navigationService.NavigateAsync(nameof(MainPage));
            }
            catch (Exception ex)
            {
                await PageDialogService.DisplayAlertAsync("Connection Error", ex.Message, "OK", null);
            }
        }
Пример #4
0
        /// <summary>
        /// creates a new comment with an anonymous user. Requires the site to be set up for this
        /// </summary>
        /// <param name="baseUrl">the web site's address</param>
        /// <param name="authorName">name of the comment author</param>
        /// <param name="email">email of the comment authro</param>
        /// <param name="content">comment text</param>
        /// <param name="postId">the post id this comment should be posted to</param>
        /// <param name="parentId">id of the comment that receives the response</param>
        /// <returns></returns>
        public async Task <WordPressEntity <Comment> > CreateAnonymousComment(string baseUrl, string authorName, string email, string content, long postId, long parentId)
        {
            WordPressEntity <Comment> result = null;

            var postCommentUrl = baseUrl.GetPostApiUrl(Resource.Comments)
                                 .AddParameterToUrl("post", postId.ToString())
                                 .AddParameterToUrl("author_name", WebUtility.UrlEncode(authorName))
                                 .AddParameterToUrl("author_email", WebUtility.UrlEncode(email))
                                 .AddParameterToUrl("author_name", WebUtility.UrlEncode(authorName))
                                 .AddParameterToUrl("content", WebUtility.UrlEncode(content));

            if (parentId != 0)
            {
                postCommentUrl = postCommentUrl.AddParameterToUrl("parent", parentId.ToString());
            }

            var response = await HttpClientInstance.PostAsync(postCommentUrl, null).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                result = new WordPressEntity <Comment>(response.Content, false, ThrowSerializationExceptions);
            }
            else
            {
                result = new WordPressEntity <Comment>(response.Content, true, ThrowSerializationExceptions);
            }

            return(result);
        }
Пример #5
0
        public async Task PostAsJson_WithResponse()
        {
            var client = new HttpClientInstance("https://postman-echo.com/post");

            var response = await client.PostAsync <Response>().ConfigureAwait(false);

            response.Url.Should().Be("https://postman-echo.com/post");
        }
Пример #6
0
        /// <summary>
        /// creates a new comment with an anonymous user. Requires the site to be set up for this
        /// </summary>
        /// <param name="baseUrl">
        /// the web site's address
        /// </param>
        /// <param name="authorName">
        /// name of the comment author
        /// </param>
        /// <param name="email">
        /// email of the comment authro
        /// </param>
        /// <param name="content">
        /// comment text
        /// </param>
        /// <param name="postId">
        /// the post id this comment should be posted to
        /// </param>
        /// <param name="parentId">
        /// id of the comment that receives the response
        /// </param>
        /// <returns>
        /// </returns>
        public async Task <WordPressEntity <Comment> > CreateAnonymousCommentAsync(string baseUrl, string authorName, string email, string content, long postId, long parentId)
        {
            if (string.IsNullOrWhiteSpace(baseUrl))
            {
                throw new NullReferenceException($"parameter {nameof(baseUrl)} MUST not be null or empty");
            }

            if (string.IsNullOrWhiteSpace(authorName))
            {
                throw new NullReferenceException($"parameter {nameof(authorName)} MUST not be null or empty");
            }

            if (string.IsNullOrWhiteSpace(email))
            {
                throw new NullReferenceException($"parameter {nameof(email)} MUST not be null or empty");
            }

            if (string.IsNullOrWhiteSpace(content))
            {
                throw new NullReferenceException($"parameter {nameof(content)} MUST not be null or empty");
            }

            if (postId == -1 || postId == default)
            {
                throw new ArgumentException($"parameter {nameof(postId)} MUST be a valid post id");
            }

            var postCommentUrl = baseUrl.GetPostApiUrl(Resource.Comments)
                                 .AddParameterToUrl("post", postId.ToString())
                                 .AddParameterToUrl("author_name", WebUtility.UrlEncode(authorName))
                                 .AddParameterToUrl("author_email", WebUtility.UrlEncode(email))
                                 .AddParameterToUrl("author_name", WebUtility.UrlEncode(authorName))
                                 .AddParameterToUrl("content", WebUtility.UrlEncode(content));

            if (parentId != 0)
            {
                postCommentUrl = postCommentUrl.AddParameterToUrl("parent", parentId.ToString());
            }

            var response = await HttpClientInstance.PostAsync(postCommentUrl, null).ConfigureAwait(false);

            WordPressEntity <Comment> result;

            if (response.IsSuccessStatusCode)
            {
                result = new WordPressEntity <Comment>(response.Content, false, this.ThrowSerializationExceptions);
            }
            else
            {
                result = new WordPressEntity <Comment>(response.Content, true, this.ThrowSerializationExceptions);
            }

            return(result);
        }
Пример #7
0
        private async Task ProcessQueueItems(object[] queueItems)
        {
            try
            {
                var ndjson = new StringBuilder();
                if (_cachedMetadataJsonLine == null)
                {
                    _cachedMetadataJsonLine = "{\"metadata\": " + _payloadItemSerializer.SerializeObject(_metadata) + "}";
                }
                ndjson.AppendLine(_cachedMetadataJsonLine);

                // Apply filters
                foreach (var item in queueItems)
                {
                    switch (item)
                    {
                    case Transaction transaction:
                        if (TryExecuteFilter(TransactionFilters, transaction) != null)
                        {
                            SerializeAndSend(item, "transaction");
                        }
                        break;

                    case Span span:
                        if (TryExecuteFilter(SpanFilters, span) != null)
                        {
                            SerializeAndSend(item, "span");
                        }
                        break;

                    case Error error:
                        if (TryExecuteFilter(ErrorFilters, error) != null)
                        {
                            SerializeAndSend(item, "error");
                        }
                        break;

                    case MetricSet _:
                        SerializeAndSend(item, "metricset");
                        break;
                    }
                }

                var content = new StringContent(ndjson.ToString(), Encoding.UTF8, "application/x-ndjson");

                var result = await HttpClientInstance.PostAsync(_intakeV2EventsAbsoluteUrl, content, CtsInstance.Token);

                if (result != null && !result.IsSuccessStatusCode)
                {
                    _logger?.Error()
                    ?.Log("Failed sending event."
                          + " Events intake API absolute URL: {EventsIntakeAbsoluteUrl}."
                          + " APM Server response: status code: {ApmServerResponseStatusCode}"
                          + ", content: \n{ApmServerResponseContent}"
                          , Http.Sanitize(_intakeV2EventsAbsoluteUrl, out var sanitizedServerUrl)
                                                                ? sanitizedServerUrl
                                                                : _intakeV2EventsAbsoluteUrl.ToString()
                          , result.StatusCode, await result.Content.ReadAsStringAsync());
                }
                else
                {
                    _logger?.Debug()
                    ?.Log("Sent items to server:\n{SerializedItems}",
                          TextUtils.Indent(string.Join($",{Environment.NewLine}", queueItems.ToArray())));
                }

                void SerializeAndSend(object item, string eventType)
                {
                    var serialized = _payloadItemSerializer.SerializeObject(item);

                    ndjson.AppendLine($"{{\"{eventType}\": " + serialized + "}");
                    _logger?.Trace()?.Log("Serialized item to send: {ItemToSend} as {SerializedItem}", item, serialized);
                }
            }
            catch (Exception e)
            {
                _logger?.Warning()
                ?.LogException(
                    e,
                    "Failed sending events. Following events were not transferred successfully to the server ({ApmServerUrl}):\n{SerializedItems}"
                    , Http.Sanitize(HttpClientInstance.BaseAddress, out var sanitizedServerUrl)
                                                        ? sanitizedServerUrl
                                                        : HttpClientInstance.BaseAddress.ToString()
                    , TextUtils.Indent(string.Join($",{Environment.NewLine}", queueItems.ToArray()))
                    );
            }

            // Executes filters for the given filter collection and handles return value and errors
            T TryExecuteFilter <T>(IEnumerable <Func <T, T> > filters, T item) where T : class
Пример #8
0
        private async Task ProcessQueueItems(object[] queueItems)
        {
            try
            {
                var metadataJson = _payloadItemSerializer.SerializeObject(_metadata);
                var ndjson       = new StringBuilder();
                ndjson.AppendLine("{\"metadata\": " + metadataJson + "}");

                foreach (var item in queueItems)
                {
                    var serialized = _payloadItemSerializer.SerializeObject(item);
                    switch (item)
                    {
                    case Transaction _:
                        ndjson.AppendLine("{\"transaction\": " + serialized + "}");
                        break;

                    case Span _:
                        ndjson.AppendLine("{\"span\": " + serialized + "}");
                        break;

                    case Error _:
                        ndjson.AppendLine("{\"error\": " + serialized + "}");
                        break;

                    case MetricSet _:
                        ndjson.AppendLine("{\"metricset\": " + serialized + "}");
                        break;
                    }
                    _logger?.Trace()?.Log("Serialized item to send: {ItemToSend} as {SerializedItem}", item, serialized);
                }

                var content = new StringContent(ndjson.ToString(), Encoding.UTF8, "application/x-ndjson");

                var result = await HttpClientInstance.PostAsync(BackendCommUtils.ApmServerEndpoints.IntakeV2EventsUrlPath, content, CtsInstance.Token);

                if (result != null && !result.IsSuccessStatusCode)
                {
                    _logger?.Error()
                    ?.Log("Failed sending event. " +
                          "APM Server response: status code: {ApmServerResponseStatusCode}, content: \n{ApmServerResponseContent}",
                          result.StatusCode, await result.Content.ReadAsStringAsync());
                }
                else
                {
                    _logger?.Debug()
                    ?.Log("Sent items to server:\n{SerializedItems}",
                          TextUtils.Indent(string.Join($",{Environment.NewLine}", queueItems.ToArray())));
                }
            }
            catch (Exception e)
            {
                _logger?.Warning()
                ?.LogException(
                    e,
                    "Failed sending events. Following events were not transferred successfully to the server ({ApmServerUrl}):\n{SerializedItems}"
                    , HttpClientInstance.BaseAddress
                    , TextUtils.Indent(string.Join($",{Environment.NewLine}", queueItems.ToArray()))
                    );
            }
        }