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

Update serialization to use System.Text.Json (#32) #34

Merged
merged 4 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,17 @@ $ cd duo_api_csharp
5. Open the Test Explorer window (Test > Test Explorer).
6. Run the unit tests by selecting on the top test and hitting the Run All button. There should be about 25 tests.
Visit Microsoft's ["Get started with unit testing page"](https://learn.microsoft.com/en-us/visualstudio/test/getting-started-with-unit-testing?view=vs-2022&tabs=dotnet%2Cmstest) for more information and help.


# Running the examples project

The example project (`examples/Examples.csproj`) connects to an Admin API instance and fetches some data to display to the command line. To run it, create a Duo Admin API instance following [these instructions](https://duo.com/docs/adminapi), making sure to enable Read permissions. Then, after building the example, you can invoke it using the command below, replacing the integration key, secret, and api hostname with the values for your API instance:

```
.\examples\bin\Debug\Examples.exe <IntegrationKey> <SecretKey> <API Hostname>
```

If successful, the command will output a summary of authentications performed against your account.

# Support

Report any bugs, feature requests, etc. to us directly:
Expand Down
22 changes: 16 additions & 6 deletions duo_api_csharp/Duo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Text;
using System.Web.Script.Serialization;
using System.Web;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;


using System.Text.Json;
using Duo.Extensions;

namespace Duo
{
public class DuoApi
Expand Down Expand Up @@ -386,11 +386,9 @@ private Dictionary<string, object> BaseJSONApiCall(string method,
HttpStatusCode statusCode;
string res = this.ApiCall(method, path, parameters, timeout, date, out statusCode);

var jss = new JavaScriptSerializer();

try
{
var dict = jss.Deserialize<Dictionary<string, object>>(res);
var dict = DeserializeJsonToMixedDictionary(res);
if (dict["stat"] as string == "OK")
{
return dict;
Expand Down Expand Up @@ -428,6 +426,18 @@ private Dictionary<string, object> BaseJSONApiCall(string method,
}
}

private Dictionary<string, object> DeserializeJsonToMixedDictionary(string json)
{
var sourceDict = JsonSerializer.Deserialize
<Dictionary<string, JsonElement>>(json);
var targetDict = new Dictionary<string, object>();
foreach (var kvp in sourceDict)
{
targetDict.Add(kvp.Key, kvp.Value.ConvertToObject());
}
return targetDict;
}

public T JSONApiCall<T>(string method,
string path,
Dictionary<string, string> parameters)
Expand Down
64 changes: 64 additions & 0 deletions duo_api_csharp/Extensions/JsonElementExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.Json;

namespace Duo.Extensions
{
internal static class JsonElementExtensions
{
/// <summary>
/// Converts a value contained within a System.Text.Json.JsonElement
/// into an object of the contained type
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
internal static object ConvertToObject(this JsonElement element)
{
switch (element.ValueKind)
{
case JsonValueKind.Undefined:
case JsonValueKind.Null:
return null;
case JsonValueKind.String:
return element.GetString();
case JsonValueKind.Number:
if (element.TryGetInt32(out int intValue))
{
return intValue;
}
if (element.TryGetInt64(out long longValue))
{
return longValue;
}
if (element.TryGetDecimal(out decimal decimalValue))
{
return decimalValue;
}
return element.GetDouble();
case JsonValueKind.True:
case JsonValueKind.False:
return element.GetBoolean();
case JsonValueKind.Object:
var sourceDict = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(element.GetRawText());
var targetDict = new Dictionary<string, object>();
foreach (var kvp in sourceDict)
{
targetDict.Add(kvp.Key, kvp.Value.ConvertToObject());
}
return targetDict;
case JsonValueKind.Array:
// ArrayList was returned by the older serializer, so make sure to keep the type
var list = new ArrayList();
foreach (var item in element.EnumerateArray())
{
list.Add(item.ConvertToObject());
}
return list;
default:
throw new InvalidOperationException("Unexpected JSON value kind: " + element.ValueKind);
}
}
}
}
40 changes: 39 additions & 1 deletion duo_api_csharp/duo_api_csharp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,40 @@
<RootNamespace>duo_api_csharp</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.6.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Text.Encodings.Web, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Encodings.Web.6.0.0\lib\net461\System.Text.Encodings.Web.dll</HintPath>
</Reference>
<Reference Include="System.Text.Json, Version=6.0.0.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Json.6.0.2\lib\net461\System.Text.Json.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Xml" />
Expand All @@ -48,13 +76,23 @@
<Compile Include="AssemblyInfo.cs" />
<Compile Include="CertificatePinnerFactory.cs" />
<Compile Include="Duo.cs" />
<Compile Include="Extensions\JsonElementExtensions.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="ca_certs.pem" />
</ItemGroup>
<ItemGroup />
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSHARP.Targets" />
<ProjectExtensions>
<VisualStudio AllowExistingFolder="true" />
</ProjectExtensions>
<Import Project="..\packages\System.Text.Json.6.0.2\build\System.Text.Json.targets" Condition="Exists('..\packages\System.Text.Json.6.0.2\build\System.Text.Json.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\System.Text.Json.6.0.2\build\System.Text.Json.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\System.Text.Json.6.0.2\build\System.Text.Json.targets'))" />
</Target>
</Project>
12 changes: 12 additions & 0 deletions duo_api_csharp/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bcl.AsyncInterfaces" version="6.0.0" targetFramework="net48" />
<package id="System.Buffers" version="4.5.1" targetFramework="net48" />
<package id="System.Memory" version="4.5.4" targetFramework="net48" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="6.0.0" targetFramework="net48" />
<package id="System.Text.Encodings.Web" version="6.0.0" targetFramework="net48" />
<package id="System.Text.Json" version="6.0.2" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net48" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net48" />
</packages>
Loading