Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.NET 8.0, Added Functionality #20

Open
wants to merge 21 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
46baec1
gitignore update
JackMBurch Dec 12, 2023
a69131e
.NET 8.0
JackMBurch Dec 15, 2023
96fb5a3
Update Readme.md
JackMBurch Dec 15, 2023
d4925c9
Initial .NET 8.0 commit, support for logging, support for storing req…
JackMBurch Dec 15, 2023
706d9e7
char strings
JackMBurch Dec 15, 2023
ae26e40
Updating constants to use environment variables for production vs san…
JackMBurch Dec 15, 2023
d7efc22
Changing console app project type to console app
JackMBurch Dec 15, 2023
8d21988
Console apps tested
JackMBurch Dec 15, 2023
e4cbd54
launchSettings files added with DIGIKEY_PRODUCTION envirnoment variables
JackMBurch Dec 15, 2023
af98193
Json menthods
JackMBurch Dec 15, 2023
8954f99
Update Readme.md
JackMBurch Dec 15, 2023
8b62a1c
Removed logger initialization logging
JackMBurch Dec 16, 2023
aaa3a67
DigiKey API Client restructured to allow scoped DB instances.
JackMBurch Dec 19, 2023
d5d8ab8
Update Readme.md
JackMBurch Dec 19, 2023
26b37a0
Dealing with "The configuration file has been changed by another prog…
JackMBurch Dec 27, 2023
b32d4c8
Fixing catch
JackMBurch Dec 27, 2023
9cdeb3f
Merge pull request #2 from JackMBurch/master
JackMBurch Dec 27, 2023
1632cc4
Authorization header corrected to "Bearer" instead of "Authorization"
JackMBurch Jan 3, 2024
03573f5
Merge pull request #3 from JackMBurch/development
JackMBurch Jan 3, 2024
6300579
Swapping from ConfigurationManager to XElement to avoid "The configur…
JackMBurch Jan 4, 2024
aa52049
Merge pull request #4 from JackMBurch/development
JackMBurch Jan 4, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -261,3 +261,8 @@ _ReSharper*/


/src/B2BApi.Bom.Api/B2BApi.Bom.Api.V3.xml
**/apiclient.config
launchsettings.json

*.nuspec
*.nupkg
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_2Legged_OAuth2Service.ConsoleApp</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
Expand Down
46 changes: 21 additions & 25 deletions 2Legged_OAuth2Service.ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,43 +1,36 @@
using System.Diagnostics;
using System.Net;
using System.Web;
using ApiClient.Extensions;
//-----------------------------------------------------------------------
//
// THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTIES OF ANY KIND, EXPRESS, IMPLIED, STATUTORY,
// OR OTHERWISE. EXPECT TO THE EXTENT PROHIBITED BY APPLICABLE LAW, DIGI-KEY DISCLAIMS ALL WARRANTIES,
// INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
// SATISFACTORY QUALITY, TITLE, NON-INFRINGEMENT, QUIET ENJOYMENT,
// AND WARRANTIES ARISING OUT OF ANY COURSE OF DEALING OR USAGE OF TRADE.
//
// DIGI-KEY DOES NOT WARRANT THAT THE SOFTWARE WILL FUNCTION AS DESCRIBED,
// WILL BE UNINTERRUPTED OR ERROR-FREE, OR FREE OF HARMFUL COMPONENTS.
//
//-----------------------------------------------------------------------

using ApiClient.Models;
using ApiClient.OAuth2.Models;

namespace _2Legged_OAuth2Service.ConsoleApp
{
public class Program
{
private ApiClientSettings? _clientSettings;

static void Main()
{
var program = new Program();

// Read configuration values from apiclient.config file and run OAuth2 code flow with OAuth2 Server
program.Authorize();

// This will keep the console window up until a key is press in the console window.
Console.WriteLine("\n\nPress any key to exit...");
Console.ReadKey();
}

/// <summary>
/// OAuth2 code flow authorization with apiclient.config values
/// </summary>
private async void Authorize()
static async Task Main()
{
// read clientSettings values from apiclient.config
_clientSettings = ApiClientSettings.CreateFromConfigFile();
ApiClientSettings? _clientSettings = ApiClientSettings.CreateFromConfigFile();
Console.WriteLine(_clientSettings.ToString());

var oAuth2Service = new ApiClient.OAuth2.OAuth2Service(_clientSettings);

var result = await oAuth2Service.Get2LeggedAccessToken();

// Check if you got an error during finishing the OAuth2 authorization
if (result.IsError)
if (result == null)
throw new Exception("Authorize result null");
else if (result.IsError)
{
Console.WriteLine("\n\nError : {0}", result.Error);
Console.WriteLine("\n\nError.Description: {0}", result.ErrorDescription);
Expand All @@ -54,6 +47,9 @@ private async void Authorize()
Console.WriteLine("After a good refresh");
Console.WriteLine(_clientSettings.ToString());
}
// This will keep the console window up until a key is press in the console window.
Console.WriteLine("\n\nPress any key to exit...");
Console.ReadKey();
}
}
}
10 changes: 10 additions & 0 deletions 2Legged_OAuth2Service.ConsoleApp/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"profiles": {
"2Legged_OAuth2Service.ConsoleApp": {
"commandName": "Project",
"environmentVariables": {
"DIGIKEY_PRODUCTION": "true"
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,16 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.3" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NLog" Version="5.1.3" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.1" />
</ItemGroup>

<ItemGroup>
<Folder Include="Properties\" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
53 changes: 18 additions & 35 deletions 3Legged_OAuth2Service.ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,39 +11,20 @@
//
//-----------------------------------------------------------------------

using System;
using ApiClient.Extensions;
using ApiClient.Models;
using System.Diagnostics;
using System.Net;
using System.Runtime.InteropServices;
using System.Web;
using ApiClient.Extensions;
using ApiClient.Models;

namespace OAuth2Service.ConsoleApp
{
public class Program
{
private ApiClientSettings? _clientSettings;

static void Main()
{
var prog = new Program();

// Read configuration values from apiclient.config file and run OAuth2 code flow with OAuth2 Server
prog.Authorize();

// This will keep the console window up until a key is press in the console window.
Console.WriteLine("\n\nPress any key to exit...");
Console.ReadKey();
}

/// <summary>
/// OAuth2 code flow authorization with apiclient.config values
/// </summary>
private async void Authorize()
static async Task Main()
{
// read clientSettings values from apiclient.config
_clientSettings = ApiClientSettings.CreateFromConfigFile();
ApiClientSettings? _clientSettings = ApiClientSettings.CreateFromConfigFile();
Console.WriteLine(_clientSettings.ToString());

// start up a HttpListener for the callback(RedirectUri) from the OAuth2 server
Expand All @@ -59,13 +40,13 @@ private async void Authorize()
var authUrl = oAuth2Service.GenerateAuthUrl(scopes);
authUrl = authUrl.Replace("&", "^&");
var psi = new ProcessStartInfo
{
FileName = "cmd",
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
CreateNoWindow = true,
Arguments = $"/c start {authUrl}"
};
{
FileName = "cmd",
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
CreateNoWindow = true,
Arguments = $"/c start {authUrl}"
};

// create Authorize url and send call it thru Process.Start
Process.Start(psi);
Expand All @@ -77,17 +58,15 @@ private async void Authorize()
httpListener.Stop();

// exact the query parameters from the returned URL
var queryString = context.Request.Url.Query;
var queryColl = HttpUtility.ParseQueryString(queryString);
var queryString = context.Request.Url?.Query;
var queryColl = HttpUtility.ParseQueryString(queryString!);

// Grab the needed query parameter code from the query collection
var code = queryColl["code"];
Console.WriteLine($"Using code {code}");

// Pass the returned code value to finish the OAuth2 authorization
var result = await oAuth2Service.FinishAuthorization(code);

// Check if you got an error during finishing the OAuth2 authorization
var result = await oAuth2Service.FinishAuthorization(code!) ?? throw new Exception("Authorize result null");
if (result.IsError)
{
Console.WriteLine("\n\nError : {0}", result.Error);
Expand All @@ -105,6 +84,10 @@ private async void Authorize()
Console.WriteLine("After a good refresh");
Console.WriteLine(_clientSettings.ToString());
}

// This will keep the console window up until a key is press in the console window.
Console.WriteLine("\n\nPress any key to exit...");
Console.ReadKey();
}
}
}
10 changes: 10 additions & 0 deletions 3Legged_OAuth2Service.ConsoleApp/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"profiles": {
"3Legged_OAuth2Service.ConsoleApp": {
"commandName": "Project",
"environmentVariables": {
"DIGIKEY_PRODUCTION": "true"
}
}
}
}
3 changes: 2 additions & 1 deletion ApiClient.ConsoleApp/ApiClient.ConsoleApp.csproj
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<OutputType>Exe</OutputType>
</PropertyGroup>

<ItemGroup>
Expand Down
60 changes: 22 additions & 38 deletions ApiClient.ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

using ApiClient.Models;
using ApiClient.OAuth2;
using ApiClient.OAuth2.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Expand All @@ -22,53 +21,38 @@ namespace ApiClient.ConsoleApp
public class Program
{
static async Task Main()
{
var prog = new Program();

await prog.CallKeywordSearch();

// This will keep the console window up until a key is pressed in the console window.
Console.WriteLine("\n\nPress any key to exit...");
Console.ReadKey();
}

private async Task CallKeywordSearch()
{
var settings = ApiClientSettings.CreateFromConfigFile();
Console.WriteLine(settings.ToString());
try
if (settings.ExpirationDateTime < DateTime.Now)
{
if (settings.ExpirationDateTime < DateTime.Now)
// Let's refresh the token
var oAuth2Service = new OAuth2Service(settings);
var oAuth2AccessToken = await oAuth2Service.RefreshTokenAsync();
if (oAuth2AccessToken.IsError)
{
// Let's refresh the token
var oAuth2Service = new OAuth2Service(settings);
var oAuth2AccessToken = await oAuth2Service.RefreshTokenAsync();
if (oAuth2AccessToken.IsError)
{
// Current Refresh token is invalid or expired
Console.WriteLine("Current Refresh token is invalid or expired ");
return;
}
// Current Refresh token is invalid or expired
Console.WriteLine("Current Refresh token is invalid or expired ");
return;
}

settings.UpdateAndSave(oAuth2AccessToken);
settings.UpdateAndSave(oAuth2AccessToken);

Console.WriteLine("After call to refresh");
Console.WriteLine(settings.ToString());
}
Console.WriteLine("After call to refresh");
Console.WriteLine(settings.ToString());
}

var client = new ApiClientService(settings);
var response = await client.KeywordSearch("P5555-ND");
var client = new ApiClientService(settings);
var response = await client.ProductInformation.KeywordSearch("P5555-ND");

// In order to pretty print the json object we need to do the following
var jsonFormatted = JToken.Parse(response).ToString(Formatting.Indented);
// In order to pretty print the json object we need to do the following
var jsonFormatted = JToken.Parse(response).ToString(Formatting.Indented);

Console.WriteLine($"Reponse is {jsonFormatted} ");
}
catch (System.Exception e)
{
Console.WriteLine(e);
throw;
}
Console.WriteLine($"Reponse is {jsonFormatted} ");

// This will keep the console window up until a key is pressed in the console window.
Console.WriteLine("\n\nPress any key to exit...");
Console.ReadKey();
}
}
}
10 changes: 10 additions & 0 deletions ApiClient.ConsoleApp/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"profiles": {
"ApiClient.ConsoleApp": {
"commandName": "Project",
"environmentVariables": {
"DIGIKEY_PRODUCTION": "true"
}
}
}
}
2 changes: 1 addition & 1 deletion ApiClient.sln
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiClient", "ApiClient\ApiC
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{560625EF-E3D3-4CC0-85D6-94E70A9131A5}"
ProjectSection(SolutionItems) = preProject
apiclient.config = apiclient.config
Readme.md = Readme.md
sample-apiclient.config = sample-apiclient.config
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "2Legged_OAuth2Service.ConsoleApp", "2Legged_OAuth2Service.ConsoleApp\2Legged_OAuth2Service.ConsoleApp.csproj", "{B43EB828-423A-4A23-8768-5C35AD5F047B}"
Expand Down
Loading