diff --git a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/SimplePost.sln b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/SimplePost.sln index 936f70170f9..8b99758a6ad 100644 --- a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/SimplePost.sln +++ b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/SimplePost.sln @@ -1,10 +1,8 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29709.97 +# Visual Studio Version 17 +VisualStudioVersion = 17.11.35327.3 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimplePost", "src\SimplePost.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimplePost.Tests", "tests\SimplePost.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimplePost", "src\SimplePost.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -12,34 +10,10 @@ Global 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 diff --git a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/Argument.cs b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/Argument.cs index 432f4d3232f..ff5a451e9e1 100644 --- a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/Argument.cs +++ b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/Argument.cs @@ -3,127 +3,30 @@ // -#nullable disable +#nullable enable using System; -using System.Collections; -using System.Collections.Generic; -namespace SimplePost +namespace SimplePost; + +internal static class Argument { - internal static class Argument + public static void AssertNotNull(T value, string name) { - 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 is null) { - if (!value.HasValue) - { - throw new ArgumentNullException(name); - } + 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) + } + public static void AssertNotNullOrEmpty(string value, string name) + { + if (value is null) { - AssertNotNullOrEmpty(value, name); - return value; + throw new ArgumentNullException(name); } - - public static void AssertNull(T value, string name, string message = null) + if (value.Length == 0) { - if (value != null) - { - throw new ArgumentException(message ?? "Value must be null.", name); - } + throw new ArgumentException("Value cannot be an empty string.", name); } } } diff --git a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/CancellationTokenExtensions.cs b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/CancellationTokenExtensions.cs new file mode 100644 index 00000000000..c27cae478e7 --- /dev/null +++ b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/CancellationTokenExtensions.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Threading; +using Azure; + +namespace SimplePost; + +internal static class CancellationTokenExtensions +{ + public static RequestContext ToRequestContext(this CancellationToken cancellationToken) + { + if (cancellationToken == default) + { + return DefaultRequestContext; + } + + return new RequestContext() + { + CancellationToken = cancellationToken + }; + } + + private static RequestContext DefaultRequestContext => _defaultRequestContext ??= new(); + private static RequestContext? _defaultRequestContext; +} diff --git a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/ModelSerializationExtensions.cs b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/ModelSerializationExtensions.cs deleted file mode 100644 index 12c51b45884..00000000000 --- a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/ModelSerializationExtensions.cs +++ /dev/null @@ -1,398 +0,0 @@ -// 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 SimplePost -{ - 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/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/RequestContentHelper.cs b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/RequestContentHelper.cs deleted file mode 100644 index 700d82f650f..00000000000 --- a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/RequestContentHelper.cs +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace SimplePost -{ - internal static class RequestContentHelper - { - public static RequestContent FromEnumerable(IEnumerable enumerable) - where T : notnull - { - Utf8JsonRequestContent content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteStartArray(); - foreach (var item in enumerable) - { - content.JsonWriter.WriteObjectValue(item, ModelSerializationExtensions.WireOptions); - } - content.JsonWriter.WriteEndArray(); - - return content; - } - - public static RequestContent FromEnumerable(IEnumerable enumerable) - { - Utf8JsonRequestContent content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteStartArray(); - foreach (var item in enumerable) - { - if (item == null) - { - content.JsonWriter.WriteNullValue(); - } - else - { -#if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(item); -#else - using (JsonDocument document = JsonDocument.Parse(item)) - { - JsonSerializer.Serialize(content.JsonWriter, document.RootElement); - } -#endif - } - } - content.JsonWriter.WriteEndArray(); - - return content; - } - - public static RequestContent FromEnumerable(ReadOnlySpan span) - where T : notnull - { - Utf8JsonRequestContent content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteStartArray(); - for (int i = 0; i < span.Length; i++) - { - content.JsonWriter.WriteObjectValue(span[i], ModelSerializationExtensions.WireOptions); - } - content.JsonWriter.WriteEndArray(); - - return content; - } - - public static RequestContent FromDictionary(IDictionary dictionary) - where TValue : notnull - { - Utf8JsonRequestContent content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteStartObject(); - foreach (var item in dictionary) - { - content.JsonWriter.WritePropertyName(item.Key); - content.JsonWriter.WriteObjectValue(item.Value, ModelSerializationExtensions.WireOptions); - } - content.JsonWriter.WriteEndObject(); - - return content; - } - - public static RequestContent FromDictionary(IDictionary dictionary) - { - Utf8JsonRequestContent content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteStartObject(); - foreach (var item in dictionary) - { - content.JsonWriter.WritePropertyName(item.Key); - if (item.Value == null) - { - content.JsonWriter.WriteNullValue(); - } - else - { -#if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(content.JsonWriter, document.RootElement); - } -#endif - } - } - content.JsonWriter.WriteEndObject(); - - return content; - } - - public static RequestContent FromObject(object value) - { - Utf8JsonRequestContent content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(value, ModelSerializationExtensions.WireOptions); - return content; - } - - public static RequestContent FromObject(BinaryData value) - { - Utf8JsonRequestContent content = new Utf8JsonRequestContent(); -#if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(value); -#else - using (JsonDocument document = JsonDocument.Parse(value)) - { - JsonSerializer.Serialize(content.JsonWriter, document.RootElement); - } -#endif - return content; - } - } -} diff --git a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/Utf8JsonRequestContent.cs b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/Utf8JsonRequestContent.cs deleted file mode 100644 index 6ff0dbadf09..00000000000 --- a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/Internal/Utf8JsonRequestContent.cs +++ /dev/null @@ -1,55 +0,0 @@ -// 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 SimplePost -{ - 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/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/SimplePostClient.cs b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/SimplePostClient.cs index 66634e7d633..cbddf3a5ecc 100644 --- a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/SimplePostClient.cs +++ b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/SimplePostClient.cs @@ -3,7 +3,7 @@ // -#nullable disable +#nullable enable using System; using System.Threading; @@ -12,184 +12,173 @@ using Azure.Core; using Azure.Core.Pipeline; -namespace SimplePost +namespace SimplePost; + +// Data plane generated client. +/// The SimplePost service client. +public partial class SimplePostClient { - // Data plane generated client. - /// The SimplePost service client. - public partial class SimplePostClient - { - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; + 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 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; + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; - /// Initializes a new instance of SimplePostClient for mocking. - protected SimplePostClient() - { - } + /// Initializes a new instance of SimplePostClient for mocking. + protected SimplePostClient() + { + _pipeline = default!; + _endpoint = default!; + ClientDiagnostics = default!; + } - /// Initializes a new instance of SimplePostClient. - /// Service host. - /// is null. - public SimplePostClient(Uri endpoint) : this(endpoint, new SimplePostClientOptions()) - { - } + /// Initializes a new instance of SimplePostClient. + /// Service host. + /// is null. + public SimplePostClient(Uri endpoint) : this(endpoint, new SimplePostClientOptions()) + { + } - /// Initializes a new instance of SimplePostClient. - /// Service host. - /// The options for configuring the client. - /// is null. - public SimplePostClient(Uri endpoint, SimplePostClientOptions options) - { - Argument.AssertNotNull(endpoint, nameof(endpoint)); - options ??= new SimplePostClientOptions(); + /// Initializes a new instance of SimplePostClient. + /// Service host. + /// The options for configuring the client. + /// is null. + public SimplePostClient(Uri endpoint, SimplePostClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + options ??= new SimplePostClientOptions(); - ClientDiagnostics = new ClientDiagnostics(options, true); - _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), Array.Empty(), new ResponseClassifier()); - _endpoint = endpoint; - } + ClientDiagnostics = new ClientDiagnostics(options, true); + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), Array.Empty(), new ResponseClassifier()); + _endpoint = endpoint; + } - /// Create. - /// The to use. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// - public virtual async Task> CreateAsync(string content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(content, nameof(content)); + /// Create. + /// The to use. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> CreateAsync(string content, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(content, nameof(content)); - using RequestContent content0 = RequestContentHelper.FromObject(content); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateAsync(content0, context).ConfigureAwait(false); - return Response.FromValue(response.Content.ToObjectFromJson(), response); - } + using RequestContent content0 = RequestContent.Create(content); + Response response = await CreateAsync(content0, cancellationToken.ToRequestContext()).ConfigureAwait(false); + return Response.FromValue(response.Content.ToObjectFromJson()!, response); + } - /// Create. - /// The to use. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// - public virtual Response Create(string content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(content, nameof(content)); + /// Create. + /// The to use. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response Create(string content, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(content, nameof(content)); - using RequestContent content0 = RequestContentHelper.FromObject(content); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = Create(content0, context); - return Response.FromValue(response.Content.ToObjectFromJson(), response); - } + using RequestContent content0 = RequestContent.Create(content); + Response response = Create(content0, cancellationToken.ToRequestContext()); + return Response.FromValue(response.Content.ToObjectFromJson()!, response); + } + + /// + /// [Protocol Method] Create. + /// + /// + /// + /// 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 CreateAsync(RequestContent content, RequestContext? context = null) + { + Argument.AssertNotNull(content, nameof(content)); - /// - /// [Protocol Method] Create. - /// - /// - /// - /// 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 CreateAsync(RequestContent content, RequestContext context = null) + using var scope = ClientDiagnostics.CreateScope("SimplePostClient.Create"); + scope.Start(); + try { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = ClientDiagnostics.CreateScope("SimplePostClient.Create"); - scope.Start(); - try - { - using HttpMessage message = CreateCreateRequest(content, context); - return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } + using HttpMessage message = CreateCreateRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } - - /// - /// [Protocol Method] Create. - /// - /// - /// - /// 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 Create(RequestContent content, RequestContext context = null) + catch (Exception e) { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = ClientDiagnostics.CreateScope("SimplePostClient.Create"); - scope.Start(); - try - { - using HttpMessage message = CreateCreateRequest(content, context); - return _pipeline.ProcessMessage(message, context); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } + scope.Failed(e); + throw; } + } + + /// + /// [Protocol Method] Create. + /// + /// + /// + /// 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 Create(RequestContent content, RequestContext? context = null) + { + Argument.AssertNotNull(content, nameof(content)); - internal HttpMessage CreateCreateRequest(RequestContent content, RequestContext context) + using var scope = ClientDiagnostics.CreateScope("SimplePostClient.Create"); + scope.Start(); + try { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - request.Content = content; - return message; + using HttpMessage message = CreateCreateRequest(content, context); + return _pipeline.ProcessMessage(message, context); } - - private static RequestContext DefaultRequestContext = new RequestContext(); - internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + catch (Exception e) { - if (!cancellationToken.CanBeCanceled) - { - return DefaultRequestContext; - } - - return new RequestContext() { CancellationToken = cancellationToken }; + scope.Failed(e); + throw; } + } - private static ResponseClassifier _responseClassifier200; - private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + private HttpMessage CreateCreateRequest(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("/", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; } + + private static ResponseClassifier? _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); } diff --git a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/SimplePostClientBuilderExtensions.cs b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/SimplePostClientBuilderExtensions.cs index 9dba2310056..ae5b1c9599f 100644 --- a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/SimplePostClientBuilderExtensions.cs +++ b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/SimplePostClientBuilderExtensions.cs @@ -3,33 +3,32 @@ // -#nullable disable +#nullable enable using System; using Azure.Core.Extensions; using SimplePost; -namespace Microsoft.Extensions.Azure +namespace Microsoft.Extensions.Azure; + +/// Extension methods to add to client builder. +public static partial class SimplePostClientBuilderExtensions { - /// Extension methods to add to client builder. - public static partial class SimplePostClientBuilderExtensions + /// Registers a instance. + /// The builder to register with. + /// Service host. + public static IAzureClientBuilder AddSimplePostClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilder { - /// Registers a instance. - /// The builder to register with. - /// Service host. - public static IAzureClientBuilder AddSimplePostClient(this TBuilder builder, Uri endpoint) - where TBuilder : IAzureClientFactoryBuilder - { - return builder.RegisterClientFactory((options) => new SimplePostClient(endpoint, options)); - } + return builder.RegisterClientFactory((options) => new SimplePostClient(endpoint, options)); + } - /// Registers a instance. - /// The builder to register with. - /// The configuration values. - public static IAzureClientBuilder AddSimplePostClient(this TBuilder builder, TConfiguration configuration) - where TBuilder : IAzureClientFactoryBuilderWithConfiguration - { - return builder.RegisterClientFactory(configuration); - } + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddSimplePostClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); } } diff --git a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/SimplePostClientOptions.cs b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/SimplePostClientOptions.cs index 96e60420599..1ed43612041 100644 --- a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/SimplePostClientOptions.cs +++ b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/Generated/SimplePostClientOptions.cs @@ -3,14 +3,13 @@ // -#nullable disable +#nullable enable using Azure.Core; -namespace SimplePost +namespace SimplePost; + +/// Client options for SimplePostClient. +public partial class SimplePostClientOptions : ClientOptions { - /// Client options for SimplePostClient. - public partial class SimplePostClientOptions : ClientOptions - { - } } diff --git a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/SimplePost.csproj b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/SimplePost.csproj index f4eebc27250..e78f784e9ca 100644 --- a/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/SimplePost.csproj +++ b/test/AzureClients/SimplePost/tsp-output/@azure-tools/typespec-csharp/src/SimplePost.csproj @@ -4,7 +4,7 @@ Azure SDK Code Generation SimplePost for Azure Data Plane 1.0.0-beta.1 SimplePost - $(RequiredTargetFrameworks) + netstandard2.0 true @@ -13,7 +13,7 @@ - - + +