Skip to content

Commit

Permalink
Merge pull request #39 from githuib/refactor-api-requests
Browse files Browse the repository at this point in the history
API-184 - Refactor request stuff and async inconsistencies
  • Loading branch information
Huib Piguillet authored Dec 24, 2020
2 parents 1e551ca + a2bee83 commit 151364d
Show file tree
Hide file tree
Showing 14 changed files with 320 additions and 376 deletions.
73 changes: 31 additions & 42 deletions Bynder/Sample/ApiSample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Bynder.Sdk.Query.Asset;
using Bynder.Sdk.Query.Collection;
using Bynder.Sdk.Settings;
using System.Threading.Tasks;

namespace Bynder.Sample
{
Expand All @@ -20,61 +21,49 @@ public class ApiSample
/// Main function
/// </summary>
/// <param name="args">arguments to main</param>
public static void Main(string[] args)
public static async Task Main(string[] args)
{
//Choose your authentication method by commenting one of these lines.
PermanentToken();
Oauth();
Configuration configuration = Configuration.FromJson("Config.json");
using var client = ClientFactory.Create(configuration);
if (configuration.PermanentToken != null)
{
await QueryBynder(client);
}
else
{
await QueryBynderUsingOAuth(client);
}
}

private static void PermanentToken()
private static async Task QueryBynder(IBynderClient client)
{
using (var client = ClientFactory.Create(Configuration.FromJson("Config.json")))
var mediaList = await client.GetAssetService().GetMediaListAsync(new MediaQuery());
foreach (var media in mediaList)
{
var mediaList = client.GetAssetService().GetMediaListAsync(new MediaQuery()).Result;

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

var collectionList = client.GetCollectionService().GetCollectionsAsync(new GetCollectionsQuery()).Result;
Console.WriteLine(media.Name);
}

foreach (var collection in collectionList)
{
Console.WriteLine(collection.Name);
}
var collectionList = await client.GetCollectionService().GetCollectionsAsync(new GetCollectionsQuery());
foreach (var collection in collectionList)
{
Console.WriteLine(collection.Name);
}
}

private static void Oauth()
private static async Task QueryBynderUsingOAuth(IBynderClient client)
{
using (var waitForToken = new WaitForToken())
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);

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

var mediaList = client.GetAssetService().GetMediaListAsync(new MediaQuery()).Result;
using var waitForToken = new WaitForToken();
using var listener = new UrlHttpListener("http://localhost:8888/", waitForToken);

foreach (var media in mediaList)
{
Console.WriteLine(media.Name);
}
Browser.Launch(client.GetOAuthService().GetAuthorisationUrl("state example", "offline asset:read collection:read"));
waitForToken.WaitHandle.WaitOne(50000);

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

foreach (var collection in collectionList)
{
Console.WriteLine(collection.Name);
}
}
if (waitForToken.Success)
{
client.GetOAuthService().GetAccessTokenAsync(waitForToken.Token, "offline asset:read collection:read").Wait();
await QueryBynder(client);
}
}

}
}
10 changes: 6 additions & 4 deletions Bynder/Sdk/Api/RequestSender/ApiRequestSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,13 @@ public async Task<T> SendRequestAsync<T>(Request<T> request)
var responseContent = response.Content;
if (response.Content == null)
{
return default(T);
return default;
}

var responseString = await responseContent.ReadAsStringAsync().ConfigureAwait(false);
if (responseString == null)
{
return default(T);
return default;
}

return JsonConvert.DeserializeObject<T>(responseString);
Expand Down Expand Up @@ -132,8 +132,10 @@ private static class HttpRequestMessageFactory
internal static HttpRequestMessage Create(
string baseUrl, HttpMethod method, IDictionary<string, string> requestParams, string urlPath)
{
var builder = new UriBuilder(baseUrl);
builder.Path = urlPath;
var builder = new UriBuilder(baseUrl)
{
Path = urlPath
};

if (HttpMethod.Get == method)
{
Expand Down
9 changes: 8 additions & 1 deletion Bynder/Sdk/Api/Requests/ApiRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@
namespace Bynder.Sdk.Api.Requests
{
/// <summary>
/// API request.
/// API request where the response body can be deserialized into an object with type T.
/// </summary>
/// <typeparam name="T">Type to which the response will be deserialized</typeparam>
internal class ApiRequest<T> : Request<T>
{
}

/// <summary>
/// API request where the response has an empty body, or a body with an unknown structure.
/// </summary>
internal class ApiRequest : Request<object>
{
}
}
5 changes: 3 additions & 2 deletions Bynder/Sdk/Api/Requests/OAuthRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ namespace Bynder.Sdk.Api.Requests
/// <typeparam name="T">Type to which the response will be deserialized</typeparam>
internal class OAuthRequest<T> : Request<T>
{
public OAuthRequest() {
Authenticated = false;
internal OAuthRequest()
{
_authenticated = false;
}
}
}
22 changes: 8 additions & 14 deletions Bynder/Sdk/Api/Requests/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,32 +11,26 @@ namespace Bynder.Sdk.Api.Requests
/// <typeparam name="T">Type to which the response will be deserialized</typeparam>
internal abstract class Request<T>
{
/// <summary>
/// Object with information about the API parameters to send.
/// </summary>
public object Query { get; set; }
protected bool _authenticated = true;

/// <summary>
/// Path of the endpoint to call.
/// Indicates whether the request needs to be authenticated.
/// </summary>
public string Path { get; set; }
internal bool Authenticated { get { return _authenticated; } }

/// <summary>
/// HttpMethod to use.
/// </summary>
public HttpMethod HTTPMethod { get; set; }
internal HttpMethod HTTPMethod { get; set; }

/// <summary>
/// Gets or sets a value indicating whether this <see cref="Request`1"/> is authenticated.
/// Path of the endpoint to call.
/// </summary>
/// <value><c>true</c> if authenticated; otherwise, <c>false</c>.</value>
public bool Authenticated { get; set; } = true;
internal string Path { get; set; }

/// <summary>
/// True if we want to deserialize response to <see cref="T"/>.
/// However if <see cref="T"/> is a string and this property has value false, we might want to get the raw string response without
/// deserializing, so in that case deserialization will not occur.
/// Optional: Object with information about the API parameters to send.
/// </summary>
public bool DeserializeResponse { get; set; } = true;
internal object Query { get; set; }
}
}
4 changes: 2 additions & 2 deletions Bynder/Sdk/Bynder.Sdk.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<Product>Bynder.Sdk</Product>
<Copyright>Copyright © Bynder</Copyright>
<PackOnBuild>true</PackOnBuild>
<PackageVersion>2.2.2</PackageVersion>
<PackageVersion>2.2.3</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>
Expand All @@ -16,7 +16,7 @@
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<Owners>BynderDevops</Owners>
<PackageProjectUrl>https://github.com/Bynder/bynder-c-sharp-sdk</PackageProjectUrl>
<PackageReleaseNotes>Fixes an issue that broke the file uploader</PackageReleaseNotes>
<PackageReleaseNotes>General improvements for stability.</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>
Expand Down
68 changes: 25 additions & 43 deletions Bynder/Sdk/Service/Asset/AssetService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,47 +43,41 @@ public AssetService(IApiRequestSender requestSender)
/// Check <see cref="IAssetService"/> for more information
/// </summary>
/// <returns>Check <see cref="IAssetService"/> for more information</returns>
public Task<IList<Brand>> GetBrandsAsync()
public async Task<IList<Brand>> GetBrandsAsync()
{
var request = new ApiRequest<IList<Brand>>
return await _requestSender.SendRequestAsync(new ApiRequest<IList<Brand>>
{
Path = "/api/v4/brands/",
HTTPMethod = HttpMethod.Get
};

return _requestSender.SendRequestAsync(request);
HTTPMethod = HttpMethod.Get,
}).ConfigureAwait(false);
}

/// <summary>
/// Check <see cref="IAssetService"/> for more information
/// </summary>
/// <returns>Check <see cref="IAssetService"/> for more information</returns>
public Task<IDictionary<string, Metaproperty>> GetMetapropertiesAsync()
public async Task<IDictionary<string, Metaproperty>> GetMetapropertiesAsync()
{
var request = new ApiRequest<IDictionary<string, Metaproperty>>
return await _requestSender.SendRequestAsync(new ApiRequest<IDictionary<string, Metaproperty>>
{
Path = "/api/v4/metaproperties/",
HTTPMethod = HttpMethod.Get
};

return _requestSender.SendRequestAsync(request);
HTTPMethod = HttpMethod.Get,
}).ConfigureAwait(false);
}

/// <summary>
/// Check <see cref="IAssetService"/> for more information
/// </summary>
/// <param name="query">Check <see cref="IAssetService"/> for more information</param>
/// <returns>Check <see cref="IAssetService"/> for more information</returns>
public Task<IList<Media>> GetMediaListAsync(MediaQuery query)
public async Task<IList<Media>> GetMediaListAsync(MediaQuery query)
{
var request = new ApiRequest<IList<Media>>
return await _requestSender.SendRequestAsync(new ApiRequest<IList<Media>>
{
Path = "/api/v4/media/",
HTTPMethod = HttpMethod.Get,
Query = query
};

return _requestSender.SendRequestAsync(request);
Query = query,
}).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -93,7 +87,7 @@ public Task<IList<Media>> GetMediaListAsync(MediaQuery query)
/// <returns>Check <see cref="IAssetService"/> for more information</returns>
public async Task<Uri> GetDownloadFileUrlAsync(DownloadMediaQuery query)
{
string path = string.Empty;
string path;
if (query.MediaItemId == null)
{
path = $"/api/v4/media/{query.MediaId}/download/";
Expand All @@ -103,13 +97,11 @@ public async Task<Uri> GetDownloadFileUrlAsync(DownloadMediaQuery query)
path = $"/api/v4/media/{query.MediaId}/download/{query.MediaItemId}/";
}

var request = new ApiRequest<DownloadFileUrl>
var downloadFileInformation = await _requestSender.SendRequestAsync(new ApiRequest<DownloadFileUrl>
{
Path = path,
HTTPMethod = HttpMethod.Get
};

var downloadFileInformation = await _requestSender.SendRequestAsync(request).ConfigureAwait(false);
HTTPMethod = HttpMethod.Get,
}).ConfigureAwait(false);
return downloadFileInformation.S3File;
}

Expand All @@ -118,49 +110,39 @@ public async Task<Uri> GetDownloadFileUrlAsync(DownloadMediaQuery query)
/// </summary>
/// <param name="query">Check <see cref="IAssetService"/> for more information</param>
/// <returns>Check <see cref="IAssetService"/> for more information</returns>
public Task UploadFileAsync(UploadQuery query)
public async Task UploadFileAsync(UploadQuery query)
{
return _uploader.UploadFile(query);
await _uploader.UploadFileAsync(query).ConfigureAwait(false);
}

/// <summary>
/// Check <see cref="IAssetService"/> for more information
/// </summary>
/// <param name="query">Check <see cref="IAssetService"/> for more information</param>
/// <returns>Check <see cref="IAssetService"/> for more information</returns>
public Task<Media> GetMediaInfoAsync(MediaInformationQuery query)
public async Task<Media> GetMediaInfoAsync(MediaInformationQuery query)
{
if (string.IsNullOrEmpty(query.MediaId))
{
throw new ArgumentNullException(nameof(query), "Parameter cannot be null or empty.");
}

var request = new ApiRequest<Media>
return await _requestSender.SendRequestAsync(new ApiRequest<Media>
{
Path = $"/api/v4/media/{query.MediaId}/",
HTTPMethod = HttpMethod.Get,
Query = query
};

return _requestSender.SendRequestAsync(request);
Query = query,
}).ConfigureAwait(false);
}

/// <summary>
/// Check <see cref="IAssetService"/> for more information
/// </summary>
/// <param name="query">Check <see cref="IAssetService"/> for more information</param>
/// <returns>Check <see cref="IAssetService"/> for more information</returns>
public Task ModifyMediaAsync(ModifyMediaQuery query)
public async Task ModifyMediaAsync(ModifyMediaQuery query)
{
var request = new ApiRequest<object>
await _requestSender.SendRequestAsync(new ApiRequest
{
Path = $"/api/v4/media/{query.MediaId}/",
HTTPMethod = HttpMethod.Post,
Query = query,
DeserializeResponse = false
};

return _requestSender.SendRequestAsync(request);
}).ConfigureAwait(false);
}
}
}
Loading

0 comments on commit 151364d

Please sign in to comment.