From fb25b1b2e3dc9adb1ca74b5e99f9a0c25418eb36 Mon Sep 17 00:00:00 2001 From: mcgallan <88413158+mcgallan@users.noreply.github.com> Date: Thu, 17 Oct 2024 10:42:17 +0800 Subject: [PATCH] Add Lro\Rpc Test (#5108) * update * Update rpc.cs * regenrate * Update rpc.cs --- eng/testProjects.json | 1 + .../Properties/launchSettings.json | 4 + test/CadlRanchProjects.Tests/lro/rpc.cs | 36 + .../azure/core/lro/rpc/Configuration.json | 11 + .../azure/core/lro/rpc/_Azure.Lro.Rpc.sln | 50 ++ .../AzureLroRpcClientBuilderExtensions.cs | 35 + .../src/Generated/AzureLroRpcModelFactory.cs | 23 + .../lro/rpc/src/Generated/Docs/RpcClient.xml | 105 +++ .../rpc/src/Generated/Internal/Argument.cs | 129 +++ .../Internal/ModelSerializationExtensions.cs | 398 +++++++++ .../Internal/Utf8JsonRequestContent.cs | 55 ++ .../Models/GenerationOptions.Serialization.cs | 136 ++++ .../src/Generated/Models/GenerationOptions.cs | 75 ++ .../Models/GenerationResult.Serialization.cs | 136 ++++ .../src/Generated/Models/GenerationResult.cs | 75 ++ .../core/lro/rpc/src/Generated/RpcClient.cs | 201 +++++ .../lro/rpc/src/Generated/RpcClientOptions.cs | 37 + .../lro/rpc/src/Properties/AssemblyInfo.cs | 6 + .../core/lro/rpc/src/_Azure.Lro.Rpc.csproj | 19 + .../Generated/Samples/Samples_RpcClient.cs | 133 +++ .../lro/rpc/tests/_Azure.Lro.Rpc.Tests.csproj | 19 + .../azure/core/lro/rpc/tspCodeModel.json | 764 ++++++++++++++++++ .../azure/core/lro/rpc/tspconfig.yaml | 3 + 23 files changed, 2451 insertions(+) create mode 100644 test/CadlRanchProjects.Tests/lro/rpc.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/Configuration.json create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/_Azure.Lro.Rpc.sln create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/AzureLroRpcClientBuilderExtensions.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/AzureLroRpcModelFactory.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Docs/RpcClient.xml create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Internal/Argument.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Internal/ModelSerializationExtensions.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Internal/Utf8JsonRequestContent.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationOptions.Serialization.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationOptions.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationResult.Serialization.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationResult.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/RpcClient.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/RpcClientOptions.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/Properties/AssemblyInfo.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/src/_Azure.Lro.Rpc.csproj create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/tests/Generated/Samples/Samples_RpcClient.cs create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/tests/_Azure.Lro.Rpc.Tests.csproj create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/tspCodeModel.json create mode 100644 test/CadlRanchProjects/azure/core/lro/rpc/tspconfig.yaml diff --git a/eng/testProjects.json b/eng/testProjects.json index 9f251c77961..31ec6201254 100644 --- a/eng/testProjects.json +++ b/eng/testProjects.json @@ -24,6 +24,7 @@ "azure/resource-manager/models/resources", "azure/core/basic", "azure/core/lro/standard", + "azure/core/lro/rpc", "azure/core/scalar", "azure/core/traits", "azure/core/model", diff --git a/src/AutoRest.CSharp/Properties/launchSettings.json b/src/AutoRest.CSharp/Properties/launchSettings.json index a05a1a3e4b0..ac93e7f93b6 100644 --- a/src/AutoRest.CSharp/Properties/launchSettings.json +++ b/src/AutoRest.CSharp/Properties/launchSettings.json @@ -628,6 +628,10 @@ "commandName": "Project", "commandLineArgs": "--standalone $(SolutionDir)\\test\\CadlRanchProjects\\azure\\core\\basic\\src\\Generated -n" }, + "typespec-azure/core/lro/rpc": { + "commandName": "Project", + "commandLineArgs": "--standalone $(SolutionDir)\\test\\CadlRanchProjects\\azure\\core\\lro\\rpc\\src\\Generated -n" + }, "typespec-azure/core/lro/standard": { "commandName": "Project", "commandLineArgs": "--standalone $(SolutionDir)\\test\\CadlRanchProjects\\azure\\core\\lro\\standard\\src\\Generated -n" diff --git a/test/CadlRanchProjects.Tests/lro/rpc.cs b/test/CadlRanchProjects.Tests/lro/rpc.cs new file mode 100644 index 00000000000..a68949ee68f --- /dev/null +++ b/test/CadlRanchProjects.Tests/lro/rpc.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Threading.Tasks; +using _Azure.Lro.Rpc; +using _Azure.Lro.Rpc.Models; +using AutoRest.TestServer.Tests.Infrastructure; +using Azure; +using NUnit.Framework; + +namespace CadlRanchProjects.Tests.lro +{ + public class LongRunningOperation : CadlRanchTestBase + { + [Test] + public Task LongRunningRpc_Completed() => Test(async (host) => + { + var option = new GenerationOptions("text"); + var response = await new RpcClient(host, null).LongRunningRpcAsync(WaitUntil.Completed, option); + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual("text data", response.Value.Data); + }); + + [Test] + public Task LongRunningRpc_Started() => Test(async (host) => + { + var option = new GenerationOptions("text"); + var response = await new RpcClient(host, null).LongRunningRpcAsync(WaitUntil.Started, option); + Assert.AreEqual(202, response.GetRawResponse().Status); + Assert.AreEqual(true, response.GetRawResponse().Headers.TryGetValue("operation-location", out string operationLocation)); + Assert.AreEqual(true, operationLocation.Contains("/azure/core/lro/rpc/generations/operations/operation1")); + }); + + + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/Configuration.json b/test/CadlRanchProjects/azure/core/lro/rpc/Configuration.json new file mode 100644 index 00000000000..753ddc4b1ad --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/Configuration.json @@ -0,0 +1,11 @@ +{ + "output-folder": ".", + "namespace": "_Azure.Lro.Rpc", + "library-name": "_Azure.Lro.Rpc", + "flavor": "azure", + "use-model-reader-writer": true, + "shared-source-folders": [ + "../../../../../../../../artifacts/bin/AutoRest.CSharp/Debug/net8.0/Generator.Shared", + "../../../../../../../../artifacts/bin/AutoRest.CSharp/Debug/net8.0/Azure.Core.Shared" + ] +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/_Azure.Lro.Rpc.sln b/test/CadlRanchProjects/azure/core/lro/rpc/_Azure.Lro.Rpc.sln new file mode 100644 index 00000000000..427bd06ce10 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/_Azure.Lro.Rpc.sln @@ -0,0 +1,50 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "_Azure.Lro.Rpc", "src\_Azure.Lro.Rpc.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "_Azure.Lro.Rpc.Tests", "tests\_Azure.Lro.Rpc.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.Build.0 = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.Build.0 = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.Build.0 = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.Build.0 = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.Build.0 = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.Build.0 = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A97F4B90-2591-4689-B1F8-5F21FE6D6CAE} + EndGlobalSection +EndGlobal diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/AzureLroRpcClientBuilderExtensions.cs b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/AzureLroRpcClientBuilderExtensions.cs new file mode 100644 index 00000000000..139cbb3a4a0 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/AzureLroRpcClientBuilderExtensions.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core.Extensions; +using _Azure.Lro.Rpc; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class AzureLroRpcClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// The to use. + public static IAzureClientBuilder AddRpcClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilder + { + return builder.RegisterClientFactory((options) => new RpcClient(endpoint, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddRpcClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/AzureLroRpcModelFactory.cs b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/AzureLroRpcModelFactory.cs new file mode 100644 index 00000000000..c5c6bb1d385 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/AzureLroRpcModelFactory.cs @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using Azure; + +namespace _Azure.Lro.Rpc.Models +{ + /// Model factory for models. + public static partial class AzureLroRpcModelFactory + { + /// Initializes a new instance of . + /// The data. + /// A new instance for mocking. + public static GenerationResult GenerationResult(string data = null) + { + return new GenerationResult(data, serializedAdditionalRawData: null); + } + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Docs/RpcClient.xml b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Docs/RpcClient.xml new file mode 100644 index 00000000000..91d42f77e95 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Docs/RpcClient.xml @@ -0,0 +1,105 @@ + + + + + +This sample shows how to call LongRunningRpcAsync. +"); +Operation operation = await client.LongRunningRpcAsync(WaitUntil.Completed, body); +GenerationResult responseData = operation.Value; +]]> +This sample shows how to call LongRunningRpcAsync with all parameters. +"); +Operation operation = await client.LongRunningRpcAsync(WaitUntil.Completed, body); +GenerationResult responseData = operation.Value; +]]> + + + +This sample shows how to call LongRunningRpc. +"); +Operation operation = client.LongRunningRpc(WaitUntil.Completed, body); +GenerationResult responseData = operation.Value; +]]> +This sample shows how to call LongRunningRpc with all parameters. +"); +Operation operation = client.LongRunningRpc(WaitUntil.Completed, body); +GenerationResult responseData = operation.Value; +]]> + + + +This sample shows how to call LongRunningRpcAsync and parse the result. +", +}); +Operation operation = await client.LongRunningRpcAsync(WaitUntil.Completed, content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.GetProperty("data").ToString()); +]]> +This sample shows how to call LongRunningRpcAsync with all parameters and request content and parse the result. +", +}); +Operation operation = await client.LongRunningRpcAsync(WaitUntil.Completed, content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.GetProperty("data").ToString()); +]]> + + + +This sample shows how to call LongRunningRpc and parse the result. +", +}); +Operation operation = client.LongRunningRpc(WaitUntil.Completed, content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.GetProperty("data").ToString()); +]]> +This sample shows how to call LongRunningRpc with all parameters and request content and parse the result. +", +}); +Operation operation = client.LongRunningRpc(WaitUntil.Completed, content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.GetProperty("data").ToString()); +]]> + + + \ No newline at end of file diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Internal/Argument.cs b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Internal/Argument.cs new file mode 100644 index 00000000000..67deb5edc84 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace _Azure.Lro.Rpc +{ + internal static class Argument + { + public static void AssertNotNull(T value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNull(T? value, string name) + where T : struct + { + if (!value.HasValue) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNullOrEmpty(IEnumerable value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value is ICollection collectionOfT && collectionOfT.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + if (value is ICollection collection && collection.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + using IEnumerator e = value.GetEnumerator(); + if (!e.MoveNext()) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + } + + public static void AssertNotNullOrEmpty(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value.Length == 0) + { + throw new ArgumentException("Value cannot be an empty string.", name); + } + } + + public static void AssertNotNullOrWhiteSpace(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name); + } + } + + public static void AssertNotDefault(ref T value, string name) + where T : struct, IEquatable + { + if (value.Equals(default)) + { + throw new ArgumentException("Value cannot be empty.", name); + } + } + + public static void AssertInRange(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (minimum.CompareTo(value) > 0) + { + throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); + } + if (maximum.CompareTo(value) < 0) + { + throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); + } + } + + public static void AssertEnumDefined(Type enumType, object value, string name) + { + if (!Enum.IsDefined(enumType, value)) + { + throw new ArgumentException($"Value not defined for {enumType.FullName}.", name); + } + } + + public static T CheckNotNull(T value, string name) + where T : class + { + AssertNotNull(value, name); + return value; + } + + public static string CheckNotNullOrEmpty(string value, string name) + { + AssertNotNullOrEmpty(value, name); + return value; + } + + public static void AssertNull(T value, string name, string message = null) + { + if (value != null) + { + throw new ArgumentException(message ?? "Value must be null.", name); + } + } + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Internal/ModelSerializationExtensions.cs b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 00000000000..cd4f7012d78 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,398 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Xml; +using Azure.Core; + +namespace _Azure.Lro.Rpc +{ + internal static class ModelSerializationExtensions + { + internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); + + public static object GetObject(this JsonElement element) + { + switch (element.ValueKind) + { + 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; + } + return element.GetDouble(); + case JsonValueKind.True: + return true; + case JsonValueKind.False: + return false; + case JsonValueKind.Undefined: + case JsonValueKind.Null: + return null; + case JsonValueKind.Object: + var dictionary = new Dictionary(); + foreach (var jsonProperty in element.EnumerateObject()) + { + dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); + } + return dictionary; + case JsonValueKind.Array: + var list = new List(); + foreach (var item in element.EnumerateArray()) + { + list.Add(item.GetObject()); + } + return list.ToArray(); + default: + throw new NotSupportedException($"Not supported value kind {element.ValueKind}"); + } + } + + public static byte[] GetBytesFromBase64(this JsonElement element, string format) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + + return format switch + { + "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()), + "D" => element.GetBytesFromBase64(), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + } + + public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch + { + "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()), + _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format) + }; + + public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format); + + public static char GetChar(this JsonElement element) + { + if (element.ValueKind == JsonValueKind.String) + { + var text = element.GetString(); + if (text == null || text.Length != 1) + { + throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); + } + return text[0]; + } + else + { + throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char"); + } + } + + [Conditional("DEBUG")] + public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) + { + throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); + } + + public static string GetRequiredString(this JsonElement element) + { + var value = element.GetString(); + if (value == null) + { + throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); + } + return value; + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, char value) + { + writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + + public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + switch (format) + { + case "U": + writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value)); + break; + case "D": + writer.WriteBase64StringValue(value); + break; + default: + throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)); + } + } + + public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + if (format != "U") + { + throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number."); + } + writer.WriteNumberValue(value.ToUnixTimeSeconds()); + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) + { + switch (value) + { + case null: + writer.WriteNullValue(); + break; + case IJsonModel jsonModel: + jsonModel.Write(writer, options ?? WireOptions); + break; + case IUtf8JsonSerializable serializable: + serializable.Write(writer); + break; + case byte[] bytes: + writer.WriteBase64StringValue(bytes); + break; + case BinaryData bytes0: + writer.WriteBase64StringValue(bytes0); + break; + case JsonElement json: + json.WriteTo(writer); + break; + case int i: + writer.WriteNumberValue(i); + break; + case decimal d: + writer.WriteNumberValue(d); + break; + case double d0: + if (double.IsNaN(d0)) + { + writer.WriteStringValue("NaN"); + } + else + { + writer.WriteNumberValue(d0); + } + break; + case float f: + writer.WriteNumberValue(f); + break; + case long l: + writer.WriteNumberValue(l); + break; + case string s: + writer.WriteStringValue(s); + break; + case bool b: + writer.WriteBooleanValue(b); + break; + case Guid g: + writer.WriteStringValue(g); + break; + case DateTimeOffset dateTimeOffset: + writer.WriteStringValue(dateTimeOffset, "O"); + break; + case DateTime dateTime: + writer.WriteStringValue(dateTime, "O"); + break; + case IEnumerable> enumerable: + writer.WriteStartObject(); + foreach (var pair in enumerable) + { + writer.WritePropertyName(pair.Key); + writer.WriteObjectValue(pair.Value, options); + } + writer.WriteEndObject(); + break; + case IEnumerable objectEnumerable: + writer.WriteStartArray(); + foreach (var item in objectEnumerable) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + break; + case TimeSpan timeSpan: + writer.WriteStringValue(timeSpan, "P"); + break; + default: + throw new NotSupportedException($"Not supported type {value.GetType()}"); + } + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) + { + writer.WriteObjectValue(value, options); + } + + internal static class TypeFormatters + { + private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; + public const string DefaultNumberFormat = "G"; + + public static string ToString(bool value) => value ? "true" : "false"; + + public static string ToString(DateTime value, string format) => value.Kind switch + { + DateTimeKind.Utc => ToString((DateTimeOffset)value, format), + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") + }; + + public static string ToString(DateTimeOffset value, string format) => format switch + { + "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "R" => value.ToString("r", CultureInfo.InvariantCulture), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(TimeSpan value, string format) => format switch + { + "P" => XmlConvert.ToString(value), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(byte[] value, string format) => format switch + { + "U" => ToBase64UrlString(value), + "D" => Convert.ToBase64String(value), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + + public static string ToBase64UrlString(byte[] value) + { + int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; + int size = checked(numWholeOrPartialInputBlocks * 4); + char[] output = new char[size]; + + int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); + + int i = 0; + for (; i < numBase64Chars; i++) + { + char ch = output[i]; + if (ch == '+') + { + output[i] = '-'; + } + else + { + if (ch == '/') + { + output[i] = '_'; + } + else + { + if (ch == '=') + { + break; + } + } + } + } + + return new string(output, 0, i); + } + + public static byte[] FromBase64UrlString(string value) + { + int paddingCharsToAdd = (value.Length % 4) switch + { + 0 => 0, + 2 => 2, + 3 => 1, + _ => throw new InvalidOperationException("Malformed input") + }; + char[] output = new char[(value.Length + paddingCharsToAdd)]; + int i = 0; + for (; i < value.Length; i++) + { + char ch = value[i]; + if (ch == '-') + { + output[i] = '+'; + } + else + { + if (ch == '_') + { + output[i] = '/'; + } + else + { + output[i] = ch; + } + } + } + + for (; i < output.Length; i++) + { + output[i] = '='; + } + + return Convert.FromBase64CharArray(output, 0, output.Length); + } + + public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch + { + "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), + _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) + }; + + public static TimeSpan ParseTimeSpan(string value, string format) => format switch + { + "P" => XmlConvert.ToTimeSpan(value), + _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) + }; + + public static string ConvertToString(object value, string format = null) => value switch + { + null => "null", + string s => s, + bool b => ToString(b), + int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), + byte[] b0 when format != null => ToString(b0, format), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when format != null => ToString(dateTime, format), + TimeSpan timeSpan when format != null => ToString(timeSpan, format), + TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; + } + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Internal/Utf8JsonRequestContent.cs b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 00000000000..cb223dee383 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace _Azure.Lro.Rpc +{ + internal class Utf8JsonRequestContent : RequestContent + { + private readonly MemoryStream _stream; + private readonly RequestContent _content; + + public Utf8JsonRequestContent() + { + _stream = new MemoryStream(); + _content = Create(_stream); + JsonWriter = new Utf8JsonWriter(_stream); + } + + public Utf8JsonWriter JsonWriter { get; } + + public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) + { + await JsonWriter.FlushAsync().ConfigureAwait(false); + await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); + } + + public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) + { + JsonWriter.Flush(); + _content.WriteTo(stream, cancellationToken); + } + + public override bool TryComputeLength(out long length) + { + length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; + return true; + } + + public override void Dispose() + { + JsonWriter.Dispose(); + _content.Dispose(); + _stream.Dispose(); + } + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationOptions.Serialization.cs b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationOptions.Serialization.cs new file mode 100644 index 00000000000..2b7dbc7078c --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationOptions.Serialization.cs @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace _Azure.Lro.Rpc.Models +{ + public partial class GenerationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(GenerationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("prompt"u8); + writer.WriteStringValue(Prompt); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + GenerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(GenerationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeGenerationOptions(document.RootElement, options); + } + + internal static GenerationOptions DeserializeGenerationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string prompt = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("prompt"u8)) + { + prompt = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new GenerationOptions(prompt, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(GenerationOptions)} does not support writing '{options.Format}' format."); + } + } + + GenerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeGenerationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(GenerationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static GenerationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeGenerationOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationOptions.cs b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationOptions.cs new file mode 100644 index 00000000000..fb7e7514341 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationOptions.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace _Azure.Lro.Rpc.Models +{ + /// Options for the generation. + public partial class GenerationOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Prompt. + /// is null. + public GenerationOptions(string prompt) + { + Argument.AssertNotNull(prompt, nameof(prompt)); + + Prompt = prompt; + } + + /// Initializes a new instance of . + /// Prompt. + /// Keeps track of any properties unknown to the library. + internal GenerationOptions(string prompt, IDictionary serializedAdditionalRawData) + { + Prompt = prompt; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal GenerationOptions() + { + } + + /// Prompt. + public string Prompt { get; } + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationResult.Serialization.cs b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationResult.Serialization.cs new file mode 100644 index 00000000000..fc10e796177 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationResult.Serialization.cs @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace _Azure.Lro.Rpc.Models +{ + public partial class GenerationResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(GenerationResult)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("data"u8); + writer.WriteStringValue(Data); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + writer.WriteEndObject(); + } + + GenerationResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(GenerationResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeGenerationResult(document.RootElement, options); + } + + internal static GenerationResult DeserializeGenerationResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string data = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("data"u8)) + { + data = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new GenerationResult(data, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(GenerationResult)} does not support writing '{options.Format}' format."); + } + } + + GenerationResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeGenerationResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(GenerationResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static GenerationResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeGenerationResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationResult.cs b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationResult.cs new file mode 100644 index 00000000000..41c5763b4a2 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/Models/GenerationResult.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace _Azure.Lro.Rpc.Models +{ + /// Result of the generation. + public partial class GenerationResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The data. + /// is null. + internal GenerationResult(string data) + { + Argument.AssertNotNull(data, nameof(data)); + + Data = data; + } + + /// Initializes a new instance of . + /// The data. + /// Keeps track of any properties unknown to the library. + internal GenerationResult(string data, IDictionary serializedAdditionalRawData) + { + Data = data; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal GenerationResult() + { + } + + /// The data. + public string Data { get; } + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/RpcClient.cs b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/RpcClient.cs new file mode 100644 index 00000000000..1ece15a93fc --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/RpcClient.cs @@ -0,0 +1,201 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; +using _Azure.Lro.Rpc.Models; + +namespace _Azure.Lro.Rpc +{ + // Data plane generated client. + /// Illustrates bodies templated with Azure Core with long-running RPC operation. + public partial class RpcClient + { + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of RpcClient. + public RpcClient() : this(new Uri("http://localhost:3000"), new RpcClientOptions()) + { + } + + /// Initializes a new instance of RpcClient. + /// The to use. + /// The options for configuring the client. + /// is null. + public RpcClient(Uri endpoint, RpcClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + options ??= new RpcClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), Array.Empty(), new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// Generate data. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The body parameter. + /// The cancellation token to use. + /// is null. + /// + public virtual async Task> LongRunningRpcAsync(WaitUntil waitUntil, GenerationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = await LongRunningRpcAsync(waitUntil, content, context).ConfigureAwait(false); + return ProtocolOperationHelpers.Convert(response, FetchGenerationResultFromOperationStatusGenerationResultError, ClientDiagnostics, "RpcClient.LongRunningRpc"); + } + + /// Generate data. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The body parameter. + /// The cancellation token to use. + /// is null. + /// + public virtual Operation LongRunningRpc(WaitUntil waitUntil, GenerationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = LongRunningRpc(waitUntil, content, context); + return ProtocolOperationHelpers.Convert(response, FetchGenerationResultFromOperationStatusGenerationResultError, ClientDiagnostics, "RpcClient.LongRunningRpc"); + } + + /// + /// [Protocol Method] Generate data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual async Task> LongRunningRpcAsync(WaitUntil waitUntil, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("RpcClient.LongRunningRpc"); + scope.Start(); + try + { + using HttpMessage message = CreateLongRunningRpcRequest(content, context); + return await ProtocolOperationHelpers.ProcessMessageAsync(_pipeline, message, ClientDiagnostics, "RpcClient.LongRunningRpc", OperationFinalStateVia.OperationLocation, context, waitUntil).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Generate data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual Operation LongRunningRpc(WaitUntil waitUntil, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("RpcClient.LongRunningRpc"); + scope.Start(); + try + { + using HttpMessage message = CreateLongRunningRpcRequest(content, context); + return ProtocolOperationHelpers.ProcessMessage(_pipeline, message, ClientDiagnostics, "RpcClient.LongRunningRpc", OperationFinalStateVia.OperationLocation, context, waitUntil); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateLongRunningRpcRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier202); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/azure/core/lro/rpc/generations:submit", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier202; + private static ResponseClassifier ResponseClassifier202 => _responseClassifier202 ??= new StatusCodeClassifier(stackalloc ushort[] { 202 }); + + private GenerationResult FetchGenerationResultFromOperationStatusGenerationResultError(Response response) + { + var resultJsonElement = JsonDocument.Parse(response.Content).RootElement.GetProperty("result"); + return GenerationResult.DeserializeGenerationResult(resultJsonElement); + } + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/RpcClientOptions.cs b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/RpcClientOptions.cs new file mode 100644 index 00000000000..8f6ace545cc --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Generated/RpcClientOptions.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace _Azure.Lro.Rpc +{ + /// Client options for RpcClient. + public partial class RpcClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2022_12_01_Preview; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2022-12-01-preview". + V2022_12_01_Preview = 1, + } + + internal string Version { get; } + + /// Initializes new instance of RpcClientOptions. + public RpcClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2022_12_01_Preview => "2022-12-01-preview", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/Properties/AssemblyInfo.cs b/test/CadlRanchProjects/azure/core/lro/rpc/src/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..92c1b5234b7 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("_Azure.Lro.Rpc.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/src/_Azure.Lro.Rpc.csproj b/test/CadlRanchProjects/azure/core/lro/rpc/src/_Azure.Lro.Rpc.csproj new file mode 100644 index 00000000000..3703d1b352f --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/src/_Azure.Lro.Rpc.csproj @@ -0,0 +1,19 @@ + + + This is the _Azure.Lro.Rpc client library for developing .NET applications with rich experience. + Azure SDK Code Generation _Azure.Lro.Rpc for Azure Data Plane + 1.0.0-beta.1 + _Azure.Lro.Rpc + $(RequiredTargetFrameworks) + true + + + + + + + + + + + diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/tests/Generated/Samples/Samples_RpcClient.cs b/test/CadlRanchProjects/azure/core/lro/rpc/tests/Generated/Samples/Samples_RpcClient.cs new file mode 100644 index 00000000000..0aa36d6cae3 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/tests/Generated/Samples/Samples_RpcClient.cs @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; +using _Azure.Lro.Rpc.Models; + +namespace _Azure.Lro.Rpc.Samples +{ + public partial class Samples_RpcClient + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Rpc_LongRunningRpc_ShortVersion() + { + RpcClient client = new RpcClient(); + + using RequestContent content = RequestContent.Create(new + { + prompt = "", + }); + Operation operation = client.LongRunningRpc(WaitUntil.Completed, content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("data").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Rpc_LongRunningRpc_ShortVersion_Async() + { + RpcClient client = new RpcClient(); + + using RequestContent content = RequestContent.Create(new + { + prompt = "", + }); + Operation operation = await client.LongRunningRpcAsync(WaitUntil.Completed, content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("data").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Rpc_LongRunningRpc_ShortVersion_Convenience() + { + RpcClient client = new RpcClient(); + + GenerationOptions body = new GenerationOptions(""); + Operation operation = client.LongRunningRpc(WaitUntil.Completed, body); + GenerationResult responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Rpc_LongRunningRpc_ShortVersion_Convenience_Async() + { + RpcClient client = new RpcClient(); + + GenerationOptions body = new GenerationOptions(""); + Operation operation = await client.LongRunningRpcAsync(WaitUntil.Completed, body); + GenerationResult responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Rpc_LongRunningRpc_AllParameters() + { + RpcClient client = new RpcClient(); + + using RequestContent content = RequestContent.Create(new + { + prompt = "", + }); + Operation operation = client.LongRunningRpc(WaitUntil.Completed, content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("data").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Rpc_LongRunningRpc_AllParameters_Async() + { + RpcClient client = new RpcClient(); + + using RequestContent content = RequestContent.Create(new + { + prompt = "", + }); + Operation operation = await client.LongRunningRpcAsync(WaitUntil.Completed, content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("data").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Rpc_LongRunningRpc_AllParameters_Convenience() + { + RpcClient client = new RpcClient(); + + GenerationOptions body = new GenerationOptions(""); + Operation operation = client.LongRunningRpc(WaitUntil.Completed, body); + GenerationResult responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Rpc_LongRunningRpc_AllParameters_Convenience_Async() + { + RpcClient client = new RpcClient(); + + GenerationOptions body = new GenerationOptions(""); + Operation operation = await client.LongRunningRpcAsync(WaitUntil.Completed, body); + GenerationResult responseData = operation.Value; + } + } +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/tests/_Azure.Lro.Rpc.Tests.csproj b/test/CadlRanchProjects/azure/core/lro/rpc/tests/_Azure.Lro.Rpc.Tests.csproj new file mode 100644 index 00000000000..4bdab8d9e6b --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/tests/_Azure.Lro.Rpc.Tests.csproj @@ -0,0 +1,19 @@ + + + $(RequiredTargetFrameworks) + + $(NoWarn);CS1591 + + + + + + + + + + + + + + diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/tspCodeModel.json b/test/CadlRanchProjects/azure/core/lro/rpc/tspCodeModel.json new file mode 100644 index 00000000000..fc9bf9d5800 --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/tspCodeModel.json @@ -0,0 +1,764 @@ +{ + "$id": "1", + "Name": "_Specs_.Azure.Core.Lro.Rpc", + "ApiVersions": [ + "2022-12-01-preview" + ], + "Enums": [ + { + "$id": "2", + "kind": "enum", + "name": "Versions", + "crossLanguageDefinitionId": "_Specs_.Azure.Core.Lro.Rpc.Versions", + "valueType": { + "$id": "3", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "4", + "kind": "enumvalue", + "name": "v2022_12_01_preview", + "value": "2022-12-01-preview", + "valueType": { + "$id": "5", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "2" + }, + "description": "The 2022-12-01-preview version.", + "decorators": [] + } + ], + "description": "The API version.", + "isFixed": true, + "isFlags": false, + "usage": "ApiVersionEnum", + "decorators": [] + }, + { + "$id": "6", + "kind": "enum", + "name": "OperationState", + "crossLanguageDefinitionId": "Azure.Core.Foundations.OperationState", + "valueType": { + "$id": "7", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "8", + "kind": "enumvalue", + "name": "NotStarted", + "value": "NotStarted", + "valueType": { + "$id": "9", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "6" + }, + "description": "The operation has not started.", + "decorators": [] + }, + { + "$id": "10", + "kind": "enumvalue", + "name": "Running", + "value": "Running", + "valueType": { + "$id": "11", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "6" + }, + "description": "The operation is in progress.", + "decorators": [] + }, + { + "$id": "12", + "kind": "enumvalue", + "name": "Succeeded", + "value": "Succeeded", + "valueType": { + "$id": "13", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "6" + }, + "description": "The operation has completed successfully.", + "decorators": [] + }, + { + "$id": "14", + "kind": "enumvalue", + "name": "Failed", + "value": "Failed", + "valueType": { + "$id": "15", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "6" + }, + "description": "The operation has failed.", + "decorators": [] + }, + { + "$id": "16", + "kind": "enumvalue", + "name": "Canceled", + "value": "Canceled", + "valueType": { + "$id": "17", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "6" + }, + "description": "The operation has been canceled by the user.", + "decorators": [] + } + ], + "description": "Enum describing allowed operation states.", + "isFixed": false, + "isFlags": false, + "usage": "Output,Json", + "decorators": [] + } + ], + "Models": [ + { + "$id": "18", + "kind": "model", + "name": "GenerationOptions", + "crossLanguageDefinitionId": "_Specs_.Azure.Core.Lro.Rpc.GenerationOptions", + "usage": "Input,Json", + "description": "Options for the generation.", + "decorators": [], + "properties": [ + { + "$id": "19", + "kind": "property", + "name": "prompt", + "serializedName": "prompt", + "description": "Prompt.", + "type": { + "$id": "20", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "_Specs_.Azure.Core.Lro.Rpc.GenerationOptions.prompt" + } + ] + }, + { + "$id": "21", + "kind": "model", + "name": "GenerationResult", + "crossLanguageDefinitionId": "_Specs_.Azure.Core.Lro.Rpc.GenerationResult", + "usage": "Output,Json", + "description": "Result of the generation.", + "decorators": [], + "properties": [ + { + "$id": "22", + "kind": "property", + "name": "data", + "serializedName": "data", + "description": "The data.", + "type": { + "$id": "23", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "_Specs_.Azure.Core.Lro.Rpc.GenerationResult.data" + } + ] + }, + { + "$id": "24", + "kind": "model", + "name": "ResourceOperationStatusGenerationResponseGenerationResultError", + "crossLanguageDefinitionId": "Azure.Core.ResourceOperationStatus", + "usage": "Output,Json", + "description": "Provides status details for long running operations.", + "decorators": [], + "properties": [ + { + "$id": "25", + "kind": "property", + "name": "id", + "serializedName": "id", + "description": "The unique ID of the operation.", + "type": { + "$id": "26", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.ResourceOperationStatus.id" + }, + { + "$id": "27", + "kind": "property", + "name": "status", + "serializedName": "status", + "description": "The status of the operation", + "type": { + "$ref": "6" + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.ResourceOperationStatus.status" + }, + { + "$id": "28", + "kind": "property", + "name": "error", + "serializedName": "error", + "description": "Error object that describes the error when status is \"Failed\".", + "type": { + "$id": "29", + "kind": "model", + "name": "Error", + "crossLanguageDefinitionId": "Azure.Core.Foundations.Error", + "usage": "Output,Json", + "description": "The error object.", + "decorators": [], + "properties": [ + { + "$id": "30", + "kind": "property", + "name": "code", + "serializedName": "code", + "description": "One of a server-defined set of error codes.", + "type": { + "$id": "31", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.Error.code" + }, + { + "$id": "32", + "kind": "property", + "name": "message", + "serializedName": "message", + "description": "A human-readable representation of the error.", + "type": { + "$id": "33", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.Error.message" + }, + { + "$id": "34", + "kind": "property", + "name": "target", + "serializedName": "target", + "description": "The target of the error.", + "type": { + "$id": "35", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.Error.target" + }, + { + "$id": "36", + "kind": "property", + "name": "details", + "serializedName": "details", + "description": "An array of details about specific errors that led to this reported error.", + "type": { + "$id": "37", + "kind": "array", + "name": "ArrayError", + "valueType": { + "$ref": "29" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.Error.details" + }, + { + "$id": "38", + "kind": "property", + "name": "innererror", + "serializedName": "innererror", + "description": "An object containing more specific information than the current object about the error.", + "type": { + "$id": "39", + "kind": "model", + "name": "InnerError", + "crossLanguageDefinitionId": "Azure.Core.Foundations.InnerError", + "usage": "Output,Json", + "description": "An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses.", + "decorators": [], + "properties": [ + { + "$id": "40", + "kind": "property", + "name": "code", + "serializedName": "code", + "description": "One of a server-defined set of error codes.", + "type": { + "$id": "41", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.InnerError.code" + }, + { + "$id": "42", + "kind": "property", + "name": "innererror", + "serializedName": "innererror", + "description": "Inner error.", + "type": { + "$ref": "39" + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.InnerError.innererror" + } + ] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.Error.innererror" + } + ] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.ResourceOperationStatus.error" + }, + { + "$id": "43", + "kind": "property", + "name": "result", + "serializedName": "result", + "description": "The result of the operation.", + "type": { + "$ref": "21" + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.ResourceOperationStatus.result" + } + ] + }, + { + "$ref": "29" + }, + { + "$ref": "39" + }, + { + "$id": "44", + "kind": "model", + "name": "OperationStatusGenerationResultError", + "crossLanguageDefinitionId": "Azure.Core.Foundations.OperationStatus", + "usage": "Output", + "description": "Provides status details for long running operations.", + "decorators": [], + "properties": [ + { + "$id": "45", + "kind": "property", + "name": "id", + "serializedName": "id", + "description": "The unique ID of the operation.", + "type": { + "$id": "46", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.OperationStatus.id" + }, + { + "$id": "47", + "kind": "property", + "name": "status", + "serializedName": "status", + "description": "The status of the operation", + "type": { + "$ref": "6" + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.OperationStatus.status" + }, + { + "$id": "48", + "kind": "property", + "name": "error", + "serializedName": "error", + "description": "Error object that describes the error when status is \"Failed\".", + "type": { + "$ref": "29" + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.OperationStatus.error" + }, + { + "$id": "49", + "kind": "property", + "name": "result", + "serializedName": "result", + "description": "The result of the operation.", + "type": { + "$ref": "21" + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.OperationStatus.result" + } + ] + } + ], + "Clients": [ + { + "$id": "50", + "Name": "RpcClient", + "Description": "Illustrates bodies templated with Azure Core with long-running RPC operation", + "Operations": [ + { + "$id": "51", + "Name": "longRunningRpc", + "ResourceName": "Rpc", + "Summary": "Generate data.", + "Description": "Generate data.", + "Accessibility": "public", + "Parameters": [ + { + "$id": "52", + "Name": "endpoint", + "NameInRequest": "endpoint", + "Type": { + "$id": "53", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url" + }, + "Location": "Uri", + "IsApiVersion": false, + "IsResourceParameter": false, + "IsContentType": false, + "IsRequired": true, + "IsEndpoint": true, + "SkipUrlEncoding": false, + "Explode": false, + "Kind": "Client", + "DefaultValue": { + "$id": "54", + "Type": { + "$id": "55", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "Value": "http://localhost:3000" + } + }, + { + "$id": "56", + "Name": "apiVersion", + "NameInRequest": "api-version", + "Description": "The API version to use for this operation.", + "Type": { + "$id": "57", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "Location": "Query", + "IsApiVersion": true, + "IsContentType": false, + "IsEndpoint": false, + "Explode": false, + "IsRequired": true, + "Kind": "Client", + "DefaultValue": { + "$id": "58", + "Type": { + "$id": "59", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "Value": "2022-12-01-preview" + }, + "Decorators": [], + "SkipUrlEncoding": false + }, + { + "$id": "60", + "Name": "contentType", + "NameInRequest": "Content-Type", + "Description": "Body parameter's content type. Known values are application/json", + "Type": { + "$id": "61", + "kind": "constant", + "valueType": { + "$id": "62", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "Location": "Header", + "IsApiVersion": false, + "IsContentType": true, + "IsEndpoint": false, + "Explode": false, + "IsRequired": true, + "Kind": "Constant", + "Decorators": [], + "SkipUrlEncoding": false + }, + { + "$id": "63", + "Name": "accept", + "NameInRequest": "Accept", + "Type": { + "$id": "64", + "kind": "constant", + "valueType": { + "$id": "65", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "Location": "Header", + "IsApiVersion": false, + "IsContentType": false, + "IsEndpoint": false, + "Explode": false, + "IsRequired": true, + "Kind": "Constant", + "Decorators": [], + "SkipUrlEncoding": false + }, + { + "$id": "66", + "Name": "body", + "NameInRequest": "body", + "Description": "The body parameter.", + "Type": { + "$ref": "18" + }, + "Location": "Body", + "IsApiVersion": false, + "IsContentType": false, + "IsEndpoint": false, + "Explode": false, + "IsRequired": true, + "Kind": "Method", + "Decorators": [], + "SkipUrlEncoding": false + } + ], + "Responses": [ + { + "$id": "67", + "StatusCodes": [ + 202 + ], + "BodyType": { + "$ref": "24" + }, + "BodyMediaType": "Json", + "Headers": [ + { + "$id": "68", + "Name": "operationLocation", + "NameInResponse": "Operation-Location", + "Description": "The location for monitoring the operation state.", + "Type": { + "$id": "69", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "70", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "decorators": [] + } + } + ], + "IsErrorResponse": false, + "ContentTypes": [ + "application/json" + ] + } + ], + "HttpMethod": "POST", + "RequestBodyMediaType": "Json", + "Uri": "{endpoint}", + "Path": "/azure/core/lro/rpc/generations:submit", + "RequestMediaTypes": [ + "application/json" + ], + "BufferResponse": true, + "LongRunning": { + "$id": "71", + "FinalStateVia": 3, + "FinalResponse": { + "$id": "72", + "StatusCodes": [ + 200 + ], + "BodyType": { + "$ref": "44" + }, + "BodyMediaType": "Json" + }, + "ResultPath": "result" + }, + "GenerateProtocolMethod": true, + "GenerateConvenienceMethod": true, + "CrossLanguageDefinitionId": "_Specs_.Azure.Core.Lro.Rpc.longRunningRpc", + "Decorators": [] + } + ], + "Protocol": { + "$id": "73" + }, + "Parameters": [ + { + "$ref": "52" + } + ], + "Decorators": [] + } + ] +} diff --git a/test/CadlRanchProjects/azure/core/lro/rpc/tspconfig.yaml b/test/CadlRanchProjects/azure/core/lro/rpc/tspconfig.yaml new file mode 100644 index 00000000000..3efc4d90f4e --- /dev/null +++ b/test/CadlRanchProjects/azure/core/lro/rpc/tspconfig.yaml @@ -0,0 +1,3 @@ +options: + "@azure-tools/typespec-csharp": + namespace: _Azure.Lro.Rpc