From 83ef6a0d46890f7fc5a0a12afe09c2d7a4767fd1 Mon Sep 17 00:00:00 2001 From: mcgallan <88413158+mcgallan@users.noreply.github.com> Date: Thu, 26 Sep 2024 14:27:20 +0800 Subject: [PATCH] Add Cadl Ranch Test In New Version 0.37.2 (#5065) * generate * update * Update azure-tcgc-usage.cs * rpc generate * Update rpc.cs * regen * basic * regen * remove * update * update * Update resource-manager-models-resources.cs * regen * Numeric Test * ConditionalRequest Test * Update package-lock.json * update * Update testProjects.json --- eng/testProjects.json | 1 + .../Properties/launchSettings.json | 4 + .../azure-core-basic.cs | 11 + .../azure-tcgc-usage.cs | 6 + .../CadlRanchProjects.Tests/encode-numeric.cs | 43 ++ .../resource-manager-models-resources.cs | 72 +++ .../special-headers/conditional-request.cs | 22 + .../encode/numeric/Configuration.json | 11 + .../encode/numeric/Encode.Numeric.sln | 50 ++ .../encode/numeric/src/Encode.Numeric.csproj | 19 + .../numeric/src/Generated/Docs/Property.xml | 281 ++++++++++ .../EncodeNumericClientBuilderExtensions.cs | 35 ++ .../src/Generated/Internal/Argument.cs | 129 +++++ .../Internal/ChangeTrackingDictionary.cs | 167 ++++++ .../Generated/Internal/ChangeTrackingList.cs | 153 ++++++ .../Internal/ModelSerializationExtensions.cs | 398 ++++++++++++++ .../src/Generated/Internal/Optional.cs | 51 ++ .../Internal/Utf8JsonRequestContent.cs | 55 ++ .../SafeintAsStringProperty.Serialization.cs | 136 +++++ .../Models/SafeintAsStringProperty.cs | 72 +++ .../Uint32AsStringProperty.Serialization.cs | 143 +++++ .../Models/Uint32AsStringProperty.cs | 65 +++ .../Uint8AsStringProperty.Serialization.cs | 136 +++++ .../Generated/Models/Uint8AsStringProperty.cs | 72 +++ .../numeric/src/Generated/NumericClient.cs | 55 ++ .../src/Generated/NumericClientOptions.cs | 16 + .../encode/numeric/src/Generated/Property.cs | 430 +++++++++++++++ .../numeric/src/Properties/AssemblyInfo.cs | 6 + .../numeric/tests/Encode.Numeric.Tests.csproj | 19 + .../Generated/Samples/Samples_Property.cs | 333 +++++++++++ .../encode/numeric/tspCodeModel.json | 518 ++++++++++++++++++ 31 files changed, 3509 insertions(+) create mode 100644 test/CadlRanchProjects.Tests/encode-numeric.cs create mode 100644 test/CadlRanchProjects/encode/numeric/Configuration.json create mode 100644 test/CadlRanchProjects/encode/numeric/Encode.Numeric.sln create mode 100644 test/CadlRanchProjects/encode/numeric/src/Encode.Numeric.csproj create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Docs/Property.xml create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/EncodeNumericClientBuilderExtensions.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Internal/Argument.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Internal/ChangeTrackingDictionary.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Internal/ChangeTrackingList.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Internal/ModelSerializationExtensions.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Internal/Optional.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Internal/Utf8JsonRequestContent.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Models/SafeintAsStringProperty.Serialization.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Models/SafeintAsStringProperty.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint32AsStringProperty.Serialization.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint32AsStringProperty.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint8AsStringProperty.Serialization.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint8AsStringProperty.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/NumericClient.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/NumericClientOptions.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Generated/Property.cs create mode 100644 test/CadlRanchProjects/encode/numeric/src/Properties/AssemblyInfo.cs create mode 100644 test/CadlRanchProjects/encode/numeric/tests/Encode.Numeric.Tests.csproj create mode 100644 test/CadlRanchProjects/encode/numeric/tests/Generated/Samples/Samples_Property.cs create mode 100644 test/CadlRanchProjects/encode/numeric/tspCodeModel.json diff --git a/eng/testProjects.json b/eng/testProjects.json index ef671d9400f..9ff944a4f35 100644 --- a/eng/testProjects.json +++ b/eng/testProjects.json @@ -36,6 +36,7 @@ "encode/bytes", "encode/datetime", "encode/duration", + "encode/numeric", "payload/content-negotiation", "payload/media-type", "payload/multipart", diff --git a/src/AutoRest.CSharp/Properties/launchSettings.json b/src/AutoRest.CSharp/Properties/launchSettings.json index 6a8ded8c0a8..4276f589ef5 100644 --- a/src/AutoRest.CSharp/Properties/launchSettings.json +++ b/src/AutoRest.CSharp/Properties/launchSettings.json @@ -696,6 +696,10 @@ "commandName": "Project", "commandLineArgs": "--standalone $(SolutionDir)\\test\\CadlRanchProjects\\encode\\duration\\src\\Generated -n" }, + "typespec-encode/numeric": { + "commandName": "Project", + "commandLineArgs": "--standalone $(SolutionDir)\\test\\CadlRanchProjects\\encode\\numeric\\src\\Generated -n" + }, "typespec-nonAzure-authentication/api-key": { "commandName": "Project", "commandLineArgs": "--standalone $(SolutionDir)\\test\\CadlRanchProjectsNonAzure\\authentication\\api-key\\src\\Generated -n" diff --git a/test/CadlRanchProjects.Tests/azure-core-basic.cs b/test/CadlRanchProjects.Tests/azure-core-basic.cs index 2a66ab8d0aa..dfe0092005b 100644 --- a/test/CadlRanchProjects.Tests/azure-core-basic.cs +++ b/test/CadlRanchProjects.Tests/azure-core-basic.cs @@ -81,6 +81,17 @@ public Task Azure_Core_Basic_export() => Test(async (host) => Assert.AreEqual("Madge", response.Name); }); + [Test] + public Task Azure_Core_Basic_exoportAllUsers() => Test(async (host) => + { + var response = await new BasicClient(host, null).ExportAllUsersAsync("json"); + Assert.AreEqual(1, response.Value.Users.First().Id); + Assert.AreEqual("Madge", response.Value.Users.First().Name); + Assert.AreEqual(2, response.Value.Users.Last().Id); + Assert.AreEqual("John", response.Value.Users.Last().Name); + Assert.AreEqual(2, response.Value.Users.Count()); + }); + [Test] public void Azure_Core_basic_RenameGetMethod() { diff --git a/test/CadlRanchProjects.Tests/azure-tcgc-usage.cs b/test/CadlRanchProjects.Tests/azure-tcgc-usage.cs index 8da0d1cc7fa..f2802a9ce66 100644 --- a/test/CadlRanchProjects.Tests/azure-tcgc-usage.cs +++ b/test/CadlRanchProjects.Tests/azure-tcgc-usage.cs @@ -19,11 +19,17 @@ public Task Azure_ClientGenerator_Core_Usage_ModelInOperation() => Test(async (h var response2 = await new UsageClient(host, null).GetModelInOperationClient().OutputToInputOutputAsync(); Assert.AreEqual("Madge", response2.Value.Name); + var response3 = await new UsageClient(host, null).GetModelInOperationClient().ModelInReadOnlyPropertyAsync(new RoundTripModel()); + Assert.AreEqual("Madge", response3.Value.Result.Name); + Assert.IsNotNull(typeof(InputModel).GetMethod("FromResponse", BindingFlags.Static | BindingFlags.NonPublic)); Assert.IsNotNull(typeof(InputModel).GetMethod("ToRequestContent", BindingFlags.Instance | BindingFlags.NonPublic)); Assert.IsNotNull(typeof(OutputModel).GetMethod("FromResponse", BindingFlags.Static | BindingFlags.NonPublic)); Assert.IsNotNull(typeof(OutputModel).GetMethod("ToRequestContent", BindingFlags.Instance | BindingFlags.NonPublic)); + + Assert.IsNotNull(typeof(RoundTripModel).GetMethod("FromResponse", BindingFlags.Static | BindingFlags.NonPublic)); + Assert.IsNotNull(typeof(RoundTripModel).GetMethod("ToRequestContent", BindingFlags.Instance | BindingFlags.NonPublic)); }); } } diff --git a/test/CadlRanchProjects.Tests/encode-numeric.cs b/test/CadlRanchProjects.Tests/encode-numeric.cs new file mode 100644 index 00000000000..eb911315491 --- /dev/null +++ b/test/CadlRanchProjects.Tests/encode-numeric.cs @@ -0,0 +1,43 @@ +using System; +using System.Text.Json; +using System.Threading.Tasks; +using AutoRest.TestServer.Tests.Infrastructure; +using Azure; +using Azure.Core; +using Encode.Numeric; +using Encode.Numeric.Models; +using NUnit.Framework; + + +namespace CadlRanchProjects.Tests +{ + public class encode_numeric : CadlRanchTestBase + { + [Test] + public Task Encode_Numeric_Property_safeintAsString() => Test(async (host) => + { + var response = await new NumericClient(host, null).GetPropertyClient().SafeintAsStringAsync(new SafeintAsStringProperty(10000000000)); + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(10000000000, response.Value.Value); + }); + + [Test] + public Task Encode_Numeric_Property_uint32AsStringOptional() => Test(async (host) => + { + var response = await new NumericClient(host, null).GetPropertyClient().Uint32AsStringOptionalAsync(new Uint32AsStringProperty() + { + Value = "1" + }); + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual("1", response.Value.Value); + }); + + [Test] + public Task Encode_Numeric_Property_uint8AsString() => Test(async (host) => + { + var response = await new NumericClient(host, null).GetPropertyClient().Uint8AsStringAsync(new Uint8AsStringProperty(255)); + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(255, response.Value.Value); + }); + } +} diff --git a/test/CadlRanchProjects.Tests/resource-manager-models-resources.cs b/test/CadlRanchProjects.Tests/resource-manager-models-resources.cs index e0b09660385..3b1a4ff5b5f 100644 --- a/test/CadlRanchProjects.Tests/resource-manager-models-resources.cs +++ b/test/CadlRanchProjects.Tests/resource-manager-models-resources.cs @@ -32,6 +32,14 @@ public Task Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_get( Assert.AreEqual(CreatedByType.User, response.Value.Data.SystemData.LastModifiedByType); }); + [Test] + public Task Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_actionSync() => Test(async (host) => + { + var id = TopLevelTrackedResource.CreateResourceIdentifier(Guid.Empty.ToString(), "test-rg", "top"); + var response = await MgmtTestHelper.CreateArmClientWithMockAuth(host).GetTopLevelTrackedResource(id).ActionSyncAsync(new NotificationDetails("Resource action at top level.", true)); + Assert.AreEqual(204, response.Status); + }); + [Test] [Ignore("https://github.com/Azure/autorest.csharp/issues/4876")] public Task Azure_ResourceManager_Models_Resources_TopLevelTrackedResources_createOrReplace() => Test(async (host) => @@ -218,5 +226,69 @@ public Task Azure_ResourceManager_Models_Resources_NestedProxyResources_listByTo Assert.AreEqual("AzureSDK", response.Value.Data.SystemData.LastModifiedBy); Assert.AreEqual(CreatedByType.User, response.Value.Data.SystemData.LastModifiedByType); }); + + [Test] + [Ignore("https://github.com/Azure/autorest.csharp/issues/4876")] + public Task Azure_ResourceManager_Models_Resources_SingletonTrackedResource_createOrUpdate() => Test(async (host) => + { + var id = SingletonTrackedResource.CreateResourceIdentifier(Guid.Empty.ToString(), "test-rg"); + var data = new SingletonTrackedResourceData(AzureLocation.EastUS) + { + Properties = new SingletonTrackedResourceProperties() + { + Description = "valid" + } + }; + var response = await MgmtTestHelper.CreateArmClientWithMockAuth(host).GetSingletonTrackedResource(id).CreateOrUpdateAsync(WaitUntil.Completed, data); + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(true, response.Value.HasData); + Assert.AreEqual("Azure.ResourceManager.Models.Resources/singletonTrackedResources", response.Value.Data.ResourceType.ToString()); + Assert.AreEqual("valid", response.Value.Data.Properties.Description); + Assert.AreEqual(ProvisioningState.Succeeded, response.Value.Data.Properties.ProvisioningState); + Assert.AreEqual("AzureSDK", response.Value.Data.SystemData.CreatedBy); + Assert.AreEqual(CreatedByType.User, response.Value.Data.SystemData.CreatedByType); + Assert.AreEqual("AzureSDK", response.Value.Data.SystemData.LastModifiedBy); + Assert.AreEqual(CreatedByType.User, response.Value.Data.SystemData.LastModifiedByType); + }); + + [Test] + [Ignore("https://github.com/Azure/autorest.csharp/issues/4876")] + public Task Azure_ResourceManager_Models_Resources_SingletonTrackedResource_update() => Test(async (host) => + { + var id = SingletonTrackedResource.CreateResourceIdentifier(Guid.Empty.ToString(), "test-rg"); + var data = new SingletonTrackedResourceData(AzureLocation.EastUS2) + { + Properties = new SingletonTrackedResourceProperties() + { + Description = "valid2" + } + }; + var response = await MgmtTestHelper.CreateArmClientWithMockAuth(host).GetSingletonTrackedResource(id).UpdateAsync(data); + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(true, response.Value.HasData); + Assert.AreEqual("Azure.ResourceManager.Models.Resources/singletonTrackedResources", response.Value.Data.ResourceType.ToString()); + Assert.AreEqual("valid2", response.Value.Data.Properties.Description); + Assert.AreEqual(ProvisioningState.Succeeded, response.Value.Data.Properties.ProvisioningState); + Assert.AreEqual("AzureSDK", response.Value.Data.SystemData.CreatedBy); + Assert.AreEqual(CreatedByType.User, response.Value.Data.SystemData.CreatedByType); + Assert.AreEqual("AzureSDK", response.Value.Data.SystemData.LastModifiedBy); + Assert.AreEqual(CreatedByType.User, response.Value.Data.SystemData.LastModifiedByType); + }); + + [Test] + public Task Azure_ResourceManager_Models_Resources_SingletonTrackedResource_getByResourceGroup() => Test(async (host) => + { + var id = SingletonTrackedResource.CreateResourceIdentifier(Guid.Empty.ToString(), "test-rg"); + var response = await MgmtTestHelper.CreateArmClientWithMockAuth(host).GetSingletonTrackedResource(id).GetAsync(); + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(true, response.Value.HasData); + Assert.AreEqual("Azure.ResourceManager.Models.Resources/singletonTrackedResources", response.Value.Data.ResourceType.ToString()); + Assert.AreEqual("valid", response.Value.Data.Properties.Description); + Assert.AreEqual(ProvisioningState.Succeeded, response.Value.Data.Properties.ProvisioningState); + Assert.AreEqual("AzureSDK", response.Value.Data.SystemData.CreatedBy); + Assert.AreEqual(CreatedByType.User, response.Value.Data.SystemData.CreatedByType); + Assert.AreEqual("AzureSDK", response.Value.Data.SystemData.LastModifiedBy); + Assert.AreEqual(CreatedByType.User, response.Value.Data.SystemData.LastModifiedByType); + }); } } diff --git a/test/CadlRanchProjects.Tests/special-headers/conditional-request.cs b/test/CadlRanchProjects.Tests/special-headers/conditional-request.cs index b793e11dfaf..c082fdc4f4e 100644 --- a/test/CadlRanchProjects.Tests/special-headers/conditional-request.cs +++ b/test/CadlRanchProjects.Tests/special-headers/conditional-request.cs @@ -3,6 +3,7 @@ using NUnit.Framework; using System.Threading.Tasks; using SpecialHeaders.ConditionalRequest; +using System; namespace CadlRanchProjects.Tests { @@ -22,5 +23,26 @@ public Task Special_Headers_Conditional_Request_PostIfNoneMatch() => Test(async Response response = await new ConditionalRequestClient(host, null).PostIfNoneMatchAsync(ifNoneMatch); Assert.AreEqual(204, response.Status); }); + + [Test] + public Task Special_Headers_Conditional_Request_HeadIfModifiedSince() => Test(async (host) => + { + DateTimeOffset ifModifiedSince = DateTimeOffset.Parse("Fri, 26 Aug 2022 14:38:00 GMT"); + Response response = await new ConditionalRequestClient(host, null).HeadIfModifiedSinceAsync(new RequestConditions() + { + IfModifiedSince = ifModifiedSince + }); + Assert.AreEqual(204, response.Status); + }); + [Test] + public Task Special_Headers_Conditional_Request_PostIfUnmodifiedSince() => Test(async (host) => + { + DateTimeOffset ifUnmodifiedSince = DateTimeOffset.Parse("Fri, 26 Aug 2022 14:38:00 GMT"); + Response response = await new ConditionalRequestClient(host, null).PostIfUnmodifiedSinceAsync(new RequestConditions() + { + IfUnmodifiedSince = ifUnmodifiedSince + }); + Assert.AreEqual(204, response.Status); + }); } } diff --git a/test/CadlRanchProjects/encode/numeric/Configuration.json b/test/CadlRanchProjects/encode/numeric/Configuration.json new file mode 100644 index 00000000000..6a085843fd4 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/Configuration.json @@ -0,0 +1,11 @@ +{ + "output-folder": ".", + "namespace": "Encode.Numeric", + "library-name": "Encode.Numeric", + "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/encode/numeric/Encode.Numeric.sln b/test/CadlRanchProjects/encode/numeric/Encode.Numeric.sln new file mode 100644 index 00000000000..1bb8a08401a --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/Encode.Numeric.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}") = "Encode.Numeric", "src\Encode.Numeric.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Encode.Numeric.Tests", "tests\Encode.Numeric.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/encode/numeric/src/Encode.Numeric.csproj b/test/CadlRanchProjects/encode/numeric/src/Encode.Numeric.csproj new file mode 100644 index 00000000000..8b4ca11f496 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Encode.Numeric.csproj @@ -0,0 +1,19 @@ + + + This is the Encode.Numeric client library for developing .NET applications with rich experience. + Azure SDK Code Generation Encode.Numeric for Azure Data Plane + 1.0.0-beta.1 + Encode.Numeric + $(RequiredTargetFrameworks) + true + + + + + + + + + + + diff --git a/test/CadlRanchProjects/encode/numeric/src/Generated/Docs/Property.xml b/test/CadlRanchProjects/encode/numeric/src/Generated/Docs/Property.xml new file mode 100644 index 00000000000..375602c189e --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/Docs/Property.xml @@ -0,0 +1,281 @@ + + + + + +This sample shows how to call SafeintAsStringAsync. + response = await client.SafeintAsStringAsync(value); +]]> +This sample shows how to call SafeintAsStringAsync with all parameters. + response = await client.SafeintAsStringAsync(value); +]]> + + + +This sample shows how to call SafeintAsString. + response = client.SafeintAsString(value); +]]> +This sample shows how to call SafeintAsString with all parameters. + response = client.SafeintAsString(value); +]]> + + + +This sample shows how to call SafeintAsStringAsync and parse the result. + +This sample shows how to call SafeintAsStringAsync with all request content and parse the result. + + + + +This sample shows how to call SafeintAsString and parse the result. + +This sample shows how to call SafeintAsString with all request content and parse the result. + + + + +This sample shows how to call Uint32AsStringOptionalAsync. + response = await client.Uint32AsStringOptionalAsync(value); +]]> +This sample shows how to call Uint32AsStringOptionalAsync with all parameters. + response = await client.Uint32AsStringOptionalAsync(value); +]]> + + + +This sample shows how to call Uint32AsStringOptional. + response = client.Uint32AsStringOptional(value); +]]> +This sample shows how to call Uint32AsStringOptional with all parameters. + response = client.Uint32AsStringOptional(value); +]]> + + + +This sample shows how to call Uint32AsStringOptionalAsync and parse the result. + +This sample shows how to call Uint32AsStringOptionalAsync with all request content and parse the result. + + + + +This sample shows how to call Uint32AsStringOptional and parse the result. + +This sample shows how to call Uint32AsStringOptional with all request content and parse the result. + + + + +This sample shows how to call Uint8AsStringAsync. + response = await client.Uint8AsStringAsync(value); +]]> +This sample shows how to call Uint8AsStringAsync with all parameters. + response = await client.Uint8AsStringAsync(value); +]]> + + + +This sample shows how to call Uint8AsString. + response = client.Uint8AsString(value); +]]> +This sample shows how to call Uint8AsString with all parameters. + response = client.Uint8AsString(value); +]]> + + + +This sample shows how to call Uint8AsStringAsync and parse the result. + +This sample shows how to call Uint8AsStringAsync with all request content and parse the result. + + + + +This sample shows how to call Uint8AsString and parse the result. + +This sample shows how to call Uint8AsString with all request content and parse the result. + + + + \ No newline at end of file diff --git a/test/CadlRanchProjects/encode/numeric/src/Generated/EncodeNumericClientBuilderExtensions.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/EncodeNumericClientBuilderExtensions.cs new file mode 100644 index 00000000000..87ff240061d --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/EncodeNumericClientBuilderExtensions.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 Encode.Numeric; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class EncodeNumericClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// The to use. + public static IAzureClientBuilder AddNumericClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilder + { + return builder.RegisterClientFactory((options) => new NumericClient(endpoint, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddNumericClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/Argument.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/Argument.cs new file mode 100644 index 00000000000..e9396659288 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/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 Encode.Numeric +{ + 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/encode/numeric/src/Generated/Internal/ChangeTrackingDictionary.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 00000000000..33ca4ac4d35 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Encode.Numeric +{ + internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull + { + private IDictionary _innerDictionary; + + public ChangeTrackingDictionary() + { + } + + public ChangeTrackingDictionary(IDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(dictionary); + } + + public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(); + foreach (var pair in dictionary) + { + _innerDictionary.Add(pair); + } + } + + public bool IsUndefined => _innerDictionary == null; + + public int Count => IsUndefined ? 0 : EnsureDictionary().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; + + public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; + + public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; + + public TValue this[TKey key] + { + get + { + if (IsUndefined) + { + throw new KeyNotFoundException(nameof(key)); + } + return EnsureDictionary()[key]; + } + set + { + EnsureDictionary()[key] = value; + } + } + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + public IEnumerator> GetEnumerator() + { + if (IsUndefined) + { + IEnumerator> enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureDictionary().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + EnsureDictionary().Add(item); + } + + public void Clear() + { + EnsureDictionary().Clear(); + } + + public bool Contains(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int index) + { + if (IsUndefined) + { + return; + } + EnsureDictionary().CopyTo(array, index); + } + + public bool Remove(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(item); + } + + public void Add(TKey key, TValue value) + { + EnsureDictionary().Add(key, value); + } + + public bool ContainsKey(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().ContainsKey(key); + } + + public bool Remove(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(key); + } + + public bool TryGetValue(TKey key, out TValue value) + { + if (IsUndefined) + { + value = default; + return false; + } + return EnsureDictionary().TryGetValue(key, out value); + } + + public IDictionary EnsureDictionary() + { + return _innerDictionary ??= new Dictionary(); + } + } +} diff --git a/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/ChangeTrackingList.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 00000000000..71869107e56 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/ChangeTrackingList.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Encode.Numeric +{ + internal class ChangeTrackingList : IList, IReadOnlyList + { + private IList _innerList; + + public ChangeTrackingList() + { + } + + public ChangeTrackingList(IList innerList) + { + if (innerList != null) + { + _innerList = innerList; + } + } + + public ChangeTrackingList(IReadOnlyList innerList) + { + if (innerList != null) + { + _innerList = innerList.ToList(); + } + } + + public bool IsUndefined => _innerList == null; + + public int Count => IsUndefined ? 0 : EnsureList().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; + + public T this[int index] + { + get + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + return EnsureList()[index]; + } + set + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList()[index] = value; + } + } + + public void Reset() + { + _innerList = null; + } + + public IEnumerator GetEnumerator() + { + if (IsUndefined) + { + IEnumerator enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureList().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(T item) + { + EnsureList().Add(item); + } + + public void Clear() + { + EnsureList().Clear(); + } + + public bool Contains(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Contains(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + if (IsUndefined) + { + return; + } + EnsureList().CopyTo(array, arrayIndex); + } + + public bool Remove(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Remove(item); + } + + public int IndexOf(T item) + { + if (IsUndefined) + { + return -1; + } + return EnsureList().IndexOf(item); + } + + public void Insert(int index, T item) + { + EnsureList().Insert(index, item); + } + + public void RemoveAt(int index) + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList().RemoveAt(index); + } + + public IList EnsureList() + { + return _innerList ??= new List(); + } + } +} diff --git a/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/ModelSerializationExtensions.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 00000000000..388b52afb51 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/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 Encode.Numeric +{ + 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/encode/numeric/src/Generated/Internal/Optional.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/Optional.cs new file mode 100644 index 00000000000..b44d92ad2bc --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/Optional.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; + +namespace Encode.Numeric +{ + internal static class Optional + { + public static bool IsCollectionDefined(IEnumerable collection) + { + return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined); + } + + public static bool IsCollectionDefined(IDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsCollectionDefined(IReadOnlyDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsDefined(T? value) + where T : struct + { + return value.HasValue; + } + + public static bool IsDefined(object value) + { + return value != null; + } + + public static bool IsDefined(JsonElement value) + { + return value.ValueKind != JsonValueKind.Undefined; + } + + public static bool IsDefined(string value) + { + return value != null; + } + } +} diff --git a/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/Utf8JsonRequestContent.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 00000000000..81d95311a69 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/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 Encode.Numeric +{ + 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/encode/numeric/src/Generated/Models/SafeintAsStringProperty.Serialization.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Models/SafeintAsStringProperty.Serialization.cs new file mode 100644 index 00000000000..894bf3024e4 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/Models/SafeintAsStringProperty.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 Encode.Numeric.Models +{ + public partial class SafeintAsStringProperty : 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(SafeintAsStringProperty)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("value"u8); + writer.WriteStringValue(Value.ToString()); + 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(); + } + + SafeintAsStringProperty 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(SafeintAsStringProperty)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSafeintAsStringProperty(document.RootElement, options); + } + + internal static SafeintAsStringProperty DeserializeSafeintAsStringProperty(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + long value = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("value"u8)) + { + value = long.Parse(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SafeintAsStringProperty(value, 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(SafeintAsStringProperty)} does not support writing '{options.Format}' format."); + } + } + + SafeintAsStringProperty 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 DeserializeSafeintAsStringProperty(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SafeintAsStringProperty)} 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 SafeintAsStringProperty FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeSafeintAsStringProperty(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/encode/numeric/src/Generated/Models/SafeintAsStringProperty.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Models/SafeintAsStringProperty.cs new file mode 100644 index 00000000000..2845e48c34e --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/Models/SafeintAsStringProperty.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Encode.Numeric.Models +{ + /// The SafeintAsStringProperty. + public partial class SafeintAsStringProperty + { + /// + /// 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 . + /// + public SafeintAsStringProperty(long value) + { + Value = value; + } + + /// Initializes a new instance of . + /// + /// Keeps track of any properties unknown to the library. + internal SafeintAsStringProperty(long value, IDictionary serializedAdditionalRawData) + { + Value = value; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SafeintAsStringProperty() + { + } + + /// Gets or sets the value. + public long Value { get; set; } + } +} diff --git a/test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint32AsStringProperty.Serialization.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint32AsStringProperty.Serialization.cs new file mode 100644 index 00000000000..6670620e383 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint32AsStringProperty.Serialization.cs @@ -0,0 +1,143 @@ +// 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 Encode.Numeric.Models +{ + public partial class Uint32AsStringProperty : 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(Uint32AsStringProperty)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Value)) + { + writer.WritePropertyName("value"u8); + writer.WriteObjectValue(Value, options); + } + 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(); + } + + Uint32AsStringProperty 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(Uint32AsStringProperty)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUint32AsStringProperty(document.RootElement, options); + } + + internal static Uint32AsStringProperty DeserializeUint32AsStringProperty(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + object value = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("value"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + value = property.Value.GetObject(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Uint32AsStringProperty(value, 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(Uint32AsStringProperty)} does not support writing '{options.Format}' format."); + } + } + + Uint32AsStringProperty 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 DeserializeUint32AsStringProperty(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Uint32AsStringProperty)} 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 Uint32AsStringProperty FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUint32AsStringProperty(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/encode/numeric/src/Generated/Models/Uint32AsStringProperty.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint32AsStringProperty.cs new file mode 100644 index 00000000000..5d0be7bddd4 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint32AsStringProperty.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Encode.Numeric.Models +{ + /// The Uint32AsStringProperty. + public partial class Uint32AsStringProperty + { + /// + /// 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 . + public Uint32AsStringProperty() + { + } + + /// Initializes a new instance of . + /// + /// Keeps track of any properties unknown to the library. + internal Uint32AsStringProperty(object value, IDictionary serializedAdditionalRawData) + { + Value = value; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Gets or sets the value. + public object Value { get; set; } + } +} diff --git a/test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint8AsStringProperty.Serialization.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint8AsStringProperty.Serialization.cs new file mode 100644 index 00000000000..1eaf2fc0ce7 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint8AsStringProperty.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 Encode.Numeric.Models +{ + public partial class Uint8AsStringProperty : 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(Uint8AsStringProperty)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("value"u8); + writer.WriteStringValue(Value.ToString()); + 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(); + } + + Uint8AsStringProperty 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(Uint8AsStringProperty)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUint8AsStringProperty(document.RootElement, options); + } + + internal static Uint8AsStringProperty DeserializeUint8AsStringProperty(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + byte value = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("value"u8)) + { + value = byte.Parse(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Uint8AsStringProperty(value, 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(Uint8AsStringProperty)} does not support writing '{options.Format}' format."); + } + } + + Uint8AsStringProperty 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 DeserializeUint8AsStringProperty(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Uint8AsStringProperty)} 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 Uint8AsStringProperty FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUint8AsStringProperty(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/encode/numeric/src/Generated/Models/Uint8AsStringProperty.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint8AsStringProperty.cs new file mode 100644 index 00000000000..ac370064fcc --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/Models/Uint8AsStringProperty.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Encode.Numeric.Models +{ + /// The Uint8AsStringProperty. + public partial class Uint8AsStringProperty + { + /// + /// 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 . + /// + public Uint8AsStringProperty(byte value) + { + Value = value; + } + + /// Initializes a new instance of . + /// + /// Keeps track of any properties unknown to the library. + internal Uint8AsStringProperty(byte value, IDictionary serializedAdditionalRawData) + { + Value = value; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Uint8AsStringProperty() + { + } + + /// Gets or sets the value. + public byte Value { get; set; } + } +} diff --git a/test/CadlRanchProjects/encode/numeric/src/Generated/NumericClient.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/NumericClient.cs new file mode 100644 index 00000000000..447d9fe8b41 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/NumericClient.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Encode.Numeric +{ + // Data plane generated client. + /// Test for encode decorator on integer. + public partial class NumericClient + { + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + + /// 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 NumericClient. + public NumericClient() : this(new Uri("http://localhost:3000"), new NumericClientOptions()) + { + } + + /// Initializes a new instance of NumericClient. + /// The to use. + /// The options for configuring the client. + /// is null. + public NumericClient(Uri endpoint, NumericClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + options ??= new NumericClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), Array.Empty(), new ResponseClassifier()); + _endpoint = endpoint; + } + + private Property _cachedProperty; + + /// Initializes a new instance of Property. + public virtual Property GetPropertyClient() + { + return Volatile.Read(ref _cachedProperty) ?? Interlocked.CompareExchange(ref _cachedProperty, new Property(ClientDiagnostics, _pipeline, _endpoint), null) ?? _cachedProperty; + } + } +} diff --git a/test/CadlRanchProjects/encode/numeric/src/Generated/NumericClientOptions.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/NumericClientOptions.cs new file mode 100644 index 00000000000..47e099bd1e2 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/NumericClientOptions.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using Azure.Core; + +namespace Encode.Numeric +{ + /// Client options for NumericClient. + public partial class NumericClientOptions : ClientOptions + { + } +} diff --git a/test/CadlRanchProjects/encode/numeric/src/Generated/Property.cs b/test/CadlRanchProjects/encode/numeric/src/Generated/Property.cs new file mode 100644 index 00000000000..dd9512a77fa --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/src/Generated/Property.cs @@ -0,0 +1,430 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; +using Encode.Numeric.Models; + +namespace Encode.Numeric +{ + // Data plane generated sub-client. + /// The Property sub-client. + public partial class Property + { + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + + /// 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 Property for mocking. + protected Property() + { + } + + /// Initializes a new instance of Property. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The to use. + internal Property(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Uri endpoint) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _endpoint = endpoint; + } + + /// Safeint as string. + /// The to use. + /// The cancellation token to use. + /// is null. + /// + public virtual async Task> SafeintAsStringAsync(SafeintAsStringProperty value, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(value, nameof(value)); + + using RequestContent content = value.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await SafeintAsStringAsync(content, context).ConfigureAwait(false); + return Response.FromValue(SafeintAsStringProperty.FromResponse(response), response); + } + + /// Safeint as string. + /// The to use. + /// The cancellation token to use. + /// is null. + /// + public virtual Response SafeintAsString(SafeintAsStringProperty value, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(value, nameof(value)); + + using RequestContent content = value.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = SafeintAsString(content, context); + return Response.FromValue(SafeintAsStringProperty.FromResponse(response), response); + } + + /// + /// [Protocol Method] Safeint as string. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// 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 response returned from the service. + /// + public virtual async Task SafeintAsStringAsync(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Property.SafeintAsString"); + scope.Start(); + try + { + using HttpMessage message = CreateSafeintAsStringRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Safeint as string. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// 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 response returned from the service. + /// + public virtual Response SafeintAsString(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Property.SafeintAsString"); + scope.Start(); + try + { + using HttpMessage message = CreateSafeintAsStringRequest(content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Uint 32 as string optional. + /// The to use. + /// The cancellation token to use. + /// is null. + /// + public virtual async Task> Uint32AsStringOptionalAsync(Uint32AsStringProperty value, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(value, nameof(value)); + + using RequestContent content = value.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await Uint32AsStringOptionalAsync(content, context).ConfigureAwait(false); + return Response.FromValue(Uint32AsStringProperty.FromResponse(response), response); + } + + /// Uint 32 as string optional. + /// The to use. + /// The cancellation token to use. + /// is null. + /// + public virtual Response Uint32AsStringOptional(Uint32AsStringProperty value, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(value, nameof(value)); + + using RequestContent content = value.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Uint32AsStringOptional(content, context); + return Response.FromValue(Uint32AsStringProperty.FromResponse(response), response); + } + + /// + /// [Protocol Method] Uint 32 as string optional. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// 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 response returned from the service. + /// + public virtual async Task Uint32AsStringOptionalAsync(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Property.Uint32AsStringOptional"); + scope.Start(); + try + { + using HttpMessage message = CreateUint32AsStringOptionalRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Uint 32 as string optional. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// 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 response returned from the service. + /// + public virtual Response Uint32AsStringOptional(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Property.Uint32AsStringOptional"); + scope.Start(); + try + { + using HttpMessage message = CreateUint32AsStringOptionalRequest(content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Uint 8 as string. + /// The to use. + /// The cancellation token to use. + /// is null. + /// + public virtual async Task> Uint8AsStringAsync(Uint8AsStringProperty value, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(value, nameof(value)); + + using RequestContent content = value.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await Uint8AsStringAsync(content, context).ConfigureAwait(false); + return Response.FromValue(Uint8AsStringProperty.FromResponse(response), response); + } + + /// Uint 8 as string. + /// The to use. + /// The cancellation token to use. + /// is null. + /// + public virtual Response Uint8AsString(Uint8AsStringProperty value, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(value, nameof(value)); + + using RequestContent content = value.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Uint8AsString(content, context); + return Response.FromValue(Uint8AsStringProperty.FromResponse(response), response); + } + + /// + /// [Protocol Method] Uint 8 as string. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// 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 response returned from the service. + /// + public virtual async Task Uint8AsStringAsync(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Property.Uint8AsString"); + scope.Start(); + try + { + using HttpMessage message = CreateUint8AsStringRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Uint 8 as string. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// 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 response returned from the service. + /// + public virtual Response Uint8AsString(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Property.Uint8AsString"); + scope.Start(); + try + { + using HttpMessage message = CreateUint8AsStringRequest(content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateSafeintAsStringRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/encode/numeric/property/safeint", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateUint32AsStringOptionalRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/encode/numeric/property/uint32", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateUint8AsStringRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/encode/numeric/property/uint8", false); + 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 _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + } +} diff --git a/test/CadlRanchProjects/encode/numeric/src/Properties/AssemblyInfo.cs b/test/CadlRanchProjects/encode/numeric/src/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..c46693a65f5 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/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("Encode.Numeric.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] diff --git a/test/CadlRanchProjects/encode/numeric/tests/Encode.Numeric.Tests.csproj b/test/CadlRanchProjects/encode/numeric/tests/Encode.Numeric.Tests.csproj new file mode 100644 index 00000000000..dfd0b1b0331 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/tests/Encode.Numeric.Tests.csproj @@ -0,0 +1,19 @@ + + + $(RequiredTargetFrameworks) + + $(NoWarn);CS1591 + + + + + + + + + + + + + + diff --git a/test/CadlRanchProjects/encode/numeric/tests/Generated/Samples/Samples_Property.cs b/test/CadlRanchProjects/encode/numeric/tests/Generated/Samples/Samples_Property.cs new file mode 100644 index 00000000000..5bc6e97e937 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/tests/Generated/Samples/Samples_Property.cs @@ -0,0 +1,333 @@ +// 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 Encode.Numeric.Models; +using NUnit.Framework; + +namespace Encode.Numeric.Samples +{ + public partial class Samples_Property + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Property_SafeintAsString_ShortVersion() + { + Property client = new NumericClient().GetPropertyClient(); + + using RequestContent content = RequestContent.Create(new + { + value = 1234L, + }); + Response response = client.SafeintAsString(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Property_SafeintAsString_ShortVersion_Async() + { + Property client = new NumericClient().GetPropertyClient(); + + using RequestContent content = RequestContent.Create(new + { + value = 1234L, + }); + Response response = await client.SafeintAsStringAsync(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Property_SafeintAsString_ShortVersion_Convenience() + { + Property client = new NumericClient().GetPropertyClient(); + + SafeintAsStringProperty value = new SafeintAsStringProperty(1234L); + Response response = client.SafeintAsString(value); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Property_SafeintAsString_ShortVersion_Convenience_Async() + { + Property client = new NumericClient().GetPropertyClient(); + + SafeintAsStringProperty value = new SafeintAsStringProperty(1234L); + Response response = await client.SafeintAsStringAsync(value); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Property_SafeintAsString_AllParameters() + { + Property client = new NumericClient().GetPropertyClient(); + + using RequestContent content = RequestContent.Create(new + { + value = 1234L, + }); + Response response = client.SafeintAsString(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Property_SafeintAsString_AllParameters_Async() + { + Property client = new NumericClient().GetPropertyClient(); + + using RequestContent content = RequestContent.Create(new + { + value = 1234L, + }); + Response response = await client.SafeintAsStringAsync(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Property_SafeintAsString_AllParameters_Convenience() + { + Property client = new NumericClient().GetPropertyClient(); + + SafeintAsStringProperty value = new SafeintAsStringProperty(1234L); + Response response = client.SafeintAsString(value); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Property_SafeintAsString_AllParameters_Convenience_Async() + { + Property client = new NumericClient().GetPropertyClient(); + + SafeintAsStringProperty value = new SafeintAsStringProperty(1234L); + Response response = await client.SafeintAsStringAsync(value); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Property_Uint32AsStringOptional_ShortVersion() + { + Property client = new NumericClient().GetPropertyClient(); + + using RequestContent content = RequestContent.Create(new object()); + Response response = client.Uint32AsStringOptional(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Property_Uint32AsStringOptional_ShortVersion_Async() + { + Property client = new NumericClient().GetPropertyClient(); + + using RequestContent content = RequestContent.Create(new object()); + Response response = await client.Uint32AsStringOptionalAsync(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Property_Uint32AsStringOptional_ShortVersion_Convenience() + { + Property client = new NumericClient().GetPropertyClient(); + + Uint32AsStringProperty value = new Uint32AsStringProperty(); + Response response = client.Uint32AsStringOptional(value); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Property_Uint32AsStringOptional_ShortVersion_Convenience_Async() + { + Property client = new NumericClient().GetPropertyClient(); + + Uint32AsStringProperty value = new Uint32AsStringProperty(); + Response response = await client.Uint32AsStringOptionalAsync(value); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Property_Uint32AsStringOptional_AllParameters() + { + Property client = new NumericClient().GetPropertyClient(); + + using RequestContent content = RequestContent.Create(new + { + value = new object(), + }); + Response response = client.Uint32AsStringOptional(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Property_Uint32AsStringOptional_AllParameters_Async() + { + Property client = new NumericClient().GetPropertyClient(); + + using RequestContent content = RequestContent.Create(new + { + value = new object(), + }); + Response response = await client.Uint32AsStringOptionalAsync(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Property_Uint32AsStringOptional_AllParameters_Convenience() + { + Property client = new NumericClient().GetPropertyClient(); + + Uint32AsStringProperty value = new Uint32AsStringProperty + { + Value = new object(), + }; + Response response = client.Uint32AsStringOptional(value); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Property_Uint32AsStringOptional_AllParameters_Convenience_Async() + { + Property client = new NumericClient().GetPropertyClient(); + + Uint32AsStringProperty value = new Uint32AsStringProperty + { + Value = new object(), + }; + Response response = await client.Uint32AsStringOptionalAsync(value); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Property_Uint8AsString_ShortVersion() + { + Property client = new NumericClient().GetPropertyClient(); + + using RequestContent content = RequestContent.Create(new + { + value = 123, + }); + Response response = client.Uint8AsString(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Property_Uint8AsString_ShortVersion_Async() + { + Property client = new NumericClient().GetPropertyClient(); + + using RequestContent content = RequestContent.Create(new + { + value = 123, + }); + Response response = await client.Uint8AsStringAsync(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Property_Uint8AsString_ShortVersion_Convenience() + { + Property client = new NumericClient().GetPropertyClient(); + + Uint8AsStringProperty value = new Uint8AsStringProperty(123); + Response response = client.Uint8AsString(value); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Property_Uint8AsString_ShortVersion_Convenience_Async() + { + Property client = new NumericClient().GetPropertyClient(); + + Uint8AsStringProperty value = new Uint8AsStringProperty(123); + Response response = await client.Uint8AsStringAsync(value); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Property_Uint8AsString_AllParameters() + { + Property client = new NumericClient().GetPropertyClient(); + + using RequestContent content = RequestContent.Create(new + { + value = 123, + }); + Response response = client.Uint8AsString(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Property_Uint8AsString_AllParameters_Async() + { + Property client = new NumericClient().GetPropertyClient(); + + using RequestContent content = RequestContent.Create(new + { + value = 123, + }); + Response response = await client.Uint8AsStringAsync(content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("value").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Property_Uint8AsString_AllParameters_Convenience() + { + Property client = new NumericClient().GetPropertyClient(); + + Uint8AsStringProperty value = new Uint8AsStringProperty(123); + Response response = client.Uint8AsString(value); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Property_Uint8AsString_AllParameters_Convenience_Async() + { + Property client = new NumericClient().GetPropertyClient(); + + Uint8AsStringProperty value = new Uint8AsStringProperty(123); + Response response = await client.Uint8AsStringAsync(value); + } + } +} diff --git a/test/CadlRanchProjects/encode/numeric/tspCodeModel.json b/test/CadlRanchProjects/encode/numeric/tspCodeModel.json new file mode 100644 index 00000000000..cc15989bf39 --- /dev/null +++ b/test/CadlRanchProjects/encode/numeric/tspCodeModel.json @@ -0,0 +1,518 @@ +{ + "$id": "1", + "Name": "Encode.Numeric", + "ApiVersions": [], + "Enums": [], + "Models": [ + { + "$id": "2", + "kind": "model", + "name": "SafeintAsStringProperty", + "crossLanguageDefinitionId": "Encode.Numeric.Property.SafeintAsStringProperty", + "usage": "Input,Output,Json", + "decorators": [], + "properties": [ + { + "$id": "3", + "kind": "property", + "name": "value", + "serializedName": "value", + "type": { + "$id": "4", + "kind": "safeint", + "name": "safeint", + "encode": "string", + "crossLanguageDefinitionId": "TypeSpec.safeint", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "decorators": [], + "crossLanguageDefinitionId": "Encode.Numeric.Property.SafeintAsStringProperty.value" + } + ] + }, + { + "$id": "5", + "kind": "model", + "name": "Uint32AsStringProperty", + "crossLanguageDefinitionId": "Encode.Numeric.Property.Uint32AsStringProperty", + "usage": "Input,Output,Json", + "decorators": [], + "properties": [ + { + "$id": "6", + "kind": "property", + "name": "value", + "serializedName": "value", + "type": { + "$id": "7", + "kind": "uint32", + "name": "uint32", + "encode": "string", + "crossLanguageDefinitionId": "TypeSpec.uint32", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "decorators": [], + "crossLanguageDefinitionId": "Encode.Numeric.Property.Uint32AsStringProperty.value" + } + ] + }, + { + "$id": "8", + "kind": "model", + "name": "Uint8AsStringProperty", + "crossLanguageDefinitionId": "Encode.Numeric.Property.Uint8AsStringProperty", + "usage": "Input,Output,Json", + "decorators": [], + "properties": [ + { + "$id": "9", + "kind": "property", + "name": "value", + "serializedName": "value", + "type": { + "$id": "10", + "kind": "uint8", + "name": "uint8", + "encode": "string", + "crossLanguageDefinitionId": "TypeSpec.uint8", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "decorators": [], + "crossLanguageDefinitionId": "Encode.Numeric.Property.Uint8AsStringProperty.value" + } + ] + } + ], + "Clients": [ + { + "$id": "11", + "Name": "NumericClient", + "Description": "Test for encode decorator on integer.", + "Operations": [], + "Protocol": { + "$id": "12" + }, + "Parameters": [ + { + "$id": "13", + "Name": "endpoint", + "NameInRequest": "endpoint", + "Type": { + "$id": "14", + "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": "15", + "Type": { + "$id": "16", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "Value": "http://localhost:3000" + } + } + ], + "Decorators": [] + }, + { + "$id": "17", + "Name": "Property", + "Operations": [ + { + "$id": "18", + "Name": "safeintAsString", + "ResourceName": "Property", + "Accessibility": "public", + "Parameters": [ + { + "$id": "19", + "Name": "endpoint", + "NameInRequest": "endpoint", + "Type": { + "$id": "20", + "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": "21", + "Type": { + "$id": "22", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "Value": "http://localhost:3000" + } + }, + { + "$id": "23", + "Name": "contentType", + "NameInRequest": "Content-Type", + "Description": "Body parameter's content type. Known values are application/json", + "Type": { + "$id": "24", + "kind": "constant", + "valueType": { + "$id": "25", + "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": "26", + "Name": "accept", + "NameInRequest": "Accept", + "Type": { + "$id": "27", + "kind": "constant", + "valueType": { + "$id": "28", + "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": "29", + "Name": "value", + "NameInRequest": "value", + "Type": { + "$ref": "2" + }, + "Location": "Body", + "IsApiVersion": false, + "IsContentType": false, + "IsEndpoint": false, + "Explode": false, + "IsRequired": true, + "Kind": "Method", + "Decorators": [], + "SkipUrlEncoding": false + } + ], + "Responses": [ + { + "$id": "30", + "StatusCodes": [ + 200 + ], + "BodyType": { + "$ref": "2" + }, + "BodyMediaType": "Json", + "Headers": [], + "IsErrorResponse": false, + "ContentTypes": [ + "application/json" + ] + } + ], + "HttpMethod": "POST", + "RequestBodyMediaType": "Json", + "Uri": "{endpoint}", + "Path": "/encode/numeric/property/safeint", + "RequestMediaTypes": [ + "application/json" + ], + "BufferResponse": true, + "GenerateProtocolMethod": true, + "GenerateConvenienceMethod": true, + "CrossLanguageDefinitionId": "Encode.Numeric.Property.safeintAsString", + "Decorators": [] + }, + { + "$id": "31", + "Name": "uint32AsStringOptional", + "ResourceName": "Property", + "Accessibility": "public", + "Parameters": [ + { + "$ref": "19" + }, + { + "$id": "32", + "Name": "contentType", + "NameInRequest": "Content-Type", + "Description": "Body parameter's content type. Known values are application/json", + "Type": { + "$id": "33", + "kind": "constant", + "valueType": { + "$id": "34", + "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": "35", + "Name": "accept", + "NameInRequest": "Accept", + "Type": { + "$id": "36", + "kind": "constant", + "valueType": { + "$id": "37", + "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": "38", + "Name": "value", + "NameInRequest": "value", + "Type": { + "$ref": "5" + }, + "Location": "Body", + "IsApiVersion": false, + "IsContentType": false, + "IsEndpoint": false, + "Explode": false, + "IsRequired": true, + "Kind": "Method", + "Decorators": [], + "SkipUrlEncoding": false + } + ], + "Responses": [ + { + "$id": "39", + "StatusCodes": [ + 200 + ], + "BodyType": { + "$ref": "5" + }, + "BodyMediaType": "Json", + "Headers": [], + "IsErrorResponse": false, + "ContentTypes": [ + "application/json" + ] + } + ], + "HttpMethod": "POST", + "RequestBodyMediaType": "Json", + "Uri": "{endpoint}", + "Path": "/encode/numeric/property/uint32", + "RequestMediaTypes": [ + "application/json" + ], + "BufferResponse": true, + "GenerateProtocolMethod": true, + "GenerateConvenienceMethod": true, + "CrossLanguageDefinitionId": "Encode.Numeric.Property.uint32AsStringOptional", + "Decorators": [] + }, + { + "$id": "40", + "Name": "uint8AsString", + "ResourceName": "Property", + "Accessibility": "public", + "Parameters": [ + { + "$ref": "19" + }, + { + "$id": "41", + "Name": "contentType", + "NameInRequest": "Content-Type", + "Description": "Body parameter's content type. Known values are application/json", + "Type": { + "$id": "42", + "kind": "constant", + "valueType": { + "$id": "43", + "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": "44", + "Name": "accept", + "NameInRequest": "Accept", + "Type": { + "$id": "45", + "kind": "constant", + "valueType": { + "$id": "46", + "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": "47", + "Name": "value", + "NameInRequest": "value", + "Type": { + "$ref": "8" + }, + "Location": "Body", + "IsApiVersion": false, + "IsContentType": false, + "IsEndpoint": false, + "Explode": false, + "IsRequired": true, + "Kind": "Method", + "Decorators": [], + "SkipUrlEncoding": false + } + ], + "Responses": [ + { + "$id": "48", + "StatusCodes": [ + 200 + ], + "BodyType": { + "$ref": "8" + }, + "BodyMediaType": "Json", + "Headers": [], + "IsErrorResponse": false, + "ContentTypes": [ + "application/json" + ] + } + ], + "HttpMethod": "POST", + "RequestBodyMediaType": "Json", + "Uri": "{endpoint}", + "Path": "/encode/numeric/property/uint8", + "RequestMediaTypes": [ + "application/json" + ], + "BufferResponse": true, + "GenerateProtocolMethod": true, + "GenerateConvenienceMethod": true, + "CrossLanguageDefinitionId": "Encode.Numeric.Property.uint8AsString", + "Decorators": [] + } + ], + "Protocol": { + "$id": "49" + }, + "Parent": "NumericClient", + "Parameters": [ + { + "$ref": "19" + } + ], + "Decorators": [] + } + ] +}