Skip to content

Commit

Permalink
Update Sample project to .NET Core 2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
condemil committed Feb 18, 2019
1 parent c6e2ea2 commit 03bab2a
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 169 deletions.
19 changes: 19 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
// https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": "Sample",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build_sample",
"program": "${workspaceFolder}/Bynder/Sample/bin/Debug/netcoreapp2.0/Bynder.Sample.dll",
"cwd": "${workspaceFolder}/Bynder/Sample",
"console": "internalConsole",
"internalConsoleOptions": "openOnSessionStart",
"logging": {
"moduleLoad": false
}
}
]
}
15 changes: 15 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build_sample",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/Bynder/Sample/Bynder.Sample.csproj"
],
"problemMatcher": "$msCompile"
}
]
}
37 changes: 14 additions & 23 deletions Bynder/Sample/ApiSample.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Bynder. All rights reserved.
// Copyright (c) Bynder. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.

using System;
using System.Configuration;
using Bynder.Api;
using Bynder.Api.Queries;
Expand All @@ -9,31 +10,18 @@
namespace Bynder.Sample
{
/// <summary>
/// Class to show a little example on how to use the Bynder C# SDK. Before running this example is important that you fill
/// Class to show a little example on how to use the Bynder C# SDK. Before running this example is important that you fill
/// API_BASE_URL, CONSUMER_KEY and CONSUMER_SECRET in App.config
/// </summary>
public class ApiSample
{
/// <summary>
/// Waiting milliseconds until users login
/// </summary>
private const int LOGIN_WAITING_MILLISECONDS = 60000;

/// <summary>
/// Main function
/// </summary>
/// <param name="args">arguments to main</param>
public static void Main(string[] args)
{
using (var waitForToken = new WaitForToken())
using (IBynderApi bynderApi = BynderApiFactory.Create(new Settings
{
CONSUMER_KEY = ConfigurationManager.AppSettings["CONSUMER_KEY"],
CONSUMER_SECRET = ConfigurationManager.AppSettings["CONSUMER_SECRET"],
TOKEN = ConfigurationManager.AppSettings["TOKEN"],
TOKEN_SECRET = ConfigurationManager.AppSettings["TOKEN_SECRET"],
URL = ConfigurationManager.AppSettings["API_BASE_URL"]
}))
using (IBynderApi bynderApi = BynderApiFactory.Create(Settings.FromJson("Config.json")))
{
// We login using the browser. To do that we have to do the following:
// 1. Request temporary tokens
Expand All @@ -42,19 +30,21 @@ public static void Main(string[] args)
// 4. User logs in.
// 5. We request final access tokens.
bynderApi.GetRequestTokenAsync().Wait();
using (var listener = new OauthHttpListener("http://localhost:8891/", waitForToken))
string token = null;

using (var listener = new OauthHttpListener("http://localhost:8891/"))
{
using (var browser = new Browser(bynderApi.GetAuthorizeUrl("http://localhost:8891/"), null))
{
waitForToken.WaitHandle.WaitOne(LOGIN_WAITING_MILLISECONDS);
}
var browser = new Browser(bynderApi.GetAuthorizeUrl("http://localhost:8891/"));
var waitForToken = listener.WaitForToken();
waitForToken.Wait();
token = waitForToken.Result;
}

if (waitForToken.Success)
if (token != null)
{
bynderApi.GetAccessTokenAsync().Wait();

// Once the user has logged in we can start doing calls to asset bank manager to
// Once the user has logged in we can start doing calls to asset bank manager to
// get media information or upload new files.
var assetBankManager = bynderApi.GetAssetBankManager();

Expand All @@ -68,6 +58,7 @@ public static void Main(string[] args)
{
var media = assetBankManager.RequestMediaInfoAsync(new MediaInformationQuery { MediaId = mediaList[0].Id, Versions = 0 }).Result;
assetBankManager.UploadFileAsync(new UploadQuery { Filepath = @"Image/bynder-logo.png", BrandId = media.BrandId }).Wait();
Console.WriteLine("Uploaded file to Bynder");
}
}
}
Expand Down
13 changes: 0 additions & 13 deletions Bynder/Sample/App.config

This file was deleted.

11 changes: 7 additions & 4 deletions Bynder/Sample/Bynder.Sample.csproj
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net461</TargetFramework>
<TargetFramework>netcoreapp2.0</TargetFramework>
<AssemblyVersion>1.2.2.0</AssemblyVersion>
<FileVersion>1.2.2.0</FileVersion>
<Company>Bynder</Company>
<Product>Bynder.Sample</Product>
<Copyright>Copyright © Bynder</Copyright>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Configuration" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Api\Bynder.Api.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Image\bynder-logo.png">
<None Update="Config.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</EmbeddedResource>
</None>
<None Update="Image\bynder-logo.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
5 changes: 5 additions & 0 deletions Bynder/Sample/Config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"api_base_url": "",
"consumer_key": "",
"consumer_secret": ""
}
102 changes: 12 additions & 90 deletions Bynder/Sample/OauthUtils/Browser.cs
Original file line number Diff line number Diff line change
@@ -1,112 +1,34 @@
// Copyright (c) Bynder. All rights reserved.
// Copyright (c) Bynder. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.

using System;
using System;
using System.Diagnostics;
using Microsoft.Win32;
using System.Runtime.InteropServices;

namespace Bynder.Sample.OauthUtils
{
/// <summary>
/// Class to open the Browser with a specific Url. If default explorer is internet explorer
/// we will add -nomerge parameter so we can close it when login is successful.
/// For other browsers probably it will not be able to close it after a successful login.
/// Class to open the Browser with a specific Url.
/// </summary>
public sealed class Browser : IDisposable
public sealed class Browser
{
/// <summary>
/// Process information
/// </summary>
private readonly Process _proc;

/// <summary>
/// Creates an instance of browser that will create a process with the default browser pointing to
/// the Url passed.
/// Creates an instance of browser that will open the default browser pointing to the Url passed.
/// </summary>
/// <param name="url">Url we want to open the browser with</param>
/// <param name="waitForToken">token to notify if possible, if the user closes the browser</param>
public Browser(string url, WaitForToken waitForToken)
{
var browserPath = GetBrowserPath();
_proc = Process.Start(browserPath, GetBrowserArguments(browserPath, url));
if (waitForToken != null
&& _proc != null)
{
_proc.EnableRaisingEvents = true;
_proc.Exited += (sender, e) => waitForToken.WaitHandle.Set();
}
}

/// <summary>
/// Kills started process if possible.
/// </summary>
public void Dispose()
public Browser(string url)
{
if (_proc != null)
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_proc.Kill();
}
catch (InvalidOperationException)
{
// When openning browser for login, if explorer already opened this exception is thrown. Is not an error, so no action
return;
}
Process.Start(new ProcessStartInfo("cmd", $"/c start {url}"));
}
}

/// <summary>
/// Gets default browser path. http://stackoverflow.com/questions/13621467/how-to-find-default-web-browser-using-c
/// </summary>
/// <returns>default browser path</returns>
private static string GetBrowserPath()
{
string browser = string.Empty;
RegistryKey key = null;
try
{
key = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command");

// trim off quotes
if (key != null)
{
browser = key.GetValue(null).ToString().ToLower().Trim(new[] { '"' });
}

const string ExeExtension = ".exe";
if (!browser.EndsWith(ExeExtension))
{
// get rid of everything after the ".exe"
browser = browser.Substring(0, browser.LastIndexOf(ExeExtension, StringComparison.InvariantCultureIgnoreCase) + 4);
}
}
finally
{
if (key != null)
{
key.Close();
}
}

return browser;
}

/// <summary>
/// Gets the arguments to open the default browser with. In case the default browser is
/// iexplorer it adds the -nomerge argument so a new process is created and we can close it.
/// </summary>
/// <param name="browserPath">default browser path</param>
/// <param name="url">Url we want to open</param>
/// <returns>arguments string</returns>
private string GetBrowserArguments(string browserPath, string url)
{
if (browserPath.ToLower().Contains("iexplore.exe"))
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return $"-nomerge {url}";
Process.Start("open", url);
}

return url;
Console.WriteLine(string.Format("Open the url in your browser: {0}", url));
}
}
}
51 changes: 12 additions & 39 deletions Bynder/Sample/OauthUtils/OauthHttpListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Net;
using System.Threading.Tasks;

namespace Bynder.Sample.OauthUtils
{
Expand All @@ -18,24 +19,16 @@ public sealed class OauthHttpListener : IDisposable
private readonly HttpListener _listener;

/// <summary>
/// We use this class to notify waiting threads that a call with oauth_token is done
/// to the Url we are listening to.
/// </summary>
private readonly WaitForToken _waitForTokenHandle;

/// <summary>
/// Creates a new OauthHttpListener that will listen to the Url and will notify waiting threads
/// Creates a new OauthHttpListener that will listen to the Url and will notify waiting threads
/// when oauth login has completed
/// </summary>
/// <param name="url">Url we want to listen to</param>
/// <param name="waitForTokenHandle">instance to pass token back and to notify waiting threads</param>
public OauthHttpListener(string url, WaitForToken waitForTokenHandle)
public OauthHttpListener(string url)
{
_listener = new HttpListener();
_listener.Prefixes.Add(url);
_waitForTokenHandle = waitForTokenHandle;
_listener.Start();
_listener.BeginGetContext(new AsyncCallback(BeginContextCallback), _listener);
}

/// <summary>
Expand All @@ -47,41 +40,21 @@ public void Dispose()
}

/// <summary>
/// Function callback that is called when we start receiving data.
/// Function that waits utils we start receiving data.
/// We keep listening until we find oauth_token parameter in the Url.
/// </summary>
/// <param name="result">async result</param>
private void BeginContextCallback(IAsyncResult result)
public async Task<string> WaitForToken()
{
HttpListener listener = (HttpListener)result.AsyncState;

// Call EndGetContext to complete the asynchronous operation.
HttpListenerContext context;
try
{
context = listener.EndGetContext(result);
}
catch (ObjectDisposedException)
{
// When Close this method is called with disposed object. Just swallow the exception
return;
}

HttpListenerRequest request = context.Request;
string token = null;
HttpListenerContext context = null;

// Need to check if we are being requested with oauth_token. Because sometimes we
// Need to check if we are being requested with oauth_token. Because sometimes we
// would recieve the favicon call before, so we have to continue listening.
if (!request.RawUrl.Contains("oauth_token"))
{
_listener.BeginGetContext(new AsyncCallback(BeginContextCallback), _listener);
return;
}

var token = request.QueryString["oauth_token"];
_waitForTokenHandle.Success = token != null;
if (token != null)
while (token == null)
{
_waitForTokenHandle.Token = token;
context = await _listener.GetContextAsync();
token = context.Request.QueryString.Get("oauth_token");
}

// Obtain a response object.
Expand All @@ -92,7 +65,7 @@ private void BeginContextCallback(IAsyncResult result)
response.StatusCode = (int)HttpStatusCode.Redirect;
response.Close();

_waitForTokenHandle.WaitHandle.Set();
return token;
}
}
}

0 comments on commit 03bab2a

Please sign in to comment.