Skip to content

Commit

Permalink
Merge pull request #33 from githuib/API-97_add-user-agent-to-requests
Browse files Browse the repository at this point in the history
API-97 - add user agent to requests
  • Loading branch information
Huib Piguillet authored Oct 28, 2020
2 parents 505276f + 44c7733 commit 8a2b324
Show file tree
Hide file tree
Showing 9 changed files with 216 additions and 159 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
# General macOS
.DS_Store
.AppleDouble
.LSOverride

# Build results
bin/
obj/
Expand Down
49 changes: 26 additions & 23 deletions Bynder/Sample/ApiSample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
// Licensed under the MIT License. See LICENSE file in the project root for full license information.

using System;
using System.Configuration;
using Bynder.Sdk;
using Bynder.Sdk.Service;
using Bynder.Sample;
using Bynder.Sample.Utils;
using Bynder.Sdk.Query.Asset;
using Bynder.Sdk.Query.Collection;
Expand All @@ -24,6 +21,13 @@ public class ApiSample
/// </summary>
/// <param name="args">arguments to main</param>
public static void Main(string[] args)
{
//Choose your authentication method by commenting one of these lines.
PermanentToken();
Oauth();
}

private static void PermanentToken()
{
using (var client = ClientFactory.Create(Configuration.FromJson("Config.json")))
{
Expand All @@ -41,34 +45,33 @@ public static void Main(string[] args)
Console.WriteLine(collection.Name);
}
}
}

private static void Oauth()
{
using (var waitForToken = new WaitForToken())
using (var listener = new UrlHttpListener("http://localhost:8888/", waitForToken))
using (var client = ClientFactory.Create(Configuration.FromJson("Config.json")))
{
using (var listener = new UrlHttpListener("http://localhost:8888/", waitForToken))
{
using (var client = ClientFactory.Create(Configuration.FromJson("Config.json")))
{
Browser.Launch(client.GetOAuthService().GetAuthorisationUrl("state example", "offline asset:read collection:read"));
waitForToken.WaitHandle.WaitOne(50000);
Browser.Launch(client.GetOAuthService().GetAuthorisationUrl("state example", "offline asset:read collection:read"));
waitForToken.WaitHandle.WaitOne(50000);

if (waitForToken.Success)
{
client.GetOAuthService().GetAccessTokenAsync(waitForToken.Token, "offline asset:read collection:read").Wait();
if (waitForToken.Success)
{
client.GetOAuthService().GetAccessTokenAsync(waitForToken.Token, "offline asset:read collection:read").Wait();

var mediaList = client.GetAssetService().GetMediaListAsync(new MediaQuery()).Result;
var mediaList = client.GetAssetService().GetMediaListAsync(new MediaQuery()).Result;

foreach (var media in mediaList)
{
Console.WriteLine(media.Name);
}
foreach (var media in mediaList)
{
Console.WriteLine(media.Name);
}

var collectionList = client.GetCollectionService().GetCollectionsAsync(new GetCollectionsQuery()).Result;
var collectionList = client.GetCollectionService().GetCollectionsAsync(new GetCollectionsQuery()).Result;

foreach (var collection in collectionList)
{
Console.WriteLine(collection.Name);
}
}
foreach (var collection in collectionList)
{
Console.WriteLine(collection.Name);
}
}
}
Expand Down
21 changes: 15 additions & 6 deletions Bynder/Sdk/Api/RequestSender/ApiRequestSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
using System.Threading.Tasks;
using Bynder.Sdk.Model;
using Bynder.Sdk.Api.Requests;
using Bynder.Sdk.Service;
using Newtonsoft.Json;
using Bynder.Sdk.Query.Decoder;
using Bynder.Sdk.Query;
Expand All @@ -28,6 +27,8 @@ internal class ApiRequestSender : IApiRequestSender
private SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
private IHttpRequestSender _httpSender;

public const string TokenPath = "/v6/authentication/oauth2/token";

/// <summary>
/// Initializes a new instance of the <see cref="T:Sdk.Api.ApiRequestSender"/> class.
/// </summary>
Expand Down Expand Up @@ -90,13 +91,21 @@ public async Task<T> SendRequestAsync<T>(Requests.Request<T> request)
}

var httpRequest = CreateHttpRequest(request);
var responseString = await _httpSender.SendHttpRequest(httpRequest).ConfigureAwait(false);
if (!string.IsNullOrEmpty(responseString))
var response = await _httpSender.SendHttpRequest(httpRequest).ConfigureAwait(false);

var responseContent = response.Content;
if (response.Content == null)
{
return default(T);
}

var responseString = await responseContent.ReadAsStringAsync().ConfigureAwait(false);
if (string.IsNullOrEmpty(responseString))
{
return JsonConvert.DeserializeObject<T>(responseString);
return default(T);
}

return default(T);
return JsonConvert.DeserializeObject<T>(responseString);
}

private HttpRequestMessage CreateHttpRequest<T>(Requests.Request<T> request)
Expand Down Expand Up @@ -131,7 +140,7 @@ private async Task RefreshToken()
{
Authenticated = false,
Query = query,
Path = $"/v6/authentication/oauth2/token",
Path = TokenPath,
HTTPMethod = HttpMethod.Post
};

Expand Down
17 changes: 13 additions & 4 deletions Bynder/Sdk/Api/RequestSender/HttpRequestSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License. See LICENSE file in the project root for full license information.

using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;

namespace Bynder.Sdk.Api.RequestSender
Expand All @@ -14,17 +15,25 @@ internal class HttpRequestSender : IHttpRequestSender
{
private readonly HttpClient _httpClient = new HttpClient();

/// <summary>
/// User-Agent header we add to each request.
/// </summary>
public string UserAgent
{
get { return $"bynder-c-sharp-sdk/{Assembly.GetExecutingAssembly().GetName().Version.ToString()}"; }
}

/// <summary>
/// Sends the HTTP request and returns the content as string.
/// Sends the HTTP request and returns its response.
/// </summary>
/// <returns>The HTTP request response.</returns>
/// <param name="httpRequest">HTTP request.</param>
public async Task<string> SendHttpRequest(HttpRequestMessage httpRequest)
public async Task<HttpResponseMessage> SendHttpRequest(HttpRequestMessage httpRequest)
{
httpRequest.Headers.Add("User-Agent", UserAgent);
var response = await _httpClient.SendAsync(httpRequest).ConfigureAwait(false);

response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return response;
}

/// <summary>
Expand Down
4 changes: 2 additions & 2 deletions Bynder/Sdk/Api/RequestSender/IHttpRequestSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ namespace Bynder.Sdk.Api.RequestSender
internal interface IHttpRequestSender : IDisposable
{
/// <summary>
/// Sends the HTTP request and returns the content as string.
/// Sends the HTTP request and returns its response.
/// </summary>
/// <returns>The HTTP request response.</returns>
/// <param name="httpRequest">HTTP request.</param>
Task<string> SendHttpRequest(HttpRequestMessage httpRequest);
Task<HttpResponseMessage> SendHttpRequest(HttpRequestMessage httpRequest);
}
}
19 changes: 19 additions & 0 deletions Bynder/Sdk/Bynder.Sdk.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,29 @@
<Company>Bynder</Company>
<Product>Bynder.Sdk</Product>
<Copyright>Copyright © Bynder</Copyright>
<PackOnBuild>true</PackOnBuild>
<PackageVersion>2.2.0</PackageVersion>
<Authors>BynderDevops</Authors>
<Description>The main goal of this SDK is to speed up the integration of Bynder customers who use C# making it easier to connect to the Bynder API (http://docs.bynder.apiary.io/) and executing requests on it.</Description>
<PackageIconUrl>https://bynder.com/static/3.0/img/favicon-black.ico</PackageIconUrl>
<NeutralLanguage>en</NeutralLanguage>
<PackageLicenseUrl>https://github.com/Bynder/bynder-c-sharp-sdk/blob/master/LICENSE</PackageLicenseUrl>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<Owners>BynderDevops</Owners>
<PackageProjectUrl>https://github.com/Bynder/bynder-c-sharp-sdk</PackageProjectUrl>
<PackageReleaseNotes>Adds the SDK's name and version to each request in the User-Agent header, to enable better insight in the Bynder API usage.</PackageReleaseNotes>
<Summary>The main goal of this SDK is to speed up the integration of Bynder customers who use C# making it easier to connect to the Bynder API (http://docs.bynder.apiary.io/) and executing requests on it.</Summary>
<PackageTags>Bynder API C# SDK</PackageTags>
<Title>Bynder.Sdk</Title>
<PackageId>Bynder.Sdk</PackageId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.7" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="NuGet.Build.Packaging" Version="0.2.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
Expand Down
Loading

0 comments on commit 8a2b324

Please sign in to comment.