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

Clientmodel review samples #12

Open
wants to merge 9 commits into
base: clientmodel-type-renames-5
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Net.ClientModel.Core;
using System.Text.Json;

namespace Maps;

public class CountryRegion : IJsonModel<CountryRegion>
{
internal CountryRegion(string isoCode)
{
IsoCode = isoCode;
}

public string IsoCode { get; }

internal static CountryRegion FromJson(JsonElement element)
{
if (element.ValueKind == JsonValueKind.Null)
{
return null;
}

string isoCode = default;

foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("isoCode"u8))
{
isoCode = property.Value.GetString();
continue;
}
}

return new CountryRegion(isoCode);
}

public CountryRegion Read(ref Utf8JsonReader reader, ModelReaderWriterOptions options)
{
using var document = JsonDocument.ParseValue(ref reader);
return FromJson(document.RootElement);
}

public CountryRegion Read(BinaryData data, ModelReaderWriterOptions options)
{
using var document = JsonDocument.Parse(data.ToString());
return FromJson(document.RootElement);
}

public void Write(Utf8JsonWriter writer, ModelReaderWriterOptions options)
{
throw new NotSupportedException("This model is used for output only");
}

public BinaryData Write(ModelReaderWriterOptions options)
{
throw new NotSupportedException("This model is used for output only");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Net;
using System.Net.ClientModel.Core;
using System.Text.Json;

namespace Maps;

public class IPAddressCountryPair : IJsonModel<IPAddressCountryPair>
{
internal IPAddressCountryPair(CountryRegion countryRegion, IPAddress ipAddress)
{
CountryRegion = countryRegion;
IpAddress = ipAddress;
}

public CountryRegion CountryRegion { get; }

public IPAddress IpAddress { get; }

internal static IPAddressCountryPair FromJson(JsonElement element)
{
if (element.ValueKind == JsonValueKind.Null)
{
return null;
}

CountryRegion countryRegion = default;
IPAddress ipAddress = default;

foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("countryRegion"u8))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}

countryRegion = CountryRegion.FromJson(property.Value);
continue;
}

if (property.NameEquals("ipAddress"u8))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}

ipAddress = IPAddress.Parse(property.Value.GetString());
continue;
}
}

return new IPAddressCountryPair(countryRegion, ipAddress);
}

internal static IPAddressCountryPair FromResponse(PipelineResponse response)
{
using var document = JsonDocument.Parse(response.Content);
return FromJson(document.RootElement);
}

public IPAddressCountryPair Read(ref Utf8JsonReader reader, ModelReaderWriterOptions options)
{
using var document = JsonDocument.ParseValue(ref reader);
return FromJson(document.RootElement);
}

public IPAddressCountryPair Read(BinaryData data, ModelReaderWriterOptions options)
{
using var document = JsonDocument.Parse(data.ToString());
return FromJson(document.RootElement);
}

public void Write(Utf8JsonWriter writer, ModelReaderWriterOptions options)
{
throw new NotSupportedException("This model is used for output only");
}

public BinaryData Write(ModelReaderWriterOptions options)
{
throw new NotSupportedException("This model is used for output only");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Net;
using System.Net.ClientModel;
using System.Net.ClientModel.Core;
using System.Text;
using System.Threading;

namespace Maps;

public class MapsClient
{
private readonly Uri _endpoint;
private readonly KeyCredential _credential;
private readonly MessagePipeline _pipeline;
private readonly string _apiVersion;

public MapsClient(Uri endpoint, KeyCredential credential, MapsClientOptions options = default)
{
if (endpoint is null) throw new ArgumentNullException(nameof(endpoint));
if (credential is null) throw new ArgumentNullException(nameof(credential));

options ??= new MapsClientOptions();

_endpoint = endpoint;
_credential = credential;
_pipeline = MessagePipeline.Create(options, new KeyCredentialAuthenticationPolicy(_credential, "subscription-key"));
_apiVersion = options.Version;
}

public virtual Result<IPAddressCountryPair> GetCountryCode(IPAddress ipAddress, CancellationToken cancellationToken = default)
{
if (ipAddress is null) throw new ArgumentNullException(nameof(ipAddress));

RequestOptions options = cancellationToken.CanBeCanceled ?
new RequestOptions() { CancellationToken = cancellationToken } :
new RequestOptions();

Result result = GetCountryCode(ipAddress.ToString(), options);

PipelineResponse response = result.GetRawResponse();
IPAddressCountryPair value = IPAddressCountryPair.FromResponse(response);

return Result.FromValue(value, response);
}

public virtual Result GetCountryCode(string ipAddress, RequestOptions options = null)
{
if (ipAddress is null) throw new ArgumentNullException(nameof(ipAddress));

options ??= new RequestOptions();
options.MessageClassifier = MessageClassifier200;

using PipelineMessage message = CreateGetLocationRequest(ipAddress, options);

_pipeline.Send(message);

PipelineResponse response = message.Response;

if (response.IsError && options.ErrorBehavior == ErrorBehavior.Default)
{
throw new UnsuccessfulRequestException(response);
}

return Result.FromResponse(response);
}

private PipelineMessage CreateGetLocationRequest(string ipAddress, RequestOptions options)
{
PipelineMessage message = _pipeline.CreateMessage();
options.Apply(message);

PipelineRequest request = message.Request;
request.Method = "GET";

UriBuilder uriBuilder = new(_endpoint.ToString());

StringBuilder path = new();
path.Append("geolocation/ip");
path.Append("/json");
uriBuilder.Path += path.ToString();

StringBuilder query = new();
query.Append("api-version=");
query.Append(Uri.EscapeDataString(_apiVersion));
query.Append("&ip=");
query.Append(Uri.EscapeDataString(ipAddress));
uriBuilder.Query = query.ToString();

request.Uri = uriBuilder.Uri;

request.Headers.Add("Accept", "application/json");

return message;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Net.ClientModel;

namespace Maps;

public class MapsClientOptions : RequestOptions
{
private const ServiceVersion LatestVersion = ServiceVersion.V1;

public enum ServiceVersion
{
V1 = 1
}

internal string Version { get; }

internal Uri Endpoint { get; }

public MapsClientOptions(ServiceVersion version = LatestVersion)
{
Version = version switch
{
ServiceVersion.V1 => "1.0",
_ => throw new NotSupportedException()
};
}
}
28 changes: 28 additions & 0 deletions sdk/core/System.Net.ClientModel/tests/client/MapsClientTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using NUnit.Framework;
using Maps;

namespace System.Net.ClientModel.Tests;

public class MapsClientTests
{
// This is a "TestSupportProject", so these tests will never be run as part of CIs.
// It's here now for quick manual validation of client functionality, but we can revisit
// this story going forward.
[Test]
public void TestClientSync()
{
string key = Environment.GetEnvironmentVariable("MAPS_API_KEY");

KeyCredential credential = new KeyCredential(key);
MapsClient client = new MapsClient(new Uri("https://atlas.microsoft.com"), credential);

IPAddress ipAddress = IPAddress.Parse("2001:4898:80e8:b::189");
Result<IPAddressCountryPair> result = client.GetCountryCode(ipAddress);

Assert.AreEqual("US", result.Value.CountryRegion.IsoCode);
Assert.AreEqual(IPAddress.Parse("2001:4898:80e8:b::189"), result.Value.IpAddress);
}
}
43 changes: 43 additions & 0 deletions sdk/maps/Azure.Maps.Geolocation/Azure.Maps.Geolocation.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.2.32526.322
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Maps.Geolocation", "src\Azure.Maps.Geolocation.csproj", "{7DCCA8AB-B7D4-491A-BDCC-FB64DE686FE7}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Maps.Geolocation.Tests", "tests\Azure.Maps.Geolocation.Tests.csproj", "{3A87F8D0-5D67-4886-8F0C-64E688B02DF4}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core.TestFramework", "..\..\core\Azure.Core.TestFramework\src\Azure.Core.TestFramework.csproj", "{9CF40117-7082-4DA2-87E5-48A0EE167391}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestHarness", "TestHarness\TestHarness.csproj", "{CE0A1047-7FAA-4837-86B0-4A2B6156E511}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7DCCA8AB-B7D4-491A-BDCC-FB64DE686FE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7DCCA8AB-B7D4-491A-BDCC-FB64DE686FE7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7DCCA8AB-B7D4-491A-BDCC-FB64DE686FE7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7DCCA8AB-B7D4-491A-BDCC-FB64DE686FE7}.Release|Any CPU.Build.0 = Release|Any CPU
{3A87F8D0-5D67-4886-8F0C-64E688B02DF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3A87F8D0-5D67-4886-8F0C-64E688B02DF4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3A87F8D0-5D67-4886-8F0C-64E688B02DF4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3A87F8D0-5D67-4886-8F0C-64E688B02DF4}.Release|Any CPU.Build.0 = Release|Any CPU
{9CF40117-7082-4DA2-87E5-48A0EE167391}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9CF40117-7082-4DA2-87E5-48A0EE167391}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9CF40117-7082-4DA2-87E5-48A0EE167391}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9CF40117-7082-4DA2-87E5-48A0EE167391}.Release|Any CPU.Build.0 = Release|Any CPU
{CE0A1047-7FAA-4837-86B0-4A2B6156E511}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CE0A1047-7FAA-4837-86B0-4A2B6156E511}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CE0A1047-7FAA-4837-86B0-4A2B6156E511}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CE0A1047-7FAA-4837-86B0-4A2B6156E511}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {122670A6-DDC3-4993-85DB-C594DCCD1AA5}
EndGlobalSection
EndGlobal
17 changes: 17 additions & 0 deletions sdk/maps/Azure.Maps.Geolocation/TestHarness/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System.Net;
using Azure;
using Azure.Maps.Geolocation;
using NUnit.Framework;

// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");


string key = Environment.GetEnvironmentVariable("AZURE_MAPS_API_KEY");
AzureKeyCredential credential = new AzureKeyCredential(key);
MapsGeolocationClient client = new MapsGeolocationClient(credential);
IPAddress ipAddress = IPAddress.Parse("2001:4898:80e8:b::189");
CountryRegionResult result = client.GetCountryCode(ipAddress);


Assert.AreEqual("US", result.IsoCode);
18 changes: 18 additions & 0 deletions sdk/maps/Azure.Maps.Geolocation/TestHarness/TestHarness.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<!--<Nullable>enable</Nullable>-->
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NUnit" Version="3.13.2" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\src\Azure.Maps.Geolocation.csproj" />
</ItemGroup>

</Project>
Loading