public void AfterPostingEntryGetRootReturnsEntryInContent()
        {
            using (var client = HttpClientFactory.Create())
            {
                var json = new
                {
                    time = DateTimeOffset.Now,
                    distance = 8000,
                    duration = TimeSpan.FromMinutes(41)
                };
                var content = new JsonContent(json);
                var expected = content.ReadAsJsonAsync().Result;
                content.Headers.ContentType.MediaType = "application/json";
                client.PostAsync("", content).Wait();

                var response = client.GetAsync("").Result;

                var actual = response.Content.ReadAsJsonAsync().Result;
                Assert.Contains(expected, actual.entries);
            }
        }
Beispiel #2
0
 /// <summary>
 /// Add subscribers to queue.
 /// </summary>
 public async Task<bool> AddSubscribersAsync(params string[] subscribers)
 {
     var add = new _Subscribers(subscribers);
     var content = new JsonContent(content: add);
     var response = await _client.PostAsync(string.Format("queues/{0}/subscribers", Name), content);
     return response.IsSuccessStatusCode;
 }
Beispiel #3
0
 /// <summary>
 /// Get existing queue or create a new queue if it does not exist yet.
 /// If no name is given, a new name is generated.
 /// </summary>
 public async Task<Queue> CreateOrGetQueueAsync(string name = null)
 {
     if (string.IsNullOrWhiteSpace(name)) name = Guid.NewGuid().ToString();
     var content = new JsonContent("{}");
     var response = await _client.PostAsync(string.Format("queues/{0}", name), content);
     return new Queue(this._client, name);
 }
Beispiel #4
0
        public virtual HttpRequest SetContent(string content)
        {
            if(!string.IsNullOrWhiteSpace(content))
                Content = new JsonContent(content);

            return this;
        }
        public void PostEntrySucceeds()
        {
            using (var client = HttpClientFactory.Create())
            {
                var json = new
                {
                    time = DateTimeOffset.Now,
                    distance = 8500,
                    duration = TimeSpan.FromMinutes(44)
                };
                var content = new JsonContent(json);
                content.Headers.ContentType.MediaType = "application/json";

                var response = client.PostAsync("", content).Result;

                Assert.True(
                    response.IsSuccessStatusCode,
                    "Actual status code: " + response.StatusCode);
            }
        }
Beispiel #6
0
        public void GetAfterPostResponseReturnsCorrectStatusCode()
        {
            using (var client = HttpClientFactory.Create())
            {
                var json = new
                {
                    time = DateTimeOffset.Now,
                    distance = 8100,
                    duration = TimeSpan.FromMinutes(41)
                };

                //see for explanation https://davidsiew.wordpress.com/2013/03/20/outside-in-tdd-clarifications/
                var content = new JsonContent(json);
                var expected = content.ReadAsJsonAsync().Result;
                client.PostAsJsonAsync("", json).Wait();

                var response = client.GetAsync("").Result;

                var actual = response.Content.ReadAsJsonAsync().Result;

                Assert.Contains(expected, actual.entries);

            }
        }
Beispiel #7
0
 public void JsonContentInputTypeIsNull()
 => AssertExtensions.Throws <ArgumentNullException>("inputType", () => JsonContent.Create(null, inputType: null, mediaType: null));
Beispiel #8
0
 /// <summary>
 /// Update queue.
 /// </summary>
 public async Task<bool> UpdateAsync(PushType pushtype = PushType.Multicast, int retries = 3, int retriesDelay = 60, params string[] subscribers)
 {
     var content = new JsonContent(content: new _Update( pushtype, retries, retriesDelay, subscribers));
     var response = await _client.PostAsync(string.Format("queues/{0}", Name), content);
     return response.IsSuccessStatusCode;
 }
Beispiel #9
0
 /// <summary>
 /// Touching a reserved message extends its timeout by the duration specified when the message was created, 
 /// which is 60 seconds by default.
 /// </summary>
 public async Task<bool> TouchMessageAsync(Message message, long delay = 60)
 {
     var content = new JsonContent();
     var response = await _client.PostAsync(string.Format("queues/{0}/messages/{1}/touch", Name, message.ID), content);
     return response.IsSuccessStatusCode;
 }
Beispiel #10
0
 /// <summary>
 /// Add messages to a queue, 
 /// and return messages added to the queue with updated ID.
 /// </summary>
 public async Task<Message[]> AddMessagesAsync(params Message[] messages)
 {
     var content = new JsonContent(new _Messages(messages));
     var response = await _client.PostAsync(string.Format("queues/{0}/messages", Name), content);
     if (response.IsSuccessStatusCode)
     {
         var json = await response.Content.ReadAsStringAsync();
         return messages.Zip(new _IDs(json).IDs, (message, id) => { message.ID = id; return message; }).ToArray();
     }
     else
     {
         return new Message[] { };
     }
 }
Beispiel #11
0
 public static HttpResponseMessage ConvertToHttpResponseISE(this JsonContent content)
 {
     return(content.ConvertToHttpResponse(HttpStatusCode.InternalServerError));
 }
Beispiel #12
0
 public static HttpResponseMessage ConvertToHttpResponseOK(this JsonContent content)
 {
     return(content.ConvertToHttpResponse(HttpStatusCode.OK));
 }
Beispiel #13
0
        public async Task <T> Run <T>(IFlurlClient request, JsonContent bodyContent, ExecuteRequestAsync <T> executeRequestAsync)
        {
            var fullResult = await executeRequestAsync(request, bodyContent);

            return(fullResult.Result);
        }
Beispiel #14
0
 /// <summary>
 /// Clear all messages in a queue.
 /// </summary>
 public async Task<bool> ClearMessagesAsync()
 {
     var content = new JsonContent();
     var response = await _client.PostAsync(string.Format("queues/{0}/clear", Name), content);
     return response.IsSuccessStatusCode;
 }
 protected Task Send(JsonContent content)
 {
     return(webSocket.Send(content));
 }
        public void WhenConstructedSetsTheContentTypeHeader()
        {
            var content = new JsonContent("{}");

            content.Headers.ContentType.Value.Should().Be("application/json");
        }
Beispiel #17
0
        public async Task <IEnumerable <ProgramInfo> > GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(channelId))
            {
                throw new ArgumentNullException(nameof(channelId));
            }

            // Normalize incoming input
            channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');

            var token = await GetToken(info, cancellationToken).ConfigureAwait(false);

            if (string.IsNullOrEmpty(token))
            {
                _logger.LogWarning("SchedulesDirect token is empty, returning empty program list");

                return(Enumerable.Empty <ProgramInfo>());
            }

            var dates = GetScheduleRequestDates(startDateUtc, endDateUtc);

            _logger.LogInformation("Channel Station ID is: {ChannelID}", channelId);
            var requestList = new List <RequestScheduleForChannelDto>()
            {
                new RequestScheduleForChannelDto()
                {
                    StationId = channelId,
                    Date      = dates
                }
            };

            _logger.LogDebug("Request string for schedules is: {@RequestString}", requestList);

            using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules");
            options.Content   = JsonContent.Create(requestList, options: _jsonOptions);
            options.Headers.TryAddWithoutValidation("token", token);
            using var response = await Send(options, true, info, cancellationToken).ConfigureAwait(false);

            await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);

            var dailySchedules = await JsonSerializer.DeserializeAsync <IReadOnlyList <DayDto> >(responseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);

            if (dailySchedules == null)
            {
                return(Array.Empty <ProgramInfo>());
            }

            _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId);

            using var programRequestOptions = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/programs");
            programRequestOptions.Headers.TryAddWithoutValidation("token", token);

            var programIds = dailySchedules.SelectMany(d => d.Programs.Select(s => s.ProgramId)).Distinct();

            programRequestOptions.Content = JsonContent.Create(programIds, options: _jsonOptions);

            using var innerResponse = await Send(programRequestOptions, true, info, cancellationToken).ConfigureAwait(false);

            await using var innerResponseStream = await innerResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);

            var programDetails = await JsonSerializer.DeserializeAsync <IReadOnlyList <ProgramDetailsDto> >(innerResponseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);

            if (programDetails == null)
            {
                return(Array.Empty <ProgramInfo>());
            }

            var programDict = programDetails.ToDictionary(p => p.ProgramId, y => y);

            var programIdsWithImages = programDetails
                                       .Where(p => p.HasImageArtwork).Select(p => p.ProgramId)
                                       .ToList();

            var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false);

            var programsInfo = new List <ProgramInfo>();

            foreach (ProgramDto schedule in dailySchedules.SelectMany(d => d.Programs))
            {
                // _logger.LogDebug("Proccesing Schedule for statio ID " + stationID +
                //              " which corresponds to channel " + channelNumber + " and program id " +
                //              schedule.ProgramId + " which says it has images? " +
                //              programDict[schedule.ProgramId].hasImageArtwork);

                if (string.IsNullOrEmpty(schedule.ProgramId))
                {
                    continue;
                }

                if (images != null)
                {
                    var imageIndex = images.FindIndex(i => i.ProgramId == schedule.ProgramId[..10]);
                    if (imageIndex > -1)
                    {
                        var programEntry = programDict[schedule.ProgramId];

                        var allImages         = images[imageIndex].Data;
                        var imagesWithText    = allImages.Where(i => string.Equals(i.Text, "yes", StringComparison.OrdinalIgnoreCase)).ToList();
                        var imagesWithoutText = allImages.Where(i => string.Equals(i.Text, "no", StringComparison.OrdinalIgnoreCase)).ToList();

                        const double DesiredAspect = 2.0 / 3;

                        programEntry.PrimaryImage = GetProgramImage(ApiUrl, imagesWithText, DesiredAspect) ??
                                                    GetProgramImage(ApiUrl, allImages, DesiredAspect);

                        const double WideAspect = 16.0 / 9;

                        programEntry.ThumbImage = GetProgramImage(ApiUrl, imagesWithText, WideAspect);

                        // Don't supply the same image twice
                        if (string.Equals(programEntry.PrimaryImage, programEntry.ThumbImage, StringComparison.Ordinal))
                        {
                            programEntry.ThumbImage = null;
                        }

                        programEntry.BackdropImage = GetProgramImage(ApiUrl, imagesWithoutText, WideAspect);

                        // programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
                        //    GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
                        //    GetProgramImage(ApiUrl, data, "Banner-LO", false) ??
                        //    GetProgramImage(ApiUrl, data, "Banner-LOT", false);
                    }
                }

                programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.ProgramId]));
            }

            return(programsInfo);
        }
Beispiel #18
0
        public async Task <(HttpStatusCode, Image)> CreateOrUpdateImageAsync(string accountName, Image image)
        {
            var response = await this.Client.PutAsync(new Uri($"/api/image/update/{accountName}",
                                                              UriKind.RelativeOrAbsolute), JsonContent.Create(image));

            var stream = await response.Content.ReadAsStreamAsync();

            Image content = response.StatusCode == HttpStatusCode.OK ?
                            await JsonSerializer.DeserializeAsync <Image>(stream) : null;

            return(response.StatusCode, content);
        }
Beispiel #19
0
        public async Task <HttpStatusCode> CreateImageAsync(string accountName, Image image)
        {
            var response = await this.Client.PostAsync(new Uri($"/api/image/create/{accountName}",
                                                               UriKind.RelativeOrAbsolute), JsonContent.Create(image));

            return(response.StatusCode);
        }
Beispiel #20
0
        public async Task <IActionResult> PostWebhook([FromQuery, Required] string key,
                                                      [FromBody, Required] FreshdeskWebhookModel model)
        {
            if (string.IsNullOrWhiteSpace(key) || !CoreHelpers.FixedTimeEquals(key, _billingSettings.FreshdeskWebhookKey))
            {
                return(new BadRequestResult());
            }

            try
            {
                var ticketId           = model.TicketId;
                var ticketContactEmail = model.TicketContactEmail;
                var ticketTags         = model.TicketTags;
                if (string.IsNullOrWhiteSpace(ticketId) || string.IsNullOrWhiteSpace(ticketContactEmail))
                {
                    return(new BadRequestResult());
                }

                var updateBody   = new Dictionary <string, object>();
                var note         = string.Empty;
                var customFields = new Dictionary <string, object>();
                var user         = await _userRepository.GetByEmailAsync(ticketContactEmail);

                if (user != null)
                {
                    var userLink = $"{_globalSettings.BaseServiceUri.Admin}/users/edit/{user.Id}";
                    note += $"<li>User, {user.Email}: {userLink}</li>";
                    customFields.Add("cf_user", userLink);
                    var tags = new HashSet <string>();
                    if (user.Premium)
                    {
                        tags.Add("Premium");
                    }
                    var orgs = await _organizationRepository.GetManyByUserIdAsync(user.Id);

                    foreach (var org in orgs)
                    {
                        var orgNote = $"{org.Name} ({org.Seats.GetValueOrDefault()}): " +
                                      $"{_globalSettings.BaseServiceUri.Admin}/organizations/edit/{org.Id}";
                        note += $"<li>Org, {orgNote}</li>";
                        if (!customFields.Any(kvp => kvp.Key == "cf_org"))
                        {
                            customFields.Add("cf_org", orgNote);
                        }
                        else
                        {
                            customFields["cf_org"] += $"\n{orgNote}";
                        }

                        var planName = GetAttribute <DisplayAttribute>(org.PlanType).Name.Split(" ").FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(planName))
                        {
                            tags.Add(string.Format("Org: {0}", planName));
                        }
                    }
                    if (tags.Any())
                    {
                        var tagsToUpdate = tags.ToList();
                        if (!string.IsNullOrWhiteSpace(ticketTags))
                        {
                            var splitTicketTags = ticketTags.Split(',');
                            for (var i = 0; i < splitTicketTags.Length; i++)
                            {
                                tagsToUpdate.Insert(i, splitTicketTags[i]);
                            }
                        }
                        updateBody.Add("tags", tagsToUpdate);
                    }

                    if (customFields.Any())
                    {
                        updateBody.Add("custom_fields", customFields);
                    }
                    var updateRequest = new HttpRequestMessage(HttpMethod.Put,
                                                               string.Format("https://bitwarden.freshdesk.com/api/v2/tickets/{0}", ticketId))
                    {
                        Content = JsonContent.Create(updateBody),
                    };
                    await CallFreshdeskApiAsync(updateRequest);

                    var noteBody = new Dictionary <string, object>
                    {
                        { "body", $"<ul>{note}</ul>" },
                        { "private", true }
                    };
                    var noteRequest = new HttpRequestMessage(HttpMethod.Post,
                                                             string.Format("https://bitwarden.freshdesk.com/api/v2/tickets/{0}/notes", ticketId))
                    {
                        Content = JsonContent.Create(noteBody),
                    };
                    await CallFreshdeskApiAsync(noteRequest);
                }

                return(new OkResult());
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error processing freshdesk webhook.");
                return(new BadRequestResult());
            }
        }
Beispiel #21
0
 public virtual void SetContent(string content)
 {
     if(content != null)
         Content = new JsonContent(content);
 }
Beispiel #22
0
 public virtual void SetContent(string content)
 {
     if(!string.IsNullOrWhiteSpace(content))
         Content = new JsonContent(content);
 }
Beispiel #23
0
 public async Task CallSendGuess(string username, int guess)
 {
     await _client.PostAsync(
         "https://localhost:44376/api/Numbers/" + username,
         JsonContent.Create(guess, typeof(int)));
 }
Beispiel #24
-1
        public void GetRootReturnsCorrectEntryFromDatabase()
        {
            dynamic entry = new ExpandoObject();
            entry.time = DateTimeOffset.Now;
            entry.distance = 6000;
            entry.duration = TimeSpan.FromMinutes(31);

            var entryToSerialize = new
            {
                time = entry.time,
                distance = entry.distance,
                duration = entry.duration
            };

            var content = new JsonContent(entryToSerialize);
            var expected = content.ReadAsJsonAsync().Result;

            var connStr = ConfigurationManager.ConnectionStrings["running-journal"].ConnectionString;
            var db = Database.OpenConnection(connStr);
            var userId = db.User.Insert(UserName: "******").UserId;
            entry.UserId = (int)userId;
            db.JournalEntry.Insert(entry);

            using (var client = HttpClientFactory.Create())
            {
                var response = client.GetAsync("").Result;

                var actual = response.Content.ReadAsJsonAsync().Result;

                Assert.Contains(expected, actual.entries);
            }
        }